blob: 8b78c5e4ddfb53b99e845b71aba3ad1084aa8a2f [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070017#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090018
19// Need to keep the log statements even in production builds
20// to enable VERBOSE logging dynamically.
21// You can enable VERBOSE logging as follows:
22// adb shell setprop log.tag.APM_AudioPolicyManager V
23#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070024
25//#define VERY_VERBOSE_LOGGING
26#ifdef VERY_VERBOSE_LOGGING
27#define ALOGVV ALOGV
28#else
29#define ALOGVV(a...) do { } while(0)
30#endif
31
Eric Laurent16c66dd2019-05-01 17:54:10 -070032#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070033#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000034#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070035#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080036#include <set>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080037#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110038#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070039
40#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010041#include <android/media/audio/common/AudioPort.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070042#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070043#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070044#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070045#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070046#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070047#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070048#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070049#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <utils/Log.h>
51
Eric Laurentd4692962014-05-05 18:13:44 -070052#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010053#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070054
Eric Laurent3b73df72014-03-11 09:06:29 -070055namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070056
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010057using android::media::audio::common::AudioDevice;
58using android::media::audio::common::AudioDeviceAddress;
59using android::media::audio::common::AudioPortDeviceExt;
60using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000061using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070062
Eric Laurentdc462862016-07-19 12:29:53 -070063//FIXME: workaround for truncated touch sounds
64// to be removed when the problem is handled by system UI
65#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070066
67// Largest difference in dB on earpiece in call between the voice volume and another
68// media / notification / system volume.
69constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
70
Mikhail Naganov15be9d22017-11-08 14:18:13 +110071// Compressed formats for MSD module, ordered from most preferred to least preferred.
Dean Wheatley8bee85a2021-02-10 16:02:23 +110072static const std::vector<audio_format_t> msdCompressedFormatsOrder = {{
73 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Mikhail Naganov15be9d22017-11-08 14:18:13 +110074 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_16_BIT }};
75// Channel masks for MSD module, 3D > 2D > 1D ordering (most preferred to least preferred).
Dean Wheatley8bee85a2021-02-10 16:02:23 +110076static const std::vector<audio_channel_mask_t> msdSurroundChannelMasksOrder = {{
Mikhail Naganov15be9d22017-11-08 14:18:13 +110077 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
78 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
79 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
80
jiabin06e4bab2019-07-29 10:13:34 -070081template <typename T>
82bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
83{
84 if (left.size() != right.size()) {
85 return false;
86 }
87 for (size_t index = 0; index < right.size(); index++) {
88 if (left[index] != right[index]) {
89 return false;
90 }
91 }
92 return true;
93}
94
95template <typename T>
96bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
97{
98 return !(left == right);
99}
100
Eric Laurente552edb2014-03-10 17:42:56 -0700101// ----------------------------------------------------------------------------
102// AudioPolicyInterface implementation
103// ----------------------------------------------------------------------------
104
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100105status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
106 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
107 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800108 nextAudioPortGeneration();
109 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800110}
111
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100112status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
113 audio_policy_dev_state_t state,
114 const char* device_address,
115 const char* device_name,
116 audio_format_t encodedFormat) {
117 media::AudioPort aidlPort;
118 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
119 status == OK) {
120 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
121 } else {
122 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
123 return status;
124 }
125}
126
François Gaffie11d30102018-11-02 16:09:09 +0100127void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
128 audio_policy_dev_state_t state)
François Gaffie44481e72016-04-20 07:49:57 +0200129{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000130 audio_port_v7 devicePort;
131 device->toAudioPort(&devicePort);
132 if (status_t status = mpClientInterface->setDeviceConnectedState(
133 &devicePort, state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
134 status != OK) {
135 ALOGE("Error %d while setting connected state for device %s", status,
136 device->getDeviceTypeAddr().toString(false).c_str());
137 }
François Gaffie44481e72016-04-20 07:49:57 +0200138}
139
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100140status_t AudioPolicyManager::setDeviceConnectionStateInt(
141 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
142 audio_format_t encodedFormat) {
143 // TODO: b/211601178 Forward 'port' to Audio HAL via mHwModules. For now, only device_type,
144 // device_address and device_name are forwarded.
145 if (port.ext.getTag() != AudioPortExt::device) {
146 return BAD_VALUE;
147 }
148 audio_devices_t device_type;
149 std::string device_address;
150 if (status_t status = aidl2legacy_AudioDevice_audio_device(
151 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
152 status != OK) {
153 return status;
154 };
155 const char* device_name = port.name.c_str();
156 // connect/disconnect only 1 device at a time
157 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
158 return BAD_VALUE;
159
160 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
161 device_type, device_address.c_str(), device_name, encodedFormat,
162 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
163 return device ? setDeviceConnectionStateInt(device, state) : INVALID_OPERATION;
164}
165
François Gaffie11d30102018-11-02 16:09:09 +0100166status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800167 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100168 const char* device_address,
169 const char* device_name,
170 audio_format_t encodedFormat) {
171 media::AudioPort aidlPort;
172 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
173 status == OK) {
174 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
175 } else {
176 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
177 return status;
178 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700179}
Paul McLeane743a472015-01-28 11:07:31 -0800180
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700181status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
182 audio_policy_dev_state_t state)
183{
Eric Laurente552edb2014-03-10 17:42:56 -0700184 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700185 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700186 SortedVector <audio_io_handle_t> outputs;
187
François Gaffie11d30102018-11-02 16:09:09 +0100188 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700189
Eric Laurente552edb2014-03-10 17:42:56 -0700190 // save a copy of the opened output descriptors before any output is opened or closed
191 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
192 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100193
194 bool wasLeUnicastActive = isLeUnicastActive();
195
Eric Laurente552edb2014-03-10 17:42:56 -0700196 switch (state)
197 {
198 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800199 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700200 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100201 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700202 return INVALID_OPERATION;
203 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800204 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700205 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700206
Eric Laurente552edb2014-03-10 17:42:56 -0700207 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200208 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700209 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700210 }
211
François Gaffie44481e72016-04-20 07:49:57 +0200212 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
213 // parameters on newly connected devices (instead of opening the outputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100214 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200215
François Gaffie11d30102018-11-02 16:09:09 +0100216 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
217 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200218
Francois Gaffie716e1432019-01-14 16:58:59 +0100219 mHwModules.cleanUpForDevice(device);
220
François Gaffie11d30102018-11-02 16:09:09 +0100221 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700222 return INVALID_OPERATION;
223 }
François Gaffie2110e042015-03-24 08:41:51 +0100224
jiabin1c4794b2020-05-05 10:08:05 -0700225 // Populate encapsulation information when a output device is connected.
226 device->setEncapsulationInfoFromHal(mpClientInterface);
227
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700228 // outputs should never be empty here
229 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
230 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100231 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800232
Eric Laurent3ae5f312015-02-03 17:12:08 -0800233 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700234 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700235 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700236 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100237 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700238 return INVALID_OPERATION;
239 }
240
François Gaffie11d30102018-11-02 16:09:09 +0100241 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700242
Paul McLeane743a472015-01-28 11:07:31 -0800243 // Send Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100244 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700245
Eric Laurente552edb2014-03-10 17:42:56 -0700246 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100247 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700248
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100249 mOutputs.clearSessionRoutesForDevice(device);
250
François Gaffie11d30102018-11-02 16:09:09 +0100251 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100252
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800253 // Reset active device codec
254 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
255
Kriti Dangef6be8f2020-11-05 11:58:19 +0100256 // remove device from mReportedFormatsMap cache
257 mReportedFormatsMap.erase(device);
258
Eric Laurente552edb2014-03-10 17:42:56 -0700259 } break;
260
261 default:
François Gaffie11d30102018-11-02 16:09:09 +0100262 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700263 return BAD_VALUE;
264 }
265
Eric Laurent736a1022019-03-27 18:28:46 -0700266 // Propagate device availability to Engine
267 setEngineDeviceConnectionState(device, state);
268
Eric Laurentae970022019-01-29 14:25:04 -0800269 // No need to evaluate playback routing when connecting a remote submix
270 // output device used by a dynamic policy of type recorder as no
271 // playback use case is affected.
272 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700273 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800274 for (audio_io_handle_t output : outputs) {
275 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800276 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
277 if (policyMix != nullptr
278 && policyMix->mMixType == MIX_TYPE_RECORDERS
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700279 && device->address() == policyMix->mDeviceAddress.string()) {
Eric Laurentae970022019-01-29 14:25:04 -0800280 doCheckForDeviceAndOutputChanges = false;
281 break;
282 }
283 }
284 }
285
286 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700287 // outputs must be closed after checkOutputForAllStrategies() is executed
288 if (!outputs.isEmpty()) {
289 for (audio_io_handle_t output : outputs) {
290 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100291 // close unused outputs after device disconnection or direct outputs that have
292 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200293 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200294 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
295 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200296 (desc->mDirectOpenCount == 0))
297 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
298 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200299 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700300 closeOutput(output);
301 }
Eric Laurente552edb2014-03-10 17:42:56 -0700302 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700303 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
304 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700305 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700306 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800307 };
308
309 if (doCheckForDeviceAndOutputChanges) {
310 checkForDeviceAndOutputChanges(checkCloseOutputs);
311 } else {
312 checkCloseOutputs();
313 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100314 (void)updateCallRouting(false /*fromCache*/);
jiabinbce0c1d2020-10-05 11:20:18 -0700315 std::vector<audio_io_handle_t> outputsToReopen;
François Gaffie11d30102018-11-02 16:09:09 +0100316 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700317 const DeviceVector activeMediaDevices =
318 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700319 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700320 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530321 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
322 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100323 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700324 // do not force device change on duplicated output because if device is 0, it will
325 // also force a device 0 for the two outputs it is duplicated to which may override
326 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100327 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100328 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700329 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700330 // always force when disconnecting (a non-duplicated device)
331 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
François Gaffie11d30102018-11-02 16:09:09 +0100332 setOutputDevices(desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700333 }
jiabinbce0c1d2020-10-05 11:20:18 -0700334 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000335 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700336 desc->supportsDevicesForPlayback(activeMediaDevices)) {
337 // Reopen the output to query the dynamic profiles when there is not active
338 // clients or all active clients will be rerouted. Otherwise, set the flag
339 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
340 // can be reopened to query dynamic profiles when all clients are inactive.
341 if (areAllActiveTracksRerouted(desc)) {
342 outputsToReopen.push_back(mOutputs.keyAt(i));
343 } else {
344 desc->mPendingReopenToQueryProfiles = true;
345 }
346 }
347 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
348 // Clear the flag that previously set for re-querying profiles.
349 desc->mPendingReopenToQueryProfiles = false;
350 }
351 }
352 for (const auto& output : outputsToReopen) {
353 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
354 closeOutput(output);
355 openOutputWithProfileAndDevice(desc->mProfile, activeMediaDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700356 }
357
Eric Laurentd60560a2015-04-10 11:31:20 -0700358 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100359 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700360 }
361
Eric Laurent96d1dda2022-03-14 17:14:19 +0100362 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
363
Eric Laurent72aa32f2014-05-30 18:51:48 -0700364 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700365 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700366 } // end if is output device
367
Eric Laurente552edb2014-03-10 17:42:56 -0700368 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700369 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100370 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700371 switch (state)
372 {
373 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700374 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700375 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100376 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700377 return INVALID_OPERATION;
378 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700379
380 if (mAvailableInputDevices.add(device) < 0) {
381 return NO_MEMORY;
382 }
383
François Gaffie44481e72016-04-20 07:49:57 +0200384 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
385 // parameters on newly connected devices (instead of opening the inputs...)
François Gaffie11d30102018-11-02 16:09:09 +0100386 broadcastDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200387
Eric Laurent0dd51852019-04-19 18:18:58 -0700388 if (checkInputsForDevice(device, state) != NO_ERROR) {
389 mAvailableInputDevices.remove(device);
390
François Gaffie11d30102018-11-02 16:09:09 +0100391 broadcastDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
Francois Gaffie716e1432019-01-14 16:58:59 +0100392
393 mHwModules.cleanUpForDevice(device);
394
Eric Laurentd4692962014-05-05 18:13:44 -0700395 return INVALID_OPERATION;
396 }
397
Eric Laurentd4692962014-05-05 18:13:44 -0700398 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700399
400 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700401 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700402 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100403 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700404 return INVALID_OPERATION;
405 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700406
François Gaffie11d30102018-11-02 16:09:09 +0100407 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700408
409 // Set Disconnect to HALs
François Gaffie11d30102018-11-02 16:09:09 +0100410 broadcastDeviceConnectionState(device, state);
Paul McLean5c477aa2014-08-20 16:47:57 -0700411
François Gaffie11d30102018-11-02 16:09:09 +0100412 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700413
414 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100415
416 // remove device from mReportedFormatsMap cache
417 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700418 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700419
420 default:
François Gaffie11d30102018-11-02 16:09:09 +0100421 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700422 return BAD_VALUE;
423 }
424
Eric Laurent736a1022019-03-27 18:28:46 -0700425 // Propagate device availability to Engine
426 setEngineDeviceConnectionState(device, state);
427
Eric Laurent0dd51852019-04-19 18:18:58 -0700428 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700429 // As the input device list can impact the output device selection, update
430 // getDeviceForStrategy() cache
431 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700432
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100433 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200434 // Reconnect Audio Source
435 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
436 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
437 checkAudioSourceForAttributes(attributes);
438 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700439 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100440 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700441 }
442
Eric Laurentb52c1522014-05-20 11:27:36 -0700443 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700444 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700445 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700446
François Gaffie11d30102018-11-02 16:09:09 +0100447 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700448 return BAD_VALUE;
449}
450
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100451status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
452 const char* device_name,
453 media::AudioPort* aidlPort) {
454 DeviceDescriptorBase devDescr(device, device_address);
455 devDescr.setName(device_name);
456 return devDescr.writeToParcelable(aidlPort);
457}
458
Eric Laurent736a1022019-03-27 18:28:46 -0700459void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
460 audio_policy_dev_state_t state) {
461
462 // the Engine does not have to know about remote submix devices used by dynamic audio policies
463 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
464 return;
465 }
466 mEngine->setDeviceConnectionState(device, state);
467}
468
469
Eric Laurente0720872014-03-11 09:30:41 -0700470audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100471 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700472{
Eric Laurent634b7142016-04-20 13:48:02 -0700473 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800474 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
475 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700476 (strlen(device_address) != 0)/*matchAddress*/);
477
478 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100479 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700480 device, device_address);
481 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
482 }
François Gaffie53615e22015-03-19 09:24:12 +0100483
Eric Laurent3a4311c2014-03-17 12:00:47 -0700484 DeviceVector *deviceVector;
485
Eric Laurente552edb2014-03-10 17:42:56 -0700486 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700487 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700488 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700489 deviceVector = &mAvailableInputDevices;
490 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100491 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700492 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700493 }
Eric Laurent634b7142016-04-20 13:48:02 -0700494
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800495 return (deviceVector->getDevice(
496 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700497 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800498}
499
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800500status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
501 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800502 const char *device_name,
503 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800504{
505 status_t status;
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700506 String8 reply;
507 AudioParameter param;
508 int isReconfigA2dpSupported = 0;
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800509
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800510 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
511 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800512
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800513 // connect/disconnect only 1 device at a time
514 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
515
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800516 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700517 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800518 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800519 // Nothing to do: device is not connected
520 return NO_ERROR;
521 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800522 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800523
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700524 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800525 // configure codecs.
526 // Handle two specific cases by sending a set parameter to
527 // configure A2DP codecs. No need to toggle device state.
528 // Case 1: A2DP active device switches from primary to primary
529 // module
530 // Case 2: A2DP device config changes on primary module.
Francois Gaffiebce7cd42020-10-14 16:13:20 +0200531 if (audio_is_a2dp_out_device(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700532 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800533 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
534 if (availablePrimaryOutputDevices().contains(devDesc) &&
535 (module != 0 && module->getHandle() == primaryHandle)) {
536 reply = mpClientInterface->getParameters(
537 AUDIO_IO_HANDLE_NONE,
538 String8(AudioParameter::keyReconfigA2dpSupported));
539 AudioParameter repliedParameters(reply);
540 repliedParameters.getInt(
541 String8(AudioParameter::keyReconfigA2dpSupported), isReconfigA2dpSupported);
542 if (isReconfigA2dpSupported) {
543 const String8 key(AudioParameter::keyReconfigA2dp);
544 param.add(key, String8("true"));
545 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
546 devDesc->setEncodedFormat(encodedFormat);
547 return NO_ERROR;
548 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700549 }
550 }
cnx421bd2dcc42020-07-11 14:58:44 +0800551 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
552 for (size_t i = 0; i < mOutputs.size(); i++) {
553 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
554 // mute media strategies and delay device switch by the largest
555 // This avoid sending the music tail into the earpiece or headset.
556 setStrategyMute(musicStrategy, true, desc);
557 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
558 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
559 nullptr, true /*fromCache*/).types());
560 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800561 // Toggle the device state: UNAVAILABLE -> AVAILABLE
562 // This will force reading again the device configuration
563 status = setDeviceConnectionState(device,
564 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800565 device_address, device_name,
566 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800567 if (status != NO_ERROR) {
568 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
569 status);
570 return status;
571 }
572
573 status = setDeviceConnectionState(device,
574 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800575 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800576 if (status != NO_ERROR) {
577 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
578 status);
579 return status;
580 }
581
582 return NO_ERROR;
583}
584
Pattydd807582021-11-04 21:01:03 +0800585status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
586 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800587{
Pattydd807582021-11-04 21:01:03 +0800588 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800589 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800590 std::unordered_set<audio_format_t> formatSet;
591 sp<HwModule> primaryModule =
592 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700593 if (primaryModule == nullptr) {
594 ALOGE("%s() unable to get primary module", __func__);
595 return NO_INIT;
596 }
Pattydd807582021-11-04 21:01:03 +0800597
598 DeviceTypeSet audioDeviceSet;
599
600 switch(device) {
601 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
602 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
603 break;
604 case AUDIO_DEVICE_OUT_BLE_HEADSET:
605 audioDeviceSet = getAudioDeviceOutAllBleSet();
606 break;
607 default:
608 ALOGE("%s() device type 0x%08x not supported", __func__, device);
609 return BAD_VALUE;
610 }
611
jiabin9a3361e2019-10-01 09:38:30 -0700612 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800613 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800614 for (const auto& device : declaredDevices) {
615 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800616 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800617 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800618 return status;
619}
620
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100621DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
622{
623 DeviceVector rxSinkdevices{};
624 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
625 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
626 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
627 auto rxSinkDevice = rxSinkdevices.itemAt(0);
628 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
629 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
630 // retrieve Rx Source device descriptor
631 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
632 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
633
634 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
635 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
636 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
637 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
638 return DeviceVector(rxSinkDevice);
639 }
640 }
641 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
642 // the device returned is not necessarily reachable via this output
643 // (filter later by setOutputDevices())
644 return getNewOutputDevices(mPrimaryOutput, fromCache);
645}
646
647status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
648{
649 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL && hasPrimaryOutput()) {
650 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
651 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
652 }
653 return INVALID_OPERATION;
654}
655
656status_t AudioPolicyManager::updateCallRoutingInternal(
657 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700658{
659 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100660 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700661 uint32_t muteWaitMs = 0;
jiabin9a3361e2019-10-01 09:38:30 -0700662 if(!hasPrimaryOutput() ||
663 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100664 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700665 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100666 ALOG_ASSERT(!rxDevices.isEmpty(), "%s() no selected output device", __func__);
François Gaffie11d30102018-11-02 16:09:09 +0100667
Francois Gaffie716e1432019-01-14 16:58:59 +0100668 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100669 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100670 ALOG_ASSERT(txSourceDevice != 0, "%s() input selected device not available", __func__);
François Gaffiec005e562018-11-06 15:04:49 +0100671
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100672 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100673 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700674
Francois Gaffie601801d2021-06-22 13:27:39 +0200675 disconnectTelephonyAudioSource(mCallRxSourceClient);
676 disconnectTelephonyAudioSource(mCallTxSourceClient);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700677
François Gaffie9eb18552018-11-05 10:33:26 +0100678 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700679 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100680 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700681 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100682 // retrieve Rx Source and Tx Sink device descriptors
683 sp<DeviceDescriptor> rxSourceDevice =
684 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
685 String8(),
686 AUDIO_FORMAT_DEFAULT);
687 sp<DeviceDescriptor> txSinkDevice =
688 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
689 String8(),
690 AUDIO_FORMAT_DEFAULT);
691
692 // RX and TX Telephony device are declared by Primary Audio HAL
693 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
694 (telephonyRxModule->getHalVersionMajor() >= 3)) {
695 if (rxSourceDevice == 0 || txSinkDevice == 0) {
696 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100697 ALOGE("%s() no telephony Tx and/or RX device", __func__);
698 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100699 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100700 // createAudioPatchInternal now supports both HW / SW bridging
701 createRxPatch = true;
702 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100703 } else {
704 // If the RX device is on the primary HW module, then use legacy routing method for
705 // voice calls via setOutputDevice() on primary output.
706 // Otherwise, create two audio patches for TX and RX path.
707 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
708 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700709 // If the TX device is also on the primary HW module, setOutputDevice() will take care
710 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100711 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
712 (txSinkDevice != 0);
713 }
714 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
715 // Otherwise, create two audio patches for TX and RX path.
716 if (!createRxPatch) {
717 muteWaitMs = setOutputDevices(mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700718 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200719 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800720 // If the TX device is on the primary HW module but RX device is
721 // on other HW module, SinkMetaData of telephony input should handle it
722 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700723 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700724 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100725 // terminate active capture if on the same HW module as the call TX source device
726 // FIXME: would be better to refine to only inputs whose profile connects to the
727 // call TX device but this information is not in the audio patch and logic here must be
728 // symmetric to the one in startInput()
729 for (const auto& activeDesc : mInputs.getActiveInputs()) {
730 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
731 closeActiveClients(activeDesc);
732 }
733 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200734 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800735 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100736 if (waitMs != nullptr) {
737 *waitMs = muteWaitMs;
738 }
739 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800740}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700741
Mikhail Naganov100f0122018-11-29 11:22:16 -0800742bool AudioPolicyManager::isDeviceOfModule(
743 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
744 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
745 if (module != 0) {
746 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
747 .indexOf(devDesc) != NAME_NOT_FOUND
748 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
749 .indexOf(devDesc) != NAME_NOT_FOUND;
750 }
751 return false;
752}
753
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200754void AudioPolicyManager::connectTelephonyRxAudioSource()
755{
Francois Gaffie601801d2021-06-22 13:27:39 +0200756 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200757 const struct audio_port_config source = {
758 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
759 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
760 };
761 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Francois Gaffie601801d2021-06-22 13:27:39 +0200762 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
763 ALOGE_IF(mCallRxSourceClient == nullptr,
764 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200765}
766
Francois Gaffie601801d2021-06-22 13:27:39 +0200767void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200768{
Francois Gaffie601801d2021-06-22 13:27:39 +0200769 if (clientDesc == nullptr) {
770 return;
771 }
772 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
773 "%s error stopping audio source", __func__);
774 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200775}
776
777void AudioPolicyManager::connectTelephonyTxAudioSource(
778 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
779 uint32_t delayMs)
780{
Francois Gaffie601801d2021-06-22 13:27:39 +0200781 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200782 if (srcDevice == nullptr || sinkDevice == nullptr) {
783 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
784 return;
785 }
786 PatchBuilder patchBuilder;
787 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
788 ALOGV("%s between source %s and sink %s", __func__,
789 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200790 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200791 const audio_attributes_t aa = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
792 struct audio_port_config source = {};
793 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200794 mCallTxSourceClient = new InternalSourceClientDescriptor(
795 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200796 mCommunnicationStrategy, toVolumeSource(aa));
797 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
798 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200799 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
800 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200801 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
802 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200803 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200804 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200805}
806
Eric Laurente0720872014-03-11 09:30:41 -0700807void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700808{
809 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100810 // store previous phone state for management of sonification strategy below
811 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100812 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100813
814 if (mEngine->setPhoneState(state) != NO_ERROR) {
815 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700816 return;
817 }
François Gaffie2110e042015-03-24 08:41:51 +0100818 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700819 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700820 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700821 // force reevaluating accessibility routing when call stops
Eric Laurent2cbe89a2014-12-19 11:49:08 -0800822 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700823 }
824
François Gaffie2110e042015-03-24 08:41:51 +0100825 /**
826 * Switching to or from incall state or switching between telephony and VoIP lead to force
827 * routing command.
828 */
Eric Laurent74b71512019-11-06 17:21:57 -0800829 bool force = ((isStateInCall(oldState) != isStateInCall(state))
830 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700831
832 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700833 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700834
Eric Laurente552edb2014-03-10 17:42:56 -0700835 int delayMs = 0;
836 if (isStateInCall(state)) {
837 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100838 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
839 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700840 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700841 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700842 // mute media and sonification strategies and delay device switch by the largest
843 // latency of any output where either strategy is active.
844 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100845 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
846 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
847 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700848 (delayMs < (int)desc->latency()*2)) {
849 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700850 }
François Gaffiec005e562018-11-06 15:04:49 +0100851 setStrategyMute(musicStrategy, true, desc);
852 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
853 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
854 nullptr, true /*fromCache*/).types());
855 setStrategyMute(sonificationStrategy, true, desc);
856 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
857 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
858 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700859 }
860 }
861
Eric Laurent87ffa392015-05-22 10:32:38 -0700862 if (hasPrimaryOutput()) {
Eric Laurent87ffa392015-05-22 10:32:38 -0700863 if (state == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100864 (void)updateCallRouting(false /*fromCache*/, delayMs);
Eric Laurent87ffa392015-05-22 10:32:38 -0700865 } else {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100866 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
867 // force routing command to audio hardware when ending call
868 // even if no device change is needed
869 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
870 rxDevices = mPrimaryOutput->devices();
871 }
872 if (oldState == AUDIO_MODE_IN_CALL) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200873 disconnectTelephonyAudioSource(mCallRxSourceClient);
874 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100875 }
François Gaffie11d30102018-11-02 16:09:09 +0100876 setOutputDevices(mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700877 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700878 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700879
880 // reevaluate routing on all outputs in case tracks have been started during the call
881 for (size_t i = 0; i < mOutputs.size(); i++) {
882 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100883 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200884 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
885 bool forceRouting = !newDevices.isEmpty();
886 setOutputDevices(desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
887 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700888 }
889 }
890
Eric Laurent96d1dda2022-03-14 17:14:19 +0100891 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
892
Eric Laurente552edb2014-03-10 17:42:56 -0700893 if (isStateInCall(state)) {
894 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700895 // force reevaluating accessibility routing when call starts
896 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
Eric Laurente552edb2014-03-10 17:42:56 -0700897 }
898
899 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100900 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
901 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700902}
903
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700904audio_mode_t AudioPolicyManager::getPhoneState() {
905 return mEngine->getPhoneState();
906}
907
Eric Laurente0720872014-03-11 09:30:41 -0700908void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100909 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700910{
François Gaffie2110e042015-03-24 08:41:51 +0100911 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700912 if (config == mEngine->getForceUse(usage)) {
913 return;
914 }
Eric Laurente552edb2014-03-10 17:42:56 -0700915
François Gaffie2110e042015-03-24 08:41:51 +0100916 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
917 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
918 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700919 }
François Gaffie2110e042015-03-24 08:41:51 +0100920 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
921 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
922 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700923
924 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700925 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800926
Eric Laurent22fcda22019-05-17 16:28:47 -0700927 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
928 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
929 mpClientInterface->invalidateStream(AUDIO_STREAM_SYSTEM);
930 mpClientInterface->invalidateStream(AUDIO_STREAM_ENFORCED_AUDIBLE);
931 }
932
Eric Laurentdc462862016-07-19 12:29:53 -0700933 //FIXME: workaround for truncated touch sounds
934 // to be removed when the problem is handled by system UI
935 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700936 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
937 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
938 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700939
940 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100941 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700942}
943
Eric Laurente0720872014-03-11 09:30:41 -0700944void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700945{
946 ALOGV("setSystemProperty() property %s, value %s", property, value);
947}
948
Dorin Drimusecc9f422022-03-09 17:57:40 +0100949// Find an MSD output profile compatible with the parameters passed.
950// When "directOnly" is set, restrict search to profiles for direct outputs.
951sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
952 const DeviceVector& devices,
953 uint32_t samplingRate,
954 audio_format_t format,
955 audio_channel_mask_t channelMask,
956 audio_output_flags_t flags,
957 bool directOnly)
958{
959 flags = getRelevantFlags(flags, directOnly);
960
961 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
962 if (msdModule != nullptr) {
963 // for the msd module check if there are patches to the output devices
964 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
965 HwModuleCollection modules;
966 modules.add(msdModule);
967 return searchCompatibleProfileHwModules(
968 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
969 flags, directOnly);
970 }
971 }
972 return nullptr;
973}
974
Michael Chana94fbb22018-04-24 14:31:19 +1000975// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
976// search to profiles for direct outputs.
977sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +0100978 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +1000979 uint32_t samplingRate,
980 audio_format_t format,
981 audio_channel_mask_t channelMask,
982 audio_output_flags_t flags,
983 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -0700984{
Dorin Drimusecc9f422022-03-09 17:57:40 +0100985 flags = getRelevantFlags(flags, directOnly);
986
987 return searchCompatibleProfileHwModules(
988 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
989}
990
991audio_output_flags_t AudioPolicyManager::getRelevantFlags (
992 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +1000993 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +0100994 // only retain flags that will drive the direct output profile selection
995 // if explicitly requested
996 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +1000997 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +0100998 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
999 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001000 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001001 return flags;
1002}
Eric Laurent861a6282015-05-18 15:40:16 -07001003
Dorin Drimusecc9f422022-03-09 17:57:40 +01001004sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1005 const HwModuleCollection& hwModules,
1006 const DeviceVector& devices,
1007 uint32_t samplingRate,
1008 audio_format_t format,
1009 audio_channel_mask_t channelMask,
1010 audio_output_flags_t flags,
1011 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001012 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001013 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001014 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001015 if (!curProfile->isCompatibleProfile(devices,
1016 samplingRate, NULL /*updatedSamplingRate*/,
1017 format, NULL /*updatedFormat*/,
1018 channelMask, NULL /*updatedChannelMask*/,
1019 flags)) {
1020 continue;
1021 }
1022 // reject profiles not corresponding to a device currently available
1023 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1024 continue;
1025 }
1026 // reject profiles if connected device does not support codec
1027 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1028 continue;
1029 }
1030 if (!directOnly) {
1031 return curProfile;
1032 }
1033
1034 // when searching for direct outputs, if several profiles are compatible, give priority
1035 // to one with offload capability
1036 if (profile != 0 &&
1037 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001038 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001039 }
1040 profile = curProfile;
1041 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1042 break;
1043 }
Eric Laurente552edb2014-03-10 17:42:56 -07001044 }
1045 }
Eric Laurent861a6282015-05-18 15:40:16 -07001046 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001047}
1048
Eric Laurentfa0f6742021-08-17 18:39:44 +02001049sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001050 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001051{
1052 for (const auto& hwModule : mHwModules) {
1053 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001054 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001055 continue;
1056 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001057 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001058 // reject profiles not corresponding to a device currently available
1059 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1060 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1061 continue;
1062 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001063 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1064 != devices.size()) {
1065 continue;
1066 }
1067 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001068 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1069 return curProfile;
1070 }
1071 }
1072 return nullptr;
1073}
1074
Eric Laurentf4e63452017-11-06 19:31:46 +00001075audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001076{
François Gaffiec005e562018-11-06 15:04:49 +01001077 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001078
1079 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1080 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1081 // format, flags, etc. This may result in some discrepancy for functions that utilize
1082 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1083 // and AudioSystem::getOutputSamplingRate().
1084
François Gaffie11d30102018-11-02 16:09:09 +01001085 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001086 const audio_io_handle_t output = selectOutput(outputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001087
François Gaffie11d30102018-11-02 16:09:09 +01001088 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1089 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001090 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001091}
1092
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001093status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1094 const audio_attributes_t *srcAttr,
1095 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001096{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001097 if (srcAttr != NULL) {
1098 if (!isValidAttributes(srcAttr)) {
1099 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1100 __func__,
1101 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1102 srcAttr->tags);
1103 return BAD_VALUE;
1104 }
1105 *dstAttr = *srcAttr;
1106 } else {
1107 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1108 ALOGE("%s: invalid stream type", __func__);
1109 return BAD_VALUE;
1110 }
François Gaffiec005e562018-11-06 15:04:49 +01001111 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001112 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001113
1114 // Only honor audibility enforced when required. The client will be
1115 // forced to reconnect if the forced usage changes.
1116 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001117 dstAttr->flags = static_cast<audio_flags_mask_t>(
1118 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001119 }
1120
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001121 return NO_ERROR;
1122}
1123
Kevin Rocard153f92d2018-12-18 18:33:28 -08001124status_t AudioPolicyManager::getOutputForAttrInt(
1125 audio_attributes_t *resultAttr,
1126 audio_io_handle_t *output,
1127 audio_session_t session,
1128 const audio_attributes_t *attr,
1129 audio_stream_type_t *stream,
1130 uid_t uid,
1131 const audio_config_t *config,
1132 audio_output_flags_t *flags,
1133 audio_port_handle_t *selectedDeviceId,
1134 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001135 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001136 output_type_t *outputType,
1137 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001138{
François Gaffiec005e562018-11-06 15:04:49 +01001139 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001140 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001141 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001142 const sp<DeviceDescriptor> requestedDevice =
1143 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1144
Eric Laurent8a1095a2019-11-08 14:44:16 -08001145 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001146 *isSpatialized = false;
1147
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001148 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1149 if (status != NO_ERROR) {
1150 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001151 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001152 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001153 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001154 }
François Gaffiec005e562018-11-06 15:04:49 +01001155 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001156
François Gaffiec005e562018-11-06 15:04:49 +01001157 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1158 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001159
Kevin Rocard153f92d2018-12-18 18:33:28 -08001160 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1161 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1162 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001163 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001164 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1165 .channel_mask = config->channel_mask,
1166 .format = config->format,
1167 };
1168 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, *flags, primaryMix,
1169 secondaryMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001170 if (status != OK) {
1171 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001172 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001173
Kevin Rocard153f92d2018-12-18 18:33:28 -08001174 // Explicit routing is higher priority then any dynamic policy primary output
Eric Laurentc529cf62020-04-17 18:19:10 -07001175 bool usePrimaryOutputFromPolicyMixes = requestedDevice == nullptr && primaryMix != nullptr;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001176
1177 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001178 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1179 && !audio_is_linear_pcm(config->format)) {
1180 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001181 return BAD_VALUE;
1182 }
1183 if (usePrimaryOutputFromPolicyMixes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001184 sp<DeviceDescriptor> deviceDesc =
1185 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1186 primaryMix->mDeviceAddress,
1187 AUDIO_FORMAT_DEFAULT);
1188 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001189 bool tryDirectForFlags = policyDesc == nullptr ||
1190 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT);
1191 // if a direct output can be opened to deliver the track's multi-channel content to the
1192 // output rather than being downmixed by the primary output, then use this direct
1193 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1194 // mix.
1195 bool tryDirectForChannelMask = policyDesc != nullptr
1196 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1197 audio_channel_count_from_out_mask(config->channel_mask));
1198 if (deviceDesc != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001199 audio_io_handle_t newOutput;
1200 status = openDirectOutput(
1201 *stream, session, config,
1202 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
1203 DeviceVector(deviceDesc), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001204 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001205 policyDesc = mOutputs.valueFor(newOutput);
1206 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001207 } else if (tryDirectForFlags) {
1208 policyDesc = nullptr;
1209 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001210 }
1211 if (policyDesc != nullptr) {
1212 policyDesc->mPolicyMix = primaryMix;
1213 *output = policyDesc->mIoHandle;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001214 *selectedDeviceId = deviceDesc != 0 ? deviceDesc->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001215
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001216 ALOGV("getOutputForAttr() returns output %d", *output);
1217 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1218 *outputType = API_OUT_MIX_PLAYBACK;
1219 } else {
1220 *outputType = API_OUTPUT_LEGACY;
1221 }
1222 return NO_ERROR;
Eric Laurent8a1095a2019-11-08 14:44:16 -08001223 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001224 }
François Gaffiec005e562018-11-06 15:04:49 +01001225 // Virtual sources must always be dynamicaly or explicitly routed
1226 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1227 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1228 return BAD_VALUE;
1229 }
1230 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1231 // in order to let the choice of the order to future vendor engine
1232 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001233
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001234 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001235 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001236 }
1237
Nadav Barb2f18162018-07-18 13:01:53 +03001238 // Set incall music only if device was explicitly set, and fallback to the device which is
1239 // chosen by the engine if not.
1240 // FIXME: provide a more generic approach which is not device specific and move this back
1241 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001242 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001243 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001244 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001245 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001246 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001247 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001248 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001249 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001250 }
1251 }
1252
François Gaffiec005e562018-11-06 15:04:49 +01001253 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1254 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1255 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001256
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001257 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001258 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001259 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001260 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001261 ALOGV("%s() Using MSD devices %s instead of devices %s",
1262 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001263 } else {
1264 *output = AUDIO_IO_HANDLE_NONE;
1265 }
1266 }
1267 if (*output == AUDIO_IO_HANDLE_NONE) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001268 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001269 flags, isSpatialized, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001270 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001271 if (*output == AUDIO_IO_HANDLE_NONE) {
1272 return INVALID_OPERATION;
1273 }
Paul McLeanaa981192015-03-21 09:55:15 -07001274
François Gaffiec005e562018-11-06 15:04:49 +01001275 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001276 for (auto &outputDevice : outputDevices) {
1277 if (outputDevice->getId() == getConfig().getDefaultOutputDevice()->getId()) {
1278 *selectedDeviceId = outputDevice->getId();
1279 break;
1280 }
1281 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001282
Eric Laurent8a1095a2019-11-08 14:44:16 -08001283 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1284 *outputType = API_OUTPUT_TELEPHONY_TX;
1285 } else {
1286 *outputType = API_OUTPUT_LEGACY;
1287 }
1288
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001289 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1290
1291 return NO_ERROR;
1292}
1293
1294status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1295 audio_io_handle_t *output,
1296 audio_session_t session,
1297 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001298 const AttributionSourceState& attributionSource,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001299 const audio_config_t *config,
1300 audio_output_flags_t *flags,
1301 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001302 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001303 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001304 output_type_t *outputType,
1305 bool *isSpatialized)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001306{
1307 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1308 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1309 return INVALID_OPERATION;
1310 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001311 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001312 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001313 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001314 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001315 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001316 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001317 const sp<DeviceDescriptor> requestedDevice =
1318 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1319
1320 // Prevent from storing invalid requested device id in clients
1321 const audio_port_handle_t sanitizedRequestedPortId =
1322 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1323 *selectedDeviceId = sanitizedRequestedPortId;
1324
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001325 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001326 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001327 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001328 if (status != NO_ERROR) {
1329 return status;
1330 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001331 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001332 if (secondaryOutputs != nullptr) {
1333 for (auto &secondaryMix : secondaryMixes) {
1334 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1335 if (outputDesc != nullptr &&
1336 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1337 secondaryOutputs->push_back(outputDesc->mIoHandle);
1338 weakSecondaryOutputDescs.push_back(outputDesc);
1339 }
1340 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001341 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001342
Eric Laurent8fc147b2018-07-22 19:13:55 -07001343 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001344 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001345 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001346 };
jiabin4ef93452019-09-10 14:29:54 -07001347 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001348
Eric Laurentc209fe42020-06-05 18:11:23 -07001349 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001350 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001351 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001352 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001353 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001354 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001355 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001356 std::move(weakSecondaryOutputDescs),
1357 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001358 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001359
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001360 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1361 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001362
Eric Laurente83b55d2014-11-14 10:06:21 -08001363 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001364}
1365
Eric Laurentc529cf62020-04-17 18:19:10 -07001366status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1367 audio_session_t session,
1368 const audio_config_t *config,
1369 audio_output_flags_t flags,
1370 const DeviceVector &devices,
1371 audio_io_handle_t *output) {
1372
1373 *output = AUDIO_IO_HANDLE_NONE;
1374
1375 // skip direct output selection if the request can obviously be attached to a mixed output
1376 // and not explicitly requested
1377 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1378 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1379 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1380 return NAME_NOT_FOUND;
1381 }
1382
1383 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1384 // This prevents creating an offloaded track and tearing it down immediately after start
1385 // when audioflinger detects there is an active non offloadable effect.
1386 // FIXME: We should check the audio session here but we do not have it in this context.
1387 // This may prevent offloading in rare situations where effects are left active by apps
1388 // in the background.
1389 sp<IOProfile> profile;
1390 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1391 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1392 profile = getProfileForOutput(
1393 devices, config->sample_rate, config->format, config->channel_mask,
1394 flags, true /* directOnly */);
1395 }
1396
1397 if (profile == nullptr) {
1398 return NAME_NOT_FOUND;
1399 }
1400
1401 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1402 for (size_t i = 0; i < mOutputs.size(); i++) {
1403 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1404 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1405 // reuse direct output if currently open by the same client
1406 // and configured with same parameters
1407 if ((config->sample_rate == desc->getSamplingRate()) &&
1408 (config->format == desc->getFormat()) &&
1409 (config->channel_mask == desc->getChannelMask()) &&
1410 (session == desc->mDirectClientSession)) {
1411 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001412 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001413 mOutputs.keyAt(i), session);
1414 *output = mOutputs.keyAt(i);
1415 return NO_ERROR;
1416 }
1417 }
1418 }
1419
1420 if (!profile->canOpenNewIo()) {
1421 return NAME_NOT_FOUND;
1422 }
1423
1424 sp<SwAudioOutputDescriptor> outputDesc =
1425 new SwAudioOutputDescriptor(profile, mpClientInterface);
1426
Michael Chan6fb34492020-12-08 15:44:49 +11001427 // An MSD patch may be using the only output stream that can service this request. Release
1428 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001429 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001430
Eric Laurentf1f22e72021-07-13 14:04:14 +02001431 status_t status =
1432 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001433
1434 // only accept an output with the requested parameters
1435 if (status != NO_ERROR ||
1436 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1437 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1438 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1439 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1440 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1441 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1442 config->channel_mask, outputDesc->getChannelMask());
1443 if (*output != AUDIO_IO_HANDLE_NONE) {
1444 outputDesc->close();
1445 }
1446 // fall back to mixer output if possible when the direct output could not be open
1447 if (audio_is_linear_pcm(config->format) &&
1448 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1449 return NAME_NOT_FOUND;
1450 }
1451 *output = AUDIO_IO_HANDLE_NONE;
1452 return BAD_VALUE;
1453 }
1454 outputDesc->mDirectOpenCount = 1;
1455 outputDesc->mDirectClientSession = session;
1456
1457 addOutput(*output, outputDesc);
1458 mPreviousOutputs = mOutputs;
1459 ALOGV("%s returns new direct output %d", __func__, *output);
1460 mpClientInterface->onAudioPortListUpdate();
1461 return NO_ERROR;
1462}
1463
François Gaffie11d30102018-11-02 16:09:09 +01001464audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1465 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001466 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001467 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001468 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001469 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001470 bool *isSpatialized,
jiabine375d412019-02-26 12:54:53 -08001471 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001472{
Andy Hungc88b0642018-04-27 15:42:35 -07001473 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001474
jiabine375d412019-02-26 12:54:53 -08001475 // Discard haptic channel mask when forcing muting haptic channels.
1476 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001477 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1478 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001479
Eric Laurente552edb2014-03-10 17:42:56 -07001480 // open a direct output if required by specified parameters
1481 //force direct flag if offload flag is set: offloading implies a direct output stream
1482 // and all common behaviors are driven by checking only the direct flag
1483 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001484 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1485 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001486 }
Nadav Bar766fb022018-01-07 12:18:03 +02001487 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1488 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001489 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001490
1491 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1492
Eric Laurente83b55d2014-11-14 10:06:21 -08001493 // only allow deep buffering for music stream type
1494 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001495 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001496 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001497 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001498 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1499 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001500 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001501 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001502 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001503 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001504 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001505 audio_is_linear_pcm(config->format) &&
1506 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001507 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001508 AUDIO_OUTPUT_FLAG_DIRECT);
1509 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001510 }
Eric Laurente552edb2014-03-10 17:42:56 -07001511
Carter Hsua3abb402021-10-26 11:11:20 +08001512 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1513 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1514 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1515 }
1516
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001517 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001518 if (mSpatializerOutput != nullptr
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001519 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001520 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001521 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001522 }
1523
Eric Laurentc529cf62020-04-17 18:19:10 -07001524 audio_config_t directConfig = *config;
1525 directConfig.channel_mask = channelMask;
1526 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1527 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001528 return output;
1529 }
1530
Eric Laurent14cbfca2016-03-17 09:42:16 -07001531 // A request for HW A/V sync cannot fallback to a mixed output because time
1532 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001533 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001534 return AUDIO_IO_HANDLE_NONE;
1535 }
1536
Eric Laurente552edb2014-03-10 17:42:56 -07001537 // ignoring channel mask due to downmix capability in mixer
1538
1539 // open a non direct output
1540
1541 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001542 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001543 // get which output is suitable for the specified stream. The actual
1544 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001545 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07001546
Eric Laurent8838a382014-09-08 16:44:28 -07001547 // at this stage we should ignore the DIRECT flag as no direct output could be found earlier
Nadav Bar766fb022018-01-07 12:18:03 +02001548 *flags = (audio_output_flags_t)(*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabinebb6af42020-06-09 17:31:17 -07001549 output = selectOutput(
1550 outputs, *flags, config->format, channelMask, config->sample_rate, session);
Eric Laurente552edb2014-03-10 17:42:56 -07001551 }
François Gaffie11d30102018-11-02 16:09:09 +01001552 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001553 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001554 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001555
Eric Laurente552edb2014-03-10 17:42:56 -07001556 return output;
1557}
1558
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001559sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001560 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1561 mAvailableInputDevices);
1562 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1563}
1564
1565DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1566 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1567 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001568}
1569
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001570const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001571 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001572 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1573 if (msdModule != 0) {
1574 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1575 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1576 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1577 const struct audio_port_config *source = &patch->mPatch.sources[j];
1578 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1579 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001580 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001581 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001582 }
1583 }
1584 }
1585 return msdPatches;
1586}
1587
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001588bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1589 ssize_t index = mAudioPatches.indexOfKey(handle);
1590 if (index < 0) {
1591 return false;
1592 }
1593 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1594 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1595 if (msdModule == nullptr) {
1596 return false;
1597 }
1598 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1599 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1600 return true;
1601 }
1602 index = getMsdOutputPatches().indexOfKey(handle);
1603 if (index < 0) {
1604 return false;
1605 }
1606 return true;
1607}
1608
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001609status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1610 const InputProfileCollection &inputProfiles,
1611 const OutputProfileCollection &outputProfiles,
1612 const sp<DeviceDescriptor> &sourceDevice,
1613 const sp<DeviceDescriptor> &sinkDevice,
1614 AudioProfileVector& sourceProfiles,
1615 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001616 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001617 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001618 return NO_INIT;
1619 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001620 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001621 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001622 return NO_INIT;
1623 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001624 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001625 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1626 inProfile->supportsDevice(sourceDevice)) {
1627 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001628 }
1629 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001630 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001631 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001632 outProfile->supportsDevice(sinkDevice)) {
1633 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001634 }
1635 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001636 return NO_ERROR;
1637}
1638
1639status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1640 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1641 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1642{
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001643 struct audio_config_base bestSinkConfig;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001644 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles,
1645 msdCompressedFormatsOrder, msdSurroundChannelMasksOrder,
1646 true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001647 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001648 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1649 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001650 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001651 }
1652 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1653 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1654 sinkConfig->format = bestSinkConfig.format;
1655 // For encoded streams force direct flag to prevent downstream mixing.
1656 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1657 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001658 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1659 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001660 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001661 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1662 // raw and IEC61937 framed streams.
1663 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1664 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1665 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001666 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1667 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
1668 sourceConfig->channel_mask = audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
1669 sourceConfig->format = bestSinkConfig.format;
1670 // Copy input stream directly without any processing (e.g. resampling).
1671 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1672 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1673 if (hwAvSync) {
1674 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1675 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1676 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1677 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1678 }
1679 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1680 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1681 sinkConfig->config_mask |= config_mask;
1682 sourceConfig->config_mask |= config_mask;
1683 return NO_ERROR;
1684}
1685
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001686PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1687 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001688{
1689 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001690 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1691 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1692 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1693 if (deviceModule == nullptr) {
1694 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1695 return patchBuilder;
1696 }
1697 const InputProfileCollection inputProfiles = msdIsSource ?
1698 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1699 const OutputProfileCollection outputProfiles = msdIsSource ?
1700 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1701
1702 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1703 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1704 device : getMsdAudioOutDevices().itemAt(0);
1705 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1706
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001707 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1708 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001709 AudioProfileVector sourceProfiles;
1710 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001711 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1712 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001713 for (auto hwAvSync : { true, false }) {
1714 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1715 sourceProfiles, sinkProfiles) != NO_ERROR) {
1716 continue;
1717 }
1718 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1719 &sinkConfig) == NO_ERROR) {
1720 // Found a matching config. Re-create PatchBuilder with this config.
1721 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1722 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001723 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001724 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001725 " supporting PCM format conversion.", __func__);
1726 return patchBuilder;
1727}
1728
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001729status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001730 DeviceVector devices;
1731 if (outputDevices != nullptr && outputDevices->size() > 0) {
1732 devices.add(*outputDevices);
1733 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001734 // Use media strategy for unspecified output device. This should only
1735 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1736 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001737 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001738 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001739 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001740 }
Michael Chan6fb34492020-12-08 15:44:49 +11001741 std::vector<PatchBuilder> patchesToCreate;
1742 for (auto i = 0u; i < devices.size(); ++i) {
1743 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001744 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001745 }
1746 // Retain only the MSD patches associated with outputDevices request.
1747 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001748 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001749 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1750 auto retainedPatch = false;
1751 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1752 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1753 patchesToRemove.removeItemsAt(i);
1754 retainedPatch = true;
1755 break;
1756 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001757 }
Michael Chan6fb34492020-12-08 15:44:49 +11001758 if (retainedPatch) {
1759 it = patchesToCreate.erase(it);
1760 continue;
1761 }
1762 ++it;
1763 }
1764 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1765 return NO_ERROR;
1766 }
1767 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1768 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001769 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001770 }
Michael Chan6fb34492020-12-08 15:44:49 +11001771 status_t status = NO_ERROR;
1772 for (const auto &p : patchesToCreate) {
1773 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1774 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1775 char message[256];
1776 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1777 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1778 currStatus == NO_ERROR ? "Success" : "Error",
1779 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1780 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1781 if (currStatus == NO_ERROR) {
1782 ALOGD("%s", message);
1783 } else {
1784 ALOGE("%s", message);
1785 if (status == NO_ERROR) {
1786 status = currStatus;
1787 }
1788 }
1789 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001790 return status;
1791}
1792
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001793void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1794 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001795 for (size_t i = 0; i < msdPatches.size(); i++) {
1796 const auto& patch = msdPatches[i];
1797 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1798 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1799 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1800 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1801 releaseAudioPatch(patch->getHandle(), mUidCached);
1802 break;
1803 }
1804 }
1805 }
1806}
1807
Dorin Drimus94d94412022-02-02 09:05:02 +01001808bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
1809 DeviceVector devicesToCheck = mOutputDevicesAll.getDevicesFromDeviceTypeAddrVec(devices);
1810 AudioPatchCollection msdPatches = getMsdOutputPatches();
1811 for (size_t i = 0; i < msdPatches.size(); i++) {
1812 const auto& patch = msdPatches[i];
1813 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1814 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1815 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1816 const auto& foundDevice = devicesToCheck.getDevice(
1817 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1818 if (foundDevice != nullptr) {
1819 devicesToCheck.remove(foundDevice);
1820 if (devicesToCheck.isEmpty()) {
1821 return true;
1822 }
1823 }
1824 }
1825 }
1826 }
1827 return false;
1828}
1829
Eric Laurente0720872014-03-11 09:30:41 -07001830audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001831 audio_output_flags_t flags,
1832 audio_format_t format,
1833 audio_channel_mask_t channelMask,
1834 uint32_t samplingRate,
1835 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07001836{
Eric Laurent16c66dd2019-05-01 17:54:10 -07001837 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
1838 "%s called with format %#x", __func__, format);
1839
jiabinebb6af42020-06-09 17:31:17 -07001840 // Return the output that haptic-generating attached to when 1) session id is specified,
1841 // 2) haptic-generating effect exists for given session id and 3) the output that
1842 // haptic-generating effect attached to is in given outputs.
1843 if (sessionId != AUDIO_SESSION_NONE) {
1844 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
1845 sessionId, FX_IID_HAPTICGENERATOR);
1846 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
1847 return hapticGeneratingOutput;
1848 }
1849 }
1850
Eric Laurent16c66dd2019-05-01 17:54:10 -07001851 // Flags disqualifying an output: the match must happen before calling selectOutput()
1852 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
1853 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
1854
1855 // Flags expressing a functional request: must be honored in priority over
1856 // other criteria
1857 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
1858 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01001859 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
1860 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001861 // Flags expressing a performance request: have lower priority than serving
1862 // requested sampling rate or channel mask
1863 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
1864 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
1865 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
1866
1867 const audio_output_flags_t functionalFlags =
1868 (audio_output_flags_t)(flags & kFunctionalFlags);
1869 const audio_output_flags_t performanceFlags =
1870 (audio_output_flags_t)(flags & kPerformanceFlags);
1871
1872 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
1873
Eric Laurente552edb2014-03-10 17:42:56 -07001874 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01001875 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07001876 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08001877 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07001878 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08001879 // with tiebreak preferring the minimum number of extra functional flags
1880 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07001881 // 3: the output supporting the exact channel mask
1882 // 4: the output with a higher channel count than requested
jiabind1785f72022-06-03 20:48:18 +00001883 // 5: the output with the highest sampling rate if the requested sample rate is
1884 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07001885 // 6: the output with the highest number of requested performance flags
1886 // 7: the output with the bit depth the closest to the requested one
1887 // 8: the primary output
1888 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07001889
Eric Laurent16c66dd2019-05-01 17:54:10 -07001890 // matching criteria values in priority order for best matching output so far
1891 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07001892
Eric Laurent16c66dd2019-05-01 17:54:10 -07001893 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
1894 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
1895 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08001896
Mikhail Naganovcf84e592017-12-07 11:25:11 -08001897 for (audio_io_handle_t output : outputs) {
1898 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001899 // matching criteria values in priority order for current output
1900 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08001901
Eric Laurent16c66dd2019-05-01 17:54:10 -07001902 if (outputDesc->isDuplicated()) {
1903 continue;
1904 }
1905 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
1906 continue;
1907 }
Eric Laurent8838a382014-09-08 16:44:28 -07001908
Eric Laurent16c66dd2019-05-01 17:54:10 -07001909 // If haptic channel is specified, use the haptic output if present.
1910 // When using haptic output, same audio format and sample rate are required.
1911 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07001912 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07001913 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
1914 continue;
1915 }
1916 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07001917 && format == outputDesc->getFormat()
1918 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001919 currentMatchCriteria[0] = outputHapticChannelCount;
1920 }
1921
1922 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08001923 const int matchingFunctionalFlags =
1924 __builtin_popcount(outputDesc->mFlags & functionalFlags);
1925 const int totalFunctionalFlags =
1926 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
1927 // Prefer matching functional flags, but subtract unnecessary functional flags.
1928 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07001929
1930 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07001931 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
1932 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001933 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
1934 channelCount <= outputChannelCount) {
1935 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07001936 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
1937 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07001938 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07001939 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07001940 currentMatchCriteria[3] = outputChannelCount;
1941 }
1942
1943 // sampling rate match
jiabind1785f72022-06-03 20:48:18 +00001944 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07001945 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07001946 }
1947
1948 // performance flags match
1949 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
1950
1951 // format match
1952 if (format != AUDIO_FORMAT_INVALID) {
1953 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07001954 PolicyAudioPort::kFormatDistanceMax -
1955 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07001956 }
1957
1958 // primary output match
1959 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
1960
1961 // compare match criteria by priority then value
1962 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1963 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
1964 bestMatchCriteria = currentMatchCriteria;
1965 bestOutput = output;
1966
1967 std::stringstream result;
1968 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
1969 std::ostream_iterator<int>(result, " "));
1970 ALOGV("%s new bestOutput %d criteria %s",
1971 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07001972 }
1973 }
1974
Eric Laurent16c66dd2019-05-01 17:54:10 -07001975 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07001976}
1977
Eric Laurent8fc147b2018-07-22 19:13:55 -07001978status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07001979{
Eric Laurent8fc147b2018-07-22 19:13:55 -07001980 ALOGV("%s portId %d", __FUNCTION__, portId);
1981
1982 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
1983 if (outputDesc == 0) {
1984 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001985 return BAD_VALUE;
1986 }
Andy Hung39efb7a2018-09-26 15:39:28 -07001987 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07001988
Eric Laurent8fc147b2018-07-22 19:13:55 -07001989 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07001990 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07001991
Eric Laurent733ce942017-12-07 12:18:25 -08001992 status_t status = outputDesc->start();
1993 if (status != NO_ERROR) {
1994 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08001995 }
1996
Eric Laurent97ac8712018-07-27 18:59:02 -07001997 uint32_t delayMs;
1998 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07001999
2000 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002001 outputDesc->stop();
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002002 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002003 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002004 if (delayMs != 0) {
2005 usleep(delayMs * 1000);
2006 }
2007
2008 return status;
2009}
2010
Eric Laurent96d1dda2022-03-14 17:14:19 +01002011bool AudioPolicyManager::isLeUnicastActive() const {
2012 if (isInCall()) {
2013 return true;
2014 }
2015 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2016}
2017
2018bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2019 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2020 return false;
2021 }
2022 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2023 ALOGV("%s active %d", __func__, active);
2024 return active;
2025}
2026
Eric Laurent97ac8712018-07-27 18:59:02 -07002027status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2028 const sp<TrackClientDescriptor>& client,
2029 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002030{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002031 // cannot start playback of STREAM_TTS if any other output is being used
2032 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002033
2034 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002035 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002036 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002037 auto clientStrategy = client->strategy();
2038 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002039 if (stream == AUDIO_STREAM_TTS) {
2040 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002041 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002042 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002043 return INVALID_OPERATION;
2044 } else {
2045 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2046 }
2047 } else {
2048 // some playback other than beacon starts
2049 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2050 }
2051
Eric Laurent77305a62016-07-25 16:39:22 -07002052 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002053 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002054 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002055
François Gaffie11d30102018-11-02 16:09:09 +01002056 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002057 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002058 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002059 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002060 audio_devices_t newDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002061 address = policyMix->mDeviceAddress.string();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002062 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002063 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002064 } else {
2065 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002066 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002067 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2068 AUDIO_FORMAT_DEFAULT);
2069 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2070 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002071 }
2072
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002073 // requiresMuteCheck is false when we can bypass mute strategy.
2074 // It covers a common case when there is no materially active audio
2075 // and muting would result in unnecessary delay and dropped audio.
2076 const uint32_t outputLatencyMs = outputDesc->latency();
2077 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002078 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002079
Eric Laurente552edb2014-03-10 17:42:56 -07002080 // increment usage count for this stream on the requested output:
2081 // NOTE that the usage count is the same for duplicated output and hardware output which is
2082 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002083 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002084
2085 if (client->hasPreferredDevice(true)) {
François Gaffief96e5432019-04-09 17:13:56 +02002086 if (outputDesc->clientsList(true /*activeOnly*/).size() == 1 &&
2087 client->isPreferredDeviceForExclusiveUse()) {
2088 // Preferred device may be exclusive, use only if no other active clients on this output
2089 devices = DeviceVector(
2090 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2091 } else {
2092 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2093 }
François Gaffie11d30102018-11-02 16:09:09 +01002094 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002095 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002096 }
2097 }
Eric Laurente552edb2014-03-10 17:42:56 -07002098
François Gaffiec005e562018-11-06 15:04:49 +01002099 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002100 selectOutputForMusicEffects();
2101 }
2102
François Gaffie1c878552018-11-22 16:53:21 +01002103 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002104 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002105 if (devices.isEmpty()) {
2106 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002107 }
François Gaffiec005e562018-11-06 15:04:49 +01002108 bool shouldWait =
2109 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2110 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2111 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002112 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002113 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002114 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002115 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002116 // An output has a shared device if
2117 // - managed by the same hw module
2118 // - supports the currently selected device
2119 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002120 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002121
Eric Laurent77305a62016-07-25 16:39:22 -07002122 // force a device change if any other output is:
2123 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002124 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002125 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002126 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002127 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002128 // change the device currently selected by the other output.
2129 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002130 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002131 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002132 force = true;
2133 }
2134 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002135 // a notification so that audio focus effect can propagate, or that a mute/unmute
2136 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002137 const uint32_t latencyMs = desc->latency();
2138 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2139
2140 if (shouldWait && isActive && (waitMs < latencyMs)) {
2141 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002142 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002143
2144 // Require mute check if another output is on a shared device
2145 // and currently active to have proper drain and avoid pops.
2146 // Note restoring AudioTracks onto this output needs to invoke
2147 // a volume ramp if there is no mute.
2148 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002149 }
2150 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002151
2152 const uint32_t muteWaitMs =
François Gaffie11d30102018-11-02 16:09:09 +01002153 setOutputDevices(outputDesc, devices, force, 0, NULL, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002154
Eric Laurente552edb2014-03-10 17:42:56 -07002155 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002156 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002157 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002158 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002159 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002160 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002161 outputDesc->useHwGain() /*force*/)) {
2162 // request AudioService to reinitialize the volume curves asynchronously
2163 ALOGE("checkAndSetVolume failed, requesting volume range init");
2164 mpClientInterface->onVolumeRangeInitRequest();
2165 };
Eric Laurente552edb2014-03-10 17:42:56 -07002166
2167 // update the outputs if starting an output with a stream that can affect notification
2168 // routing
2169 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002170
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002171 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002172 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002173 mpClientInterface->invalidateStream(AUDIO_STREAM_ACCESSIBILITY);
2174 }
Eric Laurentdc462862016-07-19 12:29:53 -07002175
2176 if (waitMs > muteWaitMs) {
2177 *delayMs = waitMs - muteWaitMs;
2178 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002179
2180 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2181 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2182 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2183 // change occurs after the MixerThread starts and causes a stream volume
2184 // glitch.
2185 //
2186 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002187 }
Eric Laurentdc462862016-07-19 12:29:53 -07002188
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002189 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002190 mEngine->getForceUse(
2191 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002192 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002193 }
2194
Eric Laurent97ac8712018-07-27 18:59:02 -07002195 // Automatically enable the remote submix input when output is started on a re routing mix
2196 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002197 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2198 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002199 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2200 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2201 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002202 "remote-submix",
2203 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002204 }
2205
Eric Laurent96d1dda2022-03-14 17:14:19 +01002206 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2207
Eric Laurente552edb2014-03-10 17:42:56 -07002208 return NO_ERROR;
2209}
2210
Eric Laurent96d1dda2022-03-14 17:14:19 +01002211void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2212 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2213 bool isUnicastActive = isLeUnicastActive();
2214
2215 if (wasUnicastActive != isUnicastActive) {
2216 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2217 for (size_t i = 0; i < mOutputs.size(); i++) {
2218 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2219 if (desc != ignoredOutput && desc->isActive()
2220 && ((isUnicastActive &&
2221 !desc->devices().
2222 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2223 || (wasUnicastActive &&
2224 !desc->devices().getDevicesFromTypes(
2225 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2226 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2227 bool force = desc->devices() != newDevices;
2228 setOutputDevices(desc, newDevices, force, delayMs);
2229 // re-apply device specific volume if not done by setOutputDevice()
2230 if (!force) {
2231 applyStreamVolumes(desc, newDevices.types(), delayMs);
2232 }
2233 }
2234 }
2235 }
2236}
2237
Eric Laurent8fc147b2018-07-22 19:13:55 -07002238status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002239{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002240 ALOGV("%s portId %d", __FUNCTION__, portId);
2241
2242 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2243 if (outputDesc == 0) {
2244 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002245 return BAD_VALUE;
2246 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002247 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002248
Eric Laurent97ac8712018-07-27 18:59:02 -07002249 ALOGV("stopOutput() output %d, stream %d, session %d",
2250 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002251
Eric Laurent97ac8712018-07-27 18:59:02 -07002252 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002253
Eric Laurent733ce942017-12-07 12:18:25 -08002254 if (status == NO_ERROR ) {
2255 outputDesc->stop();
Eric Laurent3974e3b2017-12-07 17:58:43 -08002256 }
2257 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002258}
2259
Eric Laurent97ac8712018-07-27 18:59:02 -07002260status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2261 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002262{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002263 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002264 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002265 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002266 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002267
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002268 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2269
François Gaffie1c878552018-11-22 16:53:21 +01002270 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2271 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002272 // Automatically disable the remote submix input when output is stopped on a
2273 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002274 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002275 if (isSingleDeviceType(
2276 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002277 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002278 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002279 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2280 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002281 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002282 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002283 }
2284 }
2285 bool forceDeviceUpdate = false;
2286 if (client->hasPreferredDevice(true)) {
François Gaffiec005e562018-11-06 15:04:49 +01002287 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002288 forceDeviceUpdate = true;
2289 }
2290
Eric Laurente552edb2014-03-10 17:42:56 -07002291 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002292 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002293
Eric Laurente552edb2014-03-10 17:42:56 -07002294 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002295 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002296 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002297 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002298
2299 // If the routing does not change, if an output is routed on a device using HwGain
2300 // (aka setAudioPortConfig) and there are still active clients following different
2301 // volume group(s), force reapply volume
2302 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2303 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2304
Eric Laurente552edb2014-03-10 17:42:56 -07002305 // delay the device switch by twice the latency because stopOutput() is executed when
2306 // the track stop() command is received and at that time the audio track buffer can
2307 // still contain data that needs to be drained. The latency only covers the audio HAL
2308 // and kernel buffers. Also the latency does not always include additional delay in the
2309 // audio path (audio DSP, CODEC ...)
Francois Gaffie3523ab32021-06-22 13:24:34 +02002310 setOutputDevices(outputDesc, newDevices, false, outputDesc->latency()*2,
2311 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002312
2313 // force restoring the device selection on other active outputs if it differs from the
2314 // one being selected for this output
Eric Laurent57de36c2016-09-28 16:59:11 -07002315 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002316 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002317 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002318 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002319 desc->isActive() &&
2320 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002321 (newDevices != desc->devices())) {
2322 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2323 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002324
François Gaffie11d30102018-11-02 16:09:09 +01002325 setOutputDevices(desc, newDevices2, force, delayMs);
2326
Eric Laurent57de36c2016-09-28 16:59:11 -07002327 // re-apply device specific volume if not done by setOutputDevice()
2328 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002329 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002330 }
Eric Laurente552edb2014-03-10 17:42:56 -07002331 }
2332 }
2333 // update the outputs if stopping one with a stream that can affect notification routing
2334 handleNotificationRoutingForStream(stream);
2335 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002336
2337 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2338 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002339 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002340 }
2341
François Gaffiec005e562018-11-06 15:04:49 +01002342 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002343 selectOutputForMusicEffects();
2344 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002345
2346 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2347
Eric Laurente552edb2014-03-10 17:42:56 -07002348 return NO_ERROR;
2349 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002350 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002351 return INVALID_OPERATION;
2352 }
2353}
2354
jiabinbce0c1d2020-10-05 11:20:18 -07002355bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002356{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002357 ALOGV("%s portId %d", __FUNCTION__, portId);
2358
2359 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2360 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002361 // If an output descriptor is closed due to a device routing change,
2362 // then there are race conditions with releaseOutput from tracks
2363 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2364 // destroyed shortly thereafter.
2365 //
2366 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002367 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002368 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002369 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002370
2371 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002372
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302373 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2374 if (outputDesc->isClientActive(client)) {
2375 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2376 stopOutput(portId);
2377 }
2378
Eric Laurent8fc147b2018-07-22 19:13:55 -07002379 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2380 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002381 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002382 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002383 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002384 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002385 if (--outputDesc->mDirectOpenCount == 0) {
2386 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002387 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002388 }
2389 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302390
Andy Hung39efb7a2018-09-26 15:39:28 -07002391 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002392 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2393 // The output is pending reopened to query dynamic profiles and
2394 // there is no active clients
2395 closeOutput(outputDesc->mIoHandle);
2396 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2397 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2398 if (newOutputDesc == nullptr) {
2399 ALOGE("%s failed to open output", __func__);
2400 }
2401 return true;
2402 }
2403 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002404}
2405
Eric Laurentcaf7f482014-11-25 17:50:47 -08002406status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2407 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002408 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002409 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002410 const AttributionSourceState& attributionSource,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002411 const audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002412 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002413 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002414 input_type_t *inputType,
2415 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002416{
François Gaffiec005e562018-11-06 15:04:49 +01002417 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002418 "flags %#x attributes=%s requested device ID %d",
2419 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2420 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002421
Eric Laurentad2e7b92017-09-14 20:06:42 -07002422 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002423 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002424 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002425 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002426 sp<AudioInputDescriptor> inputDesc;
2427 sp<RecordClientDescriptor> clientDesc;
2428 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002429 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002430 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002431
2432 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2433 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2434 return INVALID_OPERATION;
2435 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002436
Francois Gaffie716e1432019-01-14 16:58:59 +01002437 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2438 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002439 }
2440
Paul McLean466dc8e2015-04-17 13:15:36 -06002441 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002442 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002443 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002444
Eric Laurentad2e7b92017-09-14 20:06:42 -07002445 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2446 // possible
2447 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2448 *input != AUDIO_IO_HANDLE_NONE) {
2449 ssize_t index = mInputs.indexOfKey(*input);
2450 if (index < 0) {
2451 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2452 status = BAD_VALUE;
2453 goto error;
2454 }
2455 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002456 RecordClientVector clients = inputDesc->getClientsForSession(session);
2457 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002458 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2459 status = BAD_VALUE;
2460 goto error;
2461 }
2462 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2463 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002464 // corresponds to a new client and is only permitted from the same UID.
2465 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002466 if (clients.size() > 1) {
2467 for (const auto& client : clients) {
2468 // The client map is ordered by key values (portId) and portIds are allocated
2469 // incrementaly. So the first client in this list is the one opened by audio flinger
2470 // when the mmap stream is created and should be ignored as it does not correspond
2471 // to an actual client
2472 if (client == *clients.cbegin()) {
2473 continue;
2474 }
2475 if (uid != client->uid() && !client->isSilenced()) {
2476 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2477 uid, client->portId(), client->uid());
2478 status = INVALID_OPERATION;
2479 goto error;
2480 }
Eric Laurent331679c2018-04-16 17:03:16 -07002481 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002482 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002483 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002484 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002485
Eric Laurentfecbceb2021-02-09 14:46:43 +01002486 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002487 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002488 }
2489
2490 *input = AUDIO_IO_HANDLE_NONE;
2491 *inputType = API_INPUT_INVALID;
2492
Francois Gaffie716e1432019-01-14 16:58:59 +01002493 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
2494 strncmp(attributes.tags, "addr=", strlen("addr=")) == 0) {
2495 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002496 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002497 ALOGW("%s could not find input mix for attr %s",
2498 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002499 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002500 }
jiabinc1de2df2019-05-07 14:26:40 -07002501 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2502 String8(attr->tags + strlen("addr=")),
2503 AUDIO_FORMAT_DEFAULT);
2504 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002505 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002506 __func__, attributes.source, attributes.tags);
2507 status = BAD_VALUE;
2508 goto error;
2509 }
2510
Kevin Rocard25f9b052019-02-27 15:08:54 -08002511 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2512 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2513 } else {
2514 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2515 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002516 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002517 if (explicitRoutingDevice != nullptr) {
2518 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002519 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002520 // Prevent from storing invalid requested device id in clients
2521 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08002522 device = mEngine->getInputDeviceForAttributes(attributes, uid, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002523 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2524 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002525 }
François Gaffie11d30102018-11-02 16:09:09 +01002526 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002527 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002528 status = BAD_VALUE;
2529 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002530 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002531 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2532 *inputType = API_INPUT_MIX_CAPTURE;
2533 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002534 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2535 // there is an external policy, but this input is attached to a mix of recorders,
2536 // meaning it receives audio injected into the framework, so the recorder doesn't
2537 // know about it and is therefore considered "legacy"
2538 *inputType = API_INPUT_LEGACY;
2539 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002540 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002541 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002542 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002543 } else {
2544 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002545 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002546
Eric Laurent599c7582015-12-07 18:05:55 -08002547 }
2548
François Gaffiec005e562018-11-06 15:04:49 +01002549 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002550 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002551 status = INVALID_OPERATION;
2552 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002553 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002554
Eric Laurent8f42ea12018-08-08 09:08:25 -07002555exit:
2556
François Gaffiec005e562018-11-06 15:04:49 +01002557 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2558 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002559
Francois Gaffie716e1432019-01-14 16:58:59 +01002560 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002561 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002562 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002563
Mikhail Naganov2996f672019-04-18 12:29:59 -07002564 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002565 requestedDeviceId, attributes.source, flags,
2566 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002567 inputDesc = mInputs.valueFor(*input);
Andy Hung39efb7a2018-09-26 15:39:28 -07002568 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002569
2570 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2571 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002572
Eric Laurent599c7582015-12-07 18:05:55 -08002573 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002574
2575error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002576 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002577}
2578
2579
François Gaffie11d30102018-11-02 16:09:09 +01002580audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002581 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002582 const audio_attributes_t &attributes,
Eric Laurentfe231122017-11-17 17:48:06 -08002583 const audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002584 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002585 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002586{
2587 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002588 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002589 bool isSoundTrigger = false;
2590
François Gaffiec005e562018-11-06 15:04:49 +01002591 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002592 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2593 if (index >= 0) {
2594 input = mSoundTriggerSessions.valueFor(session);
2595 isSoundTrigger = true;
2596 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2597 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2598 } else {
2599 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002600 }
François Gaffiec005e562018-11-06 15:04:49 +01002601 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002602 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002603 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002604 }
2605
Carter Hsua3abb402021-10-26 11:11:20 +08002606 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2607 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2608 }
2609
Andy Hungf129b032015-04-07 13:45:50 -07002610 // find a compatible input profile (not necessarily identical in parameters)
2611 sp<IOProfile> profile;
Eric Laurentfe231122017-11-17 17:48:06 -08002612 // sampling rate and flags may be updated by getInputProfile
2613 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2614 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
Glenn Kasten730b9262018-03-29 15:01:26 -07002615 audio_format_t profileFormat;
Eric Laurentfe231122017-11-17 17:48:06 -08002616 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002617 audio_input_flags_t profileFlags = flags;
2618 for (;;) {
Glenn Kasten730b9262018-03-29 15:01:26 -07002619 profileFormat = config->format; // reset each time through loop, in case it is updated
François Gaffie11d30102018-11-02 16:09:09 +01002620 profile = getInputProfile(device, profileSamplingRate, profileFormat, profileChannelMask,
Andy Hungf129b032015-04-07 13:45:50 -07002621 profileFlags);
2622 if (profile != 0) {
2623 break; // success
Eric Laurent05067782016-06-01 18:27:28 -07002624 } else if (profileFlags & AUDIO_INPUT_FLAG_RAW) {
2625 profileFlags = (audio_input_flags_t) (profileFlags & ~AUDIO_INPUT_FLAG_RAW); // retry
Atneya Nair497fff12022-01-18 16:23:04 -05002626 } else if (profileFlags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(config->format)) {
Andy Hungf129b032015-04-07 13:45:50 -07002627 profileFlags = AUDIO_INPUT_FLAG_NONE; // retry
2628 } else { // fail
François Gaffie11d30102018-11-02 16:09:09 +01002629 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
Pattydd807582021-11-04 21:01:03 +08002630 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
François Gaffie11d30102018-11-02 16:09:09 +01002631 config->sample_rate, config->format, config->channel_mask, flags);
Eric Laurent599c7582015-12-07 18:05:55 -08002632 return input;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002633 }
Eric Laurente552edb2014-03-10 17:42:56 -07002634 }
Glenn Kasten05ddca52016-02-11 08:17:12 -08002635 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002636 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002637 if (samplingRate == 0) {
2638 samplingRate = profileSamplingRate;
2639 }
Eric Laurente552edb2014-03-10 17:42:56 -07002640
Eric Laurent322b4d22015-04-03 15:57:54 -07002641 if (profile->getModuleHandle() == 0) {
2642 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002643 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002644 }
2645
Eric Laurentec376dc2021-04-08 20:41:22 +02002646 // Reuse an already opened input if a client with the same session ID already exists
2647 // on that input
2648 for (size_t i = 0; i < mInputs.size(); i++) {
2649 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2650 if (desc->mProfile != profile) {
2651 continue;
2652 }
2653 RecordClientVector clients = desc->clientsList();
2654 for (const auto &client : clients) {
2655 if (session == client->session()) {
2656 return desc->mIoHandle;
2657 }
2658 }
2659 }
2660
Eric Laurent3974e3b2017-12-07 17:58:43 -08002661 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002662 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002663 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002664 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002665 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002666 continue;
2667 }
2668 // if sound trigger, reuse input if used by other sound trigger on same session
2669 // else
2670 // reuse input if active client app is not in IDLE state
2671 //
2672 RecordClientVector clients = desc->clientsList();
2673 bool doClose = false;
2674 for (const auto& client : clients) {
2675 if (isSoundTrigger != client->isSoundTrigger()) {
2676 continue;
2677 }
2678 if (client->isSoundTrigger()) {
2679 if (session == client->session()) {
2680 return desc->mIoHandle;
2681 }
2682 continue;
2683 }
2684 if (client->active() && client->appState() != APP_STATE_IDLE) {
2685 return desc->mIoHandle;
2686 }
2687 doClose = true;
2688 }
2689 if (doClose) {
2690 closeInput(desc->mIoHandle);
2691 } else {
2692 i++;
2693 }
2694 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002695 }
2696
Eric Laurentfe231122017-11-17 17:48:06 -08002697 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002698
Eric Laurentfe231122017-11-17 17:48:06 -08002699 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2700 lConfig.sample_rate = profileSamplingRate;
2701 lConfig.channel_mask = profileChannelMask;
2702 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002703
François Gaffie11d30102018-11-02 16:09:09 +01002704 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002705
2706 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002707 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002708 (profileSamplingRate != lConfig.sample_rate) ||
2709 !audio_formats_match(profileFormat, lConfig.format) ||
2710 (profileChannelMask != lConfig.channel_mask)) {
2711 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002712 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002713 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002714 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002715 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002716 }
Eric Laurent599c7582015-12-07 18:05:55 -08002717 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002718 }
2719
Eric Laurentc722f302014-12-10 11:21:49 -08002720 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002721
Eric Laurent599c7582015-12-07 18:05:55 -08002722 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002723 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06002724
Eric Laurent599c7582015-12-07 18:05:55 -08002725 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002726}
2727
Eric Laurent4eb58f12018-12-07 16:41:02 -08002728status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08002729{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002730 ALOGV("%s portId %d", __FUNCTION__, portId);
2731
2732 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2733 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002734 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07002735 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002736 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002737 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002738 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002739 if (client->active()) {
2740 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
2741 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07002742 }
2743
Eric Laurent8f42ea12018-08-08 09:08:25 -07002744 audio_session_t session = client->session();
2745
Eric Laurent4eb58f12018-12-07 16:41:02 -08002746 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002747
Eric Laurent4eb58f12018-12-07 16:41:02 -08002748 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07002749
Eric Laurent4eb58f12018-12-07 16:41:02 -08002750 status_t status = inputDesc->start();
2751 if (status != NO_ERROR) {
2752 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07002753 }
Eric Laurente552edb2014-03-10 17:42:56 -07002754
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002755 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08002756 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07002757 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08002758
Eric Laurent8f42ea12018-08-08 09:08:25 -07002759 // indicate active capture to sound trigger service if starting capture from a mic on
2760 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002761 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002762 if (device != nullptr) {
2763 status = setInputDevice(input, device, true /* force */);
2764 } else {
2765 ALOGW("%s no new input device can be found for descriptor %d",
2766 __FUNCTION__, inputDesc->getId());
2767 status = BAD_VALUE;
2768 }
Eric Laurente552edb2014-03-10 17:42:56 -07002769
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002770 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002771 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002772 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002773 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002774 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2775 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002776 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08002777 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002778
François Gaffie11d30102018-11-02 16:09:09 +01002779 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2780 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002781 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002782 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002783 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002784
Eric Laurent8f42ea12018-08-08 09:08:25 -07002785 // automatically enable the remote submix output when input is started if not
2786 // used by a policy mix of type MIX_TYPE_RECORDERS
2787 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01002788 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002789 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002790 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002791 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002792 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2793 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07002794 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002795 if (address != "") {
2796 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2797 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002798 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08002799 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07002800 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002801 } else if (status != NO_ERROR) {
2802 // Restore client activity state.
2803 inputDesc->setClientActive(client, false);
2804 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07002805 }
2806
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002807 ALOGV("%s input %d source = %d status = %d exit",
2808 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07002809
Mikhail Naganov480ffee2019-07-01 15:07:19 -07002810 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07002811}
2812
Eric Laurent8fc147b2018-07-22 19:13:55 -07002813status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002814{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002815 ALOGV("%s portId %d", __FUNCTION__, portId);
2816
2817 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2818 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002819 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002820 return BAD_VALUE;
2821 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002822 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07002823 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002824 if (!client->active()) {
2825 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07002826 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002827 }
Carter Hsue6139d52021-07-08 10:30:20 +08002828 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002829 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06002830
Eric Laurent8f42ea12018-08-08 09:08:25 -07002831 inputDesc->stop();
2832 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08002833 auto current_source = inputDesc->source();
2834 setInputDevice(input, getNewInputDevice(inputDesc),
2835 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002836 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002837 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002838 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002839 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002840 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
2841 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07002842 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00002843 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002844
2845 // automatically disable the remote submix output when input is stopped if not
2846 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01002847 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002848 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002849 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002850 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002851 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
2852 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002853 }
2854 if (address != "") {
2855 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
2856 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002857 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002858 }
2859 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07002860 resetInputDevice(input);
2861
2862 // indicate inactive capture to sound trigger service if stopping capture from a mic on
2863 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01002864 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
2865 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07002866 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07002867 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002868 }
2869 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07002870 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002871 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07002872}
2873
Eric Laurent8fc147b2018-07-22 19:13:55 -07002874void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002875{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002876 ALOGV("%s portId %d", __FUNCTION__, portId);
2877
2878 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
2879 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002880 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002881 return;
2882 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002883 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002884 audio_io_handle_t input = inputDesc->mIoHandle;
2885
Eric Laurent8f42ea12018-08-08 09:08:25 -07002886 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06002887
Andy Hung39efb7a2018-09-26 15:39:28 -07002888 inputDesc->removeClient(portId);
Eric Laurent599c7582015-12-07 18:05:55 -08002889
Andy Hung39efb7a2018-09-26 15:39:28 -07002890 if (inputDesc->getClientCount() > 0) {
2891 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002892 return;
2893 }
2894
Eric Laurent05b90f82014-08-27 15:32:29 -07002895 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07002896 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002897 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07002898}
2899
Eric Laurent8f42ea12018-08-08 09:08:25 -07002900void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07002901{
Eric Laurent8f42ea12018-08-08 09:08:25 -07002902 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002903
2904 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07002905 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07002906 }
2907}
2908
Eric Laurent8f42ea12018-08-08 09:08:25 -07002909void AudioPolicyManager::closeClient(audio_port_handle_t portId)
2910{
2911 stopInput(portId);
2912 releaseInput(portId);
2913}
Eric Laurent8fc147b2018-07-22 19:13:55 -07002914
Eric Laurent0dd51852019-04-19 18:18:58 -07002915void AudioPolicyManager::checkCloseInputs() {
2916 // After connecting or disconnecting an input device, close input if:
2917 // - it has no client (was just opened to check profile) OR
2918 // - none of its supported devices are connected anymore OR
2919 // - one of its clients cannot be routed to one of its supported
2920 // devices anymore. Otherwise update device selection
2921 std::vector<audio_io_handle_t> inputsToClose;
2922 for (size_t i = 0; i < mInputs.size(); i++) {
2923 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
2924 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07002925 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07002926 inputsToClose.push_back(mInputs.keyAt(i));
2927 } else {
2928 bool close = false;
2929 for (const auto& client : input->clientsList()) {
2930 sp<DeviceDescriptor> device =
yuanjiahsu0735bf32021-03-18 08:12:54 +08002931 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid());
Eric Laurent0dd51852019-04-19 18:18:58 -07002932 if (!input->supportedDevices().contains(device)) {
2933 close = true;
2934 break;
2935 }
2936 }
2937 if (close) {
2938 inputsToClose.push_back(mInputs.keyAt(i));
2939 } else {
2940 setInputDevice(input->mIoHandle, getNewInputDevice(input));
2941 }
2942 }
2943 }
2944
2945 for (const audio_io_handle_t handle : inputsToClose) {
2946 ALOGV("%s closing input %d", __func__, handle);
2947 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07002948 }
Eric Laurentd4692962014-05-05 18:13:44 -07002949}
2950
François Gaffie251c7f02018-11-07 10:41:08 +01002951void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07002952{
2953 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08002954 if (indexMin < 0 || indexMax < 0) {
2955 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
2956 return;
2957 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002958 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08002959
2960 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08002961 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
2962 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08002963 continue;
2964 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08002965 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08002966 }
Eric Laurente552edb2014-03-10 17:42:56 -07002967}
2968
Eric Laurente0720872014-03-11 09:30:41 -07002969status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01002970 int index,
2971 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002972{
François Gaffieaaac0fd2018-11-22 17:56:39 +01002973 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07002974 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
2975 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
2976 return NO_ERROR;
2977 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01002978 ALOGV("%s: stream %s attributes=%s", __func__,
2979 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002980 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07002981}
2982
Eric Laurente0720872014-03-11 09:30:41 -07002983status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01002984 int *index,
2985 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07002986{
François Gaffiec005e562018-11-06 15:04:49 +01002987 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
2988 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07002989 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07002990 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07002991 deviceTypes = mEngine->getOutputDevicesForStream(
2992 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07002993 }
jiabin9a3361e2019-10-01 09:38:30 -07002994 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07002995}
2996
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01002997status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01002998 int index,
2999 audio_devices_t device)
3000{
3001 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003002 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3003 if (group == VOLUME_GROUP_NONE) {
3004 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003005 return BAD_VALUE;
3006 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003007 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003008 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003009 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003010 VolumeSource vs = toVolumeSource(group);
3011 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3012
3013 status = setVolumeCurveIndex(index, device, curves);
3014 if (status != NO_ERROR) {
3015 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3016 return status;
3017 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003018
jiabin9a3361e2019-10-01 09:38:30 -07003019 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003020 auto curCurvAttrs = curves.getAttributes();
3021 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3022 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003023 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003024 } else if (!curves.getStreamTypes().empty()) {
3025 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003026 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003027 } else {
3028 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3029 return BAD_VALUE;
3030 }
jiabin9a3361e2019-10-01 09:38:30 -07003031 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3032 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003033
François Gaffiecfe17322018-11-07 13:41:29 +01003034 // update volume on all outputs and streams matching the following:
3035 // - The requested stream (or a stream matching for volume control) is active on the output
3036 // - The device (or devices) selected by the engine for this stream includes
3037 // the requested device
3038 // - For non default requested device, currently selected device on the output is either the
3039 // requested device or one of the devices selected by the engine for this stream
3040 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3041 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003042 for (size_t i = 0; i < mOutputs.size(); i++) {
3043 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003044 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003045
jiabin9a3361e2019-10-01 09:38:30 -07003046 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3047 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003048 }
François Gaffieed91f582020-01-31 10:35:37 +01003049 if (!(desc->isActive(vs) || isInCall())) {
3050 continue;
3051 }
3052 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3053 curDevices.find(device) == curDevices.end()) {
3054 continue;
3055 }
3056 bool applyVolume = false;
3057 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3058 curSrcDevices.insert(device);
3059 applyVolume = (curSrcDevices.find(
3060 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3061 } else {
3062 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3063 }
3064 if (!applyVolume) {
3065 continue; // next output
3066 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003067 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3068 // If a higher priority strategy is active, and the output is routed to a device with a
3069 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003070 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003071 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003072 // If the volume source is active with higher priority source, ensure at least Sw Muted
3073 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003074 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3075 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3076 false /*preferredDevice*/);
3077 if (activeClients.empty()) {
3078 continue;
3079 }
3080 bool isPreempted = false;
3081 bool isHigherPriority = productStrategy < strategy;
3082 for (const auto &client : activeClients) {
3083 if (isHigherPriority && (client->volumeSource() != vs)) {
3084 ALOGV("%s: Strategy=%d (\nrequester:\n"
3085 " group %d, volumeGroup=%d attributes=%s)\n"
3086 " higher priority source active:\n"
3087 " volumeGroup=%d attributes=%s) \n"
3088 " on output %zu, bailing out", __func__, productStrategy,
3089 group, group, toString(attributes).c_str(),
3090 client->volumeSource(), toString(client->attributes()).c_str(), i);
3091 applyVolume = false;
3092 isPreempted = true;
3093 break;
3094 }
3095 // However, continue for loop to ensure no higher prio clients running on output
3096 if (client->volumeSource() == vs) {
3097 applyVolume = true;
3098 }
3099 }
3100 if (isPreempted || applyVolume) {
3101 break;
3102 }
3103 }
3104 if (!applyVolume) {
3105 continue; // next output
3106 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003107 }
François Gaffieed91f582020-01-31 10:35:37 +01003108 //FIXME: workaround for truncated touch sounds
3109 // delayed volume change for system stream to be removed when the problem is
3110 // handled by system UI
3111 status_t volStatus = checkAndSetVolume(
3112 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003113 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003114 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3115 if (volStatus != NO_ERROR) {
3116 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003117 }
3118 }
François Gaffiecfe17322018-11-07 13:41:29 +01003119 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3120 return status;
3121}
3122
François Gaffieaaac0fd2018-11-22 17:56:39 +01003123status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003124 audio_devices_t device,
3125 IVolumeCurves &volumeCurves)
3126{
3127 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3128 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003129 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3130 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003131 (index > volumeCurves.getVolumeIndexMax())) {
3132 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3133 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3134 return BAD_VALUE;
3135 }
3136 if (!audio_is_output_device(device)) {
3137 return BAD_VALUE;
3138 }
3139
3140 // Force max volume if stream cannot be muted
3141 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3142
François Gaffieaaac0fd2018-11-22 17:56:39 +01003143 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003144 volumeCurves.addCurrentVolumeIndex(device, index);
3145 return NO_ERROR;
3146}
3147
3148status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3149 int &index,
3150 audio_devices_t device)
3151{
3152 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3153 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003154 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003155 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003156 DeviceTypeSet deviceTypes = mEngine->getOutputDevicesForAttributes(
3157 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003158 }
jiabin9a3361e2019-10-01 09:38:30 -07003159 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003160}
3161
3162status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3163 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003164 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003165{
jiabin9a3361e2019-10-01 09:38:30 -07003166 if (isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003167 return BAD_VALUE;
3168 }
jiabin9a3361e2019-10-01 09:38:30 -07003169 index = curves.getVolumeIndex(deviceTypes);
3170 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003171 return NO_ERROR;
3172}
3173
3174status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3175 int &index)
3176{
3177 index = getVolumeCurves(attr).getVolumeIndexMin();
3178 return NO_ERROR;
3179}
3180
3181status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3182 int &index)
3183{
3184 index = getVolumeCurves(attr).getVolumeIndexMax();
3185 return NO_ERROR;
3186}
3187
Eric Laurent36829f92017-04-07 19:04:42 -07003188audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003189{
3190 // select one output among several suitable for global effects.
3191 // The priority is as follows:
3192 // 1: An offloaded output. If the effect ends up not being offloadable,
3193 // AudioFlinger will invalidate the track and the offloaded output
3194 // will be closed causing the effect to be moved to a PCM output.
3195 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003196 // 3: The primary output
3197 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003198
François Gaffiec005e562018-11-06 15:04:49 +01003199 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3200 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003201 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003202
Eric Laurent36829f92017-04-07 19:04:42 -07003203 if (outputs.size() == 0) {
3204 return AUDIO_IO_HANDLE_NONE;
3205 }
Eric Laurente552edb2014-03-10 17:42:56 -07003206
Eric Laurent36829f92017-04-07 19:04:42 -07003207 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3208 bool activeOnly = true;
3209
3210 while (output == AUDIO_IO_HANDLE_NONE) {
3211 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3212 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3213 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3214
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003215 for (audio_io_handle_t output : outputs) {
3216 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003217 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003218 continue;
3219 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003220 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3221 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003222 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003223 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003224 }
3225 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003226 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003227 }
3228 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003229 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003230 }
3231 }
3232 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3233 output = outputOffloaded;
3234 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3235 output = outputDeepBuffer;
3236 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3237 output = outputPrimary;
3238 } else {
3239 output = outputs[0];
3240 }
3241 activeOnly = false;
3242 }
3243
3244 if (output != mMusicEffectOutput) {
Eric Laurent6c796322019-04-09 14:13:17 -07003245 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
Eric Laurent36829f92017-04-07 19:04:42 -07003246 mpClientInterface->moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output);
3247 mMusicEffectOutput = output;
3248 }
3249
3250 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003251 return output;
3252}
3253
Eric Laurent36829f92017-04-07 19:04:42 -07003254audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3255{
3256 return selectOutputForMusicEffects();
3257}
3258
Eric Laurente0720872014-03-11 09:30:41 -07003259status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003260 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003261 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003262 int session,
3263 int id)
3264{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003265 if (session != AUDIO_SESSION_DEVICE) {
3266 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003267 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003268 index = mInputs.indexOfKey(io);
3269 if (index < 0) {
3270 ALOGW("registerEffect() unknown io %d", io);
3271 return INVALID_OPERATION;
3272 }
Eric Laurente552edb2014-03-10 17:42:56 -07003273 }
3274 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003275 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3276 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3277 || strategy == PRODUCT_STRATEGY_NONE));
3278 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003279}
3280
Eric Laurentc241b0d2018-11-28 09:08:49 -08003281status_t AudioPolicyManager::unregisterEffect(int id)
3282{
3283 if (mEffects.getEffect(id) == nullptr) {
3284 return INVALID_OPERATION;
3285 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003286 if (mEffects.isEffectEnabled(id)) {
3287 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3288 setEffectEnabled(id, false);
3289 }
3290 return mEffects.unregisterEffect(id);
3291}
3292
3293status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3294{
3295 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3296 if (effect == nullptr) {
3297 return INVALID_OPERATION;
3298 }
3299
3300 status_t status = mEffects.setEffectEnabled(id, enabled);
3301 if (status == NO_ERROR) {
3302 mInputs.trackEffectEnabled(effect, enabled);
3303 }
3304 return status;
3305}
3306
Eric Laurent6c796322019-04-09 14:13:17 -07003307
3308status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3309{
3310 mEffects.moveEffects(ids, io);
3311 return NO_ERROR;
3312}
3313
Eric Laurentc75307b2015-03-17 15:29:32 -07003314bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3315{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003316 auto vs = toVolumeSource(stream, false);
3317 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003318}
3319
3320bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3321{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003322 auto vs = toVolumeSource(stream, false);
3323 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003324}
3325
Eric Laurente0720872014-03-11 09:30:41 -07003326bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003327{
3328 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003329 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003330 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003331 return true;
3332 }
3333 }
3334 return false;
3335}
3336
Eric Laurent275e8e92014-11-30 15:14:47 -08003337// Register a list of custom mixes with their attributes and format.
3338// When a mix is registered, corresponding input and output profiles are
3339// added to the remote submix hw module. The profile contains only the
3340// parameters (sampling rate, format...) specified by the mix.
3341// The corresponding input remote submix device is also connected.
3342//
3343// When a remote submix device is connected, the address is checked to select the
3344// appropriate profile and the corresponding input or output stream is opened.
3345//
3346// When capture starts, getInputForAttr() will:
3347// - 1 look for a mix matching the address passed in attribtutes tags if any
3348// - 2 if none found, getDeviceForInputSource() will:
3349// - 2.1 look for a mix matching the attributes source
3350// - 2.2 if none found, default to device selection by policy rules
3351// At this time, the corresponding output remote submix device is also connected
3352// and active playback use cases can be transferred to this mix if needed when reconnecting
3353// after AudioTracks are invalidated
3354//
3355// When playback starts, getOutputForAttr() will:
3356// - 1 look for a mix matching the address passed in attribtutes tags if any
3357// - 2 if none found, look for a mix matching the attributes usage
3358// - 3 if none found, default to device and output selection by policy rules.
3359
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003360status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003361{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003362 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3363 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003364 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003365 sp<HwModule> rSubmixModule;
3366 // examine each mix's route type
3367 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003368 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003369 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3370 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3371 ALOGE("Unsupported Policy Mix %zu of %zu: "
3372 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3373 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003374 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003375 break;
3376 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003377 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3378 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003379 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003380 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3381 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003382 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003383 rSubmixModule = mHwModules.getModuleFromName(
3384 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3385 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003386 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003387 i);
3388 res = INVALID_OPERATION;
3389 break;
3390 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003391 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003392
Eric Laurent97ac8712018-07-27 18:59:02 -07003393 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003394 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003395 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003396 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003397 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3398 } else {
3399 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3400 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003401 }
François Gaffie036e1e92015-03-19 10:16:24 +01003402
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003403 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003404 ALOGE("Error registering mix %zu for address %s", i, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003405 res = INVALID_OPERATION;
3406 break;
3407 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003408 audio_config_t outputConfig = mix.mFormat;
3409 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003410 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3411 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003412 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3413 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003414 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003415 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address);
jiabin5740f082019-08-19 15:08:30 -07003416 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003417 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address);
François Gaffie036e1e92015-03-19 10:16:24 +01003418
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003419 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003420 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
3421 address.string(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
3422 ALOGE("Failed to set remote submix device available, type %u, address %s",
3423 mix.mDeviceType, address.string());
3424 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003425 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003426 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3427 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003428 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003429 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003430 i, mixes.size(), type, address.string());
3431
3432 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3433 mix.mDeviceType, mix.mDeviceAddress,
3434 String8(), AUDIO_FORMAT_DEFAULT);
3435 if (device == nullptr) {
3436 res = INVALID_OPERATION;
3437 break;
3438 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003439
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003440 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003441 // First try to find an already opened output supporting the device
3442 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003443 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003444
Eric Laurentc529cf62020-04-17 18:19:10 -07003445 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003446 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003447 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3448 address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003449 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003450 } else {
3451 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003452 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003453 }
3454 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003455 // If no output found, try to find a direct output profile supporting the device
3456 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3457 sp<HwModule> module = mHwModules[i];
3458 for (size_t j = 0;
3459 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3460 j++) {
3461 sp<IOProfile> profile = module->getOutputProfiles()[j];
3462 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3463 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3464 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
3465 address.string());
3466 res = INVALID_OPERATION;
3467 } else {
3468 foundOutput = true;
3469 }
3470 }
3471 }
3472 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003473 if (res != NO_ERROR) {
3474 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003475 i, type, address.string());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003476 res = INVALID_OPERATION;
3477 break;
3478 } else if (!foundOutput) {
3479 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Eric Laurent2c80be02019-01-23 18:06:37 -08003480 i, type, address.string());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003481 res = INVALID_OPERATION;
3482 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003483 } else {
3484 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003485 }
Eric Laurentc722f302014-12-10 11:21:49 -08003486 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003487 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003488 if (res != NO_ERROR) {
3489 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003490 } else if (checkOutputs) {
3491 checkForDeviceAndOutputChanges();
3492 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003493 }
3494 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003495}
3496
3497status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3498{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003499 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003500 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003501 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003502 sp<HwModule> rSubmixModule;
3503 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003504 for (const auto& mix : mixes) {
3505 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003506
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003507 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003508 rSubmixModule = mHwModules.getModuleFromName(
3509 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3510 if (rSubmixModule == 0) {
3511 res = INVALID_OPERATION;
3512 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003513 }
3514 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003515
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003516 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003517
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003518 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003519 res = INVALID_OPERATION;
3520 continue;
3521 }
3522
Kevin Rocard04ed0462019-05-02 17:53:24 -07003523 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
3524 if (getDeviceConnectionState(device, address.string()) ==
3525 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3526 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
3527 address.string(), "remote-submix",
3528 AUDIO_FORMAT_DEFAULT);
3529 if (res != OK) {
3530 ALOGE("Error making RemoteSubmix device unavailable for mix "
3531 "with type %d, address %s", device, address.string());
3532 }
3533 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003534 }
jiabin5740f082019-08-19 15:08:30 -07003535 rSubmixModule->removeOutputProfile(address.c_str());
3536 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003537
Kevin Rocard153f92d2018-12-18 18:33:28 -08003538 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003539 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003540 res = INVALID_OPERATION;
3541 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003542 } else {
3543 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003544 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003545 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003546 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003547 if (res == NO_ERROR && checkOutputs) {
3548 checkForDeviceAndOutputChanges();
3549 updateCallAndOutputRouting();
3550 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003551 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003552}
3553
Mikhail Naganov100f0122018-11-29 11:22:16 -08003554void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3555{
3556 size_t i = 0;
3557 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3558 for (const auto& fmt : mManualSurroundFormats) {
3559 if (i++ != 0) dst->append(", ");
3560 std::string sfmt;
3561 FormatConverter::toString(fmt, sfmt);
3562 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3563 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3564 }
3565}
3566
Eric Laurentc529cf62020-04-17 18:19:10 -07003567// Returns true if all devices types match the predicate and are supported by one HW module
3568bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003569 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003570 std::function<bool(audio_devices_t)> predicate,
3571 const char *context) {
3572 for (size_t i = 0; i < devices.size(); i++) {
3573 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003574 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent0e26e3f2020-04-29 14:24:16 -07003575 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, true /*matchAddress*/);
Eric Laurentc529cf62020-04-17 18:19:10 -07003576 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003577 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003578 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003579 return false;
3580 }
3581 }
3582 return true;
3583}
3584
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003585status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003586 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003587 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003588 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3589 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003590 }
3591 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003592 if (res != NO_ERROR) {
3593 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3594 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003595 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003596
3597 checkForDeviceAndOutputChanges();
3598 updateCallAndOutputRouting();
3599
3600 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003601}
3602
3603status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3604 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003605 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3606 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003607 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003608 __FUNCTION__, uid);
3609 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003610 }
3611
Eric Laurentc529cf62020-04-17 18:19:10 -07003612 checkForDeviceAndOutputChanges();
3613 updateCallAndOutputRouting();
3614
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003615 return res;
3616}
3617
Eric Laurent2517af32020-11-25 15:31:27 +01003618
jiabin0a488932020-08-07 17:32:40 -07003619status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3620 device_role_t role,
3621 const AudioDeviceTypeAddrVector &devices) {
3622 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3623 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003624
Eric Laurentc529cf62020-04-17 18:19:10 -07003625 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003626 return BAD_VALUE;
3627 }
jiabin0a488932020-08-07 17:32:40 -07003628 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003629 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003630 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3631 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003632 return status;
3633 }
3634
3635 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003636
3637 bool forceVolumeReeval = false;
3638 // FIXME: workaround for truncated touch sounds
3639 // to be removed when the problem is handled by system UI
3640 uint32_t delayMs = 0;
3641 if (strategy == mCommunnicationStrategy) {
3642 forceVolumeReeval = true;
3643 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3644 updateInputRouting();
3645 }
3646 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003647
3648 return NO_ERROR;
3649}
3650
3651void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs)
3652{
3653 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003654 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003655 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003656 // Only apply special touch sound delay once
3657 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003658 }
3659 for (size_t i = 0; i < mOutputs.size(); i++) {
3660 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3661 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02003662 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
3663 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003664 // As done in setDeviceConnectionState, we could also fix default device issue by
3665 // preventing the force re-routing in case of default dev that distinguishes on address.
3666 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02003667 bool forceRouting = !newDevices.isEmpty();
3668 waitMs = setOutputDevices(outputDesc, newDevices, forceRouting, delayMs, nullptr,
3669 true /*requiresMuteCheck*/,
3670 !forceRouting /*requiresVolumeCheck*/);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003671 // Only apply special touch sound delay once
3672 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003673 }
3674 if (forceVolumeReeval && !newDevices.isEmpty()) {
3675 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
3676 }
3677 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01003678 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003679}
3680
Eric Laurent2517af32020-11-25 15:31:27 +01003681void AudioPolicyManager::updateInputRouting() {
3682 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05303683 // Skip for hotword recording as the input device switch
3684 // is handled within sound trigger HAL
3685 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
3686 continue;
3687 }
Eric Laurent2517af32020-11-25 15:31:27 +01003688 auto newDevice = getNewInputDevice(activeDesc);
3689 // Force new input selection if the new device can not be reached via current input
3690 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
3691 setInputDevice(activeDesc->mIoHandle, newDevice);
3692 } else {
3693 closeInput(activeDesc->mIoHandle);
3694 }
3695 }
3696}
3697
jiabin0a488932020-08-07 17:32:40 -07003698status_t AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
3699 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003700{
Eric Laurentfecbceb2021-02-09 14:46:43 +01003701 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003702
jiabin0a488932020-08-07 17:32:40 -07003703 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003704 if (status != NO_ERROR) {
Eric Laurent2517af32020-11-25 15:31:27 +01003705 ALOGV("Engine could not remove preferred device for strategy %d status %d",
3706 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003707 return status;
3708 }
3709
3710 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003711
3712 bool forceVolumeReeval = false;
3713 // FIXME: workaround for truncated touch sounds
3714 // to be removed when the problem is handled by system UI
3715 uint32_t delayMs = 0;
3716 if (strategy == mCommunnicationStrategy) {
3717 forceVolumeReeval = true;
3718 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3719 updateInputRouting();
3720 }
3721 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003722
3723 return NO_ERROR;
3724}
3725
jiabin0a488932020-08-07 17:32:40 -07003726status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
3727 device_role_t role,
3728 AudioDeviceTypeAddrVector &devices) {
3729 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003730}
3731
Jiabin Huang3b98d322020-09-03 17:54:16 +00003732status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
3733 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3734 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3735 dumpAudioDeviceTypeAddrVector(devices).c_str());
3736
Mikhail Naganov55773032020-10-01 15:08:13 -07003737 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003738 return BAD_VALUE;
3739 }
3740 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
3741 ALOGW_IF(status != NO_ERROR,
3742 "Engine could not set preferred devices %s for audio source %d role %d",
3743 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3744
3745 return status;
3746}
3747
3748status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
3749 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
3750 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
3751 dumpAudioDeviceTypeAddrVector(devices).c_str());
3752
Mikhail Naganov55773032020-10-01 15:08:13 -07003753 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003754 return BAD_VALUE;
3755 }
3756 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
3757 ALOGW_IF(status != NO_ERROR,
3758 "Engine could not add preferred devices %s for audio source %d role %d",
3759 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
3760
Eric Laurent2517af32020-11-25 15:31:27 +01003761 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003762 return status;
3763}
3764
3765status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
3766 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
3767{
3768 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
3769 dumpAudioDeviceTypeAddrVector(devices).c_str());
3770
Mikhail Naganov55773032020-10-01 15:08:13 -07003771 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003772 return BAD_VALUE;
3773 }
3774
3775 status_t status = mEngine->removeDevicesRoleForCapturePreset(
3776 audioSource, role, devices);
3777 ALOGW_IF(status != NO_ERROR,
3778 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
3779
Eric Laurent2517af32020-11-25 15:31:27 +01003780 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003781 return status;
3782}
3783
3784status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
3785 device_role_t role) {
3786 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
3787
3788 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
3789 ALOGW_IF(status != NO_ERROR,
3790 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
3791
Eric Laurent2517af32020-11-25 15:31:27 +01003792 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00003793 return status;
3794}
3795
3796status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
3797 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
3798 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
3799}
3800
Oscar Azucena90e77632019-11-27 17:12:28 -08003801status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07003802 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003803 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003804 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3805 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08003806 }
Oscar Azucena90e77632019-11-27 17:12:28 -08003807 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
3808 if (status != NO_ERROR) {
3809 ALOGE("%s() could not set device affinity for userId %d",
3810 __FUNCTION__, userId);
3811 return status;
3812 }
3813
3814 // reevaluate outputs for all devices
3815 checkForDeviceAndOutputChanges();
3816 updateCallAndOutputRouting();
3817
3818 return NO_ERROR;
3819}
3820
3821status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01003822 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena90e77632019-11-27 17:12:28 -08003823 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
3824 if (status != NO_ERROR) {
3825 ALOGE("%s() Could not remove all device affinities fo userId = %d",
3826 __FUNCTION__, userId);
3827 return status;
3828 }
3829
3830 // reevaluate outputs for all devices
3831 checkForDeviceAndOutputChanges();
3832 updateCallAndOutputRouting();
3833
3834 return NO_ERROR;
3835}
3836
Andy Hungc29d82b2018-10-05 12:23:17 -07003837void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07003838{
Andy Hungc29d82b2018-10-05 12:23:17 -07003839 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00003840 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07003841 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07003842 std::string stateLiteral;
3843 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07003844 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003845 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
3846 "communications", "media", "record", "dock", "system",
3847 "HDMI system audio", "encoded surround output", "vibrate ringing" };
3848 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
3849 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08003850 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
3851 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
3852 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
3853 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
3854 dst->append(" (MANUAL: ");
3855 dumpManualSurroundFormats(dst);
3856 dst->append(")");
3857 }
3858 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07003859 }
Andy Hungc29d82b2018-10-05 12:23:17 -07003860 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
3861 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00003862 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Andy Hungc29d82b2018-10-05 12:23:17 -07003863 dst->appendFormat(" Config source: %s\n", mConfig.getSource().c_str()); // getConfig not const
Eric Laurent2517af32020-11-25 15:31:27 +01003864
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003865 dst->append("\n");
3866 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
3867 dst->append("\n");
3868 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003869 mHwModulesAll.dump(dst);
3870 mOutputs.dump(dst);
3871 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00003872 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07003873 mAudioPatches.dump(dst);
3874 mPolicyMixes.dump(dst);
3875 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01003876
Kevin Rocardb99cc752019-03-21 20:52:24 -07003877 dst->appendFormat(" AllowedCapturePolicies:\n");
3878 for (auto& policy : mAllowedCapturePolicies) {
3879 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
3880 }
3881
François Gaffiec005e562018-11-06 15:04:49 +01003882 dst->appendFormat("\nPolicy Engine dump:\n");
3883 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07003884}
3885
3886status_t AudioPolicyManager::dump(int fd)
3887{
3888 String8 result;
3889 dump(&result);
Andy Hungbb54e202018-10-05 11:42:02 -07003890 write(fd, result.string(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07003891 return NO_ERROR;
3892}
3893
Kevin Rocardb99cc752019-03-21 20:52:24 -07003894status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
3895{
3896 mAllowedCapturePolicies[uid] = capturePolicy;
3897 return NO_ERROR;
3898}
3899
Eric Laurente552edb2014-03-10 17:42:56 -07003900// This function checks for the parameters which can be offloaded.
3901// This can be enhanced depending on the capability of the DSP and policy
3902// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01003903audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07003904{
Eric Laurent90fe31c2020-11-26 20:06:35 +01003905 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07003906 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01003907 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07003908 offloadInfo.format,
3909 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
3910 offloadInfo.has_video);
3911
jiabin2b9d5a12021-12-10 01:06:29 +00003912 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01003913 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003914 }
3915
3916 // See if there is a profile to support this.
3917 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01003918 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07003919 offloadInfo.sample_rate,
3920 offloadInfo.format,
3921 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10003922 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
3923 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01003924 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
3925 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
3926 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01003927 if (profile == nullptr) {
3928 return AUDIO_OFFLOAD_NOT_SUPPORTED;
3929 }
3930 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
3931 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
3932 }
3933 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07003934}
3935
Michael Chana94fbb22018-04-24 14:31:19 +10003936bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
3937 const audio_attributes_t& attributes) {
3938 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01003939 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00003940 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
3941 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10003942 config.sample_rate,
3943 config.format,
3944 config.channel_mask,
3945 output_flags,
3946 true /* directOnly */);
3947 ALOGV("%s() profile %sfound with name: %s, "
3948 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3949 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07003950 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10003951 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01003952
3953 // also try the MSD module if compatible profile not found
3954 if (profile == nullptr) {
3955 profile = getMsdProfileForOutput(outputDevices,
3956 config.sample_rate,
3957 config.format,
3958 config.channel_mask,
3959 output_flags,
3960 true /* directOnly */);
3961 ALOGV("%s() MSD profile %sfound with name: %s, "
3962 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
3963 __FUNCTION__, profile != 0 ? "" : "NOT ",
3964 (profile != 0 ? profile->getTagName().c_str() : "null"),
3965 config.sample_rate, config.format, config.channel_mask, output_flags);
3966 }
3967 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10003968}
3969
jiabin2b9d5a12021-12-10 01:06:29 +00003970bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
3971 bool durationIgnored) {
3972 if (mMasterMono) {
3973 return false; // no offloading if mono is set.
3974 }
3975
3976 // Check if offload has been disabled
3977 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
3978 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
3979 return false;
3980 }
3981
3982 // Check if stream type is music, then only allow offload as of now.
3983 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
3984 {
3985 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
3986 return false;
3987 }
3988
3989 //TODO: enable audio offloading with video when ready
3990 const bool allowOffloadWithVideo =
3991 property_get_bool("audio.offload.video", false /* default_value */);
3992 if (offloadInfo.has_video && !allowOffloadWithVideo) {
3993 ALOGV("%s: has_video == true, returning false", __func__);
3994 return false;
3995 }
3996
3997 //If duration is less than minimum value defined in property, return false
3998 const int min_duration_secs = property_get_int32(
3999 "audio.offload.min.duration.secs", -1 /* default_value */);
4000 if (!durationIgnored) {
4001 if (min_duration_secs >= 0) {
4002 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4003 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4004 __func__, min_duration_secs);
4005 return false;
4006 }
4007 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4008 ALOGV("%s: Offload denied by duration < default min(=%u)",
4009 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4010 return false;
4011 }
4012 }
4013
4014 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4015 // creating an offloaded track and tearing it down immediately after start when audioflinger
4016 // detects there is an active non offloadable effect.
4017 // FIXME: We should check the audio session here but we do not have it in this context.
4018 // This may prevent offloading in rare situations where effects are left active by apps
4019 // in the background.
4020 if (mEffects.isNonOffloadableEffectEnabled()) {
4021 return false;
4022 }
4023
4024 return true;
4025}
4026
4027audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4028 const audio_config_t *config) {
4029 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4030 offloadInfo.format = config->format;
4031 offloadInfo.sample_rate = config->sample_rate;
4032 offloadInfo.channel_mask = config->channel_mask;
4033 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4034 offloadInfo.has_video = false;
4035 offloadInfo.is_streaming = false;
4036 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4037
4038 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4039 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4040 audio_flags_to_audio_output_flags(attr->flags, &flags);
4041 // only retain flags that will drive compressed offload or passthrough
4042 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4043 if (offloadPossible) {
4044 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4045 }
4046 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4047
Dorin Drimusfae3c642022-03-17 18:36:30 +01004048 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004049 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004050 DeviceVector outputDevices = engineOutputDevices;
4051 // the MSD module checks for different conditions and output devices
4052 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4053 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4054 continue;
4055 }
4056 outputDevices = getMsdAudioOutDevices();
4057 }
jiabin2b9d5a12021-12-10 01:06:29 +00004058 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004059 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004060 config->sample_rate, nullptr /*updatedSamplingRate*/,
4061 config->format, nullptr /*updatedFormat*/,
4062 config->channel_mask, nullptr /*updatedChannelMask*/,
4063 flags)) {
4064 continue;
4065 }
4066 // reject profiles not corresponding to a device currently available
4067 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4068 continue;
4069 }
4070 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4071 != AUDIO_OUTPUT_FLAG_NONE) {
jiabinc6132d62022-01-01 07:36:31 +00004072 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004073 != AUDIO_DIRECT_NOT_SUPPORTED) {
4074 // Already reports offload gapless supported. No need to report offload support.
4075 continue;
4076 }
4077 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4078 != AUDIO_OUTPUT_FLAG_NONE) {
4079 // If offload gapless is reported, no need to report offload support.
4080 directMode = (audio_direct_mode_t) ((directMode &
4081 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4082 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4083 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004084 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004085 }
4086 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004087 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004088 }
4089 }
4090 }
4091 return directMode;
4092}
4093
Dorin Drimusf2196d82022-01-03 12:11:18 +01004094status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4095 AudioProfileVector& audioProfilesVector) {
Dorin Drimus76e69572022-09-23 15:28:51 +00004096 if (mEffects.isNonOffloadableEffectEnabled()) {
4097 return OK;
4098 }
Dorin Drimusf2196d82022-01-03 12:11:18 +01004099 AudioDeviceTypeAddrVector devices;
Andy Hung6d23c0f2022-02-16 09:37:15 -08004100 status_t status = getDevicesForAttributes(*attr, &devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004101 if (status != OK) {
4102 return status;
4103 }
4104 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4105 if (devices.empty()) {
4106 return OK; // no output devices for the attributes
4107 }
4108
4109 for (const auto& hwModule : mHwModules) {
Dorin Drimus94d94412022-02-02 09:05:02 +01004110 // the MSD module checks for different conditions
4111 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4112 continue;
4113 }
4114 for (const auto& outputProfile : hwModule->getOutputProfiles()) {
4115 if (!outputProfile->asAudioPort()->isDirectOutput()) {
Dorin Drimusf2196d82022-01-03 12:11:18 +01004116 continue;
4117 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004118 // allow only profiles that support all the available and routed devices
4119 if (outputProfile->getSupportedDevices().getDevicesFromDeviceTypeAddrVec(devices).size()
Dorin Drimusf2196d82022-01-03 12:11:18 +01004120 != devices.size()) {
4121 continue;
4122 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004123 audioProfilesVector.addAllValidProfiles(
4124 outputProfile->asAudioPort()->getAudioProfiles());
Dorin Drimusf2196d82022-01-03 12:11:18 +01004125 }
4126 }
Dorin Drimus94d94412022-02-02 09:05:02 +01004127
4128 // add the direct profiles from MSD if present and has audio patches to all the output(s)
4129 const auto& msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
4130 if (msdModule != nullptr) {
4131 if (msdHasPatchesToAllDevices(devices)) {
4132 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
4133 for (const auto& outputProfile : msdModule->getOutputProfiles()) {
4134 if (!outputProfile->asAudioPort()->isDirectOutput()) {
4135 continue;
4136 }
4137 audioProfilesVector.addAllValidProfiles(
4138 outputProfile->asAudioPort()->getAudioProfiles());
4139 }
4140 } else {
4141 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
4142 }
4143 }
4144
Dorin Drimusf2196d82022-01-03 12:11:18 +01004145 return NO_ERROR;
4146}
4147
Eric Laurent6a94d692014-05-20 11:18:06 -07004148status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4149 audio_port_type_t type,
4150 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004151 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004152 unsigned int *generation)
4153{
jiabin19cdba52020-11-24 11:28:58 -08004154 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4155 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004156 return BAD_VALUE;
4157 }
4158 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004159 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004160 *num_ports = 0;
4161 }
4162
4163 size_t portsWritten = 0;
4164 size_t portsMax = *num_ports;
4165 *num_ports = 0;
4166 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004167 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4168 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004169 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004170 for (const auto& dev : mAvailableOutputDevices) {
4171 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004172 continue;
4173 }
4174 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004175 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004176 }
4177 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004178 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004179 }
4180 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004181 for (const auto& dev : mAvailableInputDevices) {
4182 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004183 continue;
4184 }
4185 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004186 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004187 }
4188 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004189 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004190 }
4191 }
4192 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4193 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4194 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4195 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4196 }
4197 *num_ports += mInputs.size();
4198 }
4199 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004200 size_t numOutputs = 0;
4201 for (size_t i = 0; i < mOutputs.size(); i++) {
4202 if (!mOutputs[i]->isDuplicated()) {
4203 numOutputs++;
4204 if (portsWritten < portsMax) {
4205 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4206 }
4207 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004208 }
Eric Laurent84c70242014-06-23 08:46:27 -07004209 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004210 }
4211 }
4212 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004213 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004214 return NO_ERROR;
4215}
4216
jiabin19cdba52020-11-24 11:28:58 -08004217status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004218{
Eric Laurent99fcae42018-05-17 16:59:18 -07004219 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4220 return BAD_VALUE;
4221 }
4222 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4223 if (dev != 0) {
4224 dev->toAudioPort(port);
4225 return NO_ERROR;
4226 }
4227 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4228 if (dev != 0) {
4229 dev->toAudioPort(port);
4230 return NO_ERROR;
4231 }
4232 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4233 if (out != 0) {
4234 out->toAudioPort(port);
4235 return NO_ERROR;
4236 }
4237 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4238 if (in != 0) {
4239 in->toAudioPort(port);
4240 return NO_ERROR;
4241 }
4242 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004243}
4244
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004245status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4246 audio_patch_handle_t *handle,
4247 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004248{
François Gaffieafd4cea2019-11-18 15:50:22 +01004249 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004250 if (handle == NULL || patch == NULL) {
4251 return BAD_VALUE;
4252 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004253 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004254 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004255 return BAD_VALUE;
4256 }
4257 // only one source per audio patch supported for now
4258 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004259 return INVALID_OPERATION;
4260 }
Eric Laurent874c42872014-08-08 15:13:39 -07004261 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004262 return INVALID_OPERATION;
4263 }
Eric Laurent874c42872014-08-08 15:13:39 -07004264 for (size_t i = 0; i < patch->num_sinks; i++) {
4265 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4266 return INVALID_OPERATION;
4267 }
4268 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004269
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004270 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4271 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4272 if (srcDevice == nullptr || sinkDevice == nullptr) {
4273 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4274 return BAD_VALUE;
4275 }
4276 ALOGV("%s between source %s and sink %s", __func__,
4277 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4278 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4279 // Default attributes, default volume priority, not to infer with non raw audio patches.
4280 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4281 const struct audio_port_config *source = &patch->sources[0];
4282 sp<SourceClientDescriptor> sourceDesc =
4283 new InternalSourceClientDescriptor(
4284 portId, uid, attributes, *source, srcDevice, sinkDevice,
4285 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4286
4287 status_t status =
4288 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4289
4290 if (status != NO_ERROR) {
4291 return INVALID_OPERATION;
4292 }
4293 mAudioSources.add(portId, sourceDesc);
4294 return NO_ERROR;
4295}
4296
4297status_t AudioPolicyManager::connectAudioSourceToSink(
4298 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4299 const struct audio_patch *patch,
4300 audio_patch_handle_t &handle,
4301 uid_t uid, uint32_t delayMs)
4302{
4303 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4304 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4305 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4306 return INVALID_OPERATION;
4307 }
4308 sourceDesc->connect(handle, sinkDevice);
4309 if (isMsdPatch(handle)) {
4310 return NO_ERROR;
4311 }
4312 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4313 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4314 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4315 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4316 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4317 goto FailurePatchAdded;
4318 }
4319 status = swOutput->start();
4320 if (status != NO_ERROR) {
4321 goto FailureSourceAdded;
4322 }
4323 swOutput->addClient(sourceDesc);
4324 status = startSource(swOutput, sourceDesc, &delayMs);
4325 if (status != NO_ERROR) {
4326 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4327 goto FailureSourceActive;
4328 }
4329 if (delayMs != 0) {
4330 usleep(delayMs * 1000);
4331 }
4332 return NO_ERROR;
4333
4334FailureSourceActive:
4335 swOutput->stop();
4336 releaseOutput(sourceDesc->portId());
4337FailureSourceAdded:
4338 sourceDesc->setSwOutput(nullptr);
4339FailurePatchAdded:
4340 releaseAudioPatchInternal(handle);
4341 return INVALID_OPERATION;
4342}
4343
4344status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4345 audio_patch_handle_t *handle,
4346 uid_t uid, uint32_t delayMs,
4347 const sp<SourceClientDescriptor>& sourceDesc)
4348{
4349 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004350 sp<AudioPatch> patchDesc;
4351 ssize_t index = mAudioPatches.indexOfKey(*handle);
4352
François Gaffieafd4cea2019-11-18 15:50:22 +01004353 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4354 patch->sources[0].role,
4355 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004356#if LOG_NDEBUG == 0
4357 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004358 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4359 patch->sinks[i].role,
4360 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004361 }
4362#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004363
4364 if (index >= 0) {
4365 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004366 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4367 __func__, mUidCached, patchDesc->getUid(), uid);
4368 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004369 return INVALID_OPERATION;
4370 }
4371 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004372 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004373 }
4374
4375 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004376 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004377 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004378 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004379 return BAD_VALUE;
4380 }
Eric Laurent84c70242014-06-23 08:46:27 -07004381 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4382 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004383 if (patchDesc != 0) {
4384 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004385 ALOGV("%s source id differs for patch current id %d new id %d",
4386 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004387 return BAD_VALUE;
4388 }
4389 }
Eric Laurent874c42872014-08-08 15:13:39 -07004390 DeviceVector devices;
4391 for (size_t i = 0; i < patch->num_sinks; i++) {
4392 // Only support mix to devices connection
4393 // TODO add support for mix to mix connection
4394 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004395 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004396 return INVALID_OPERATION;
4397 }
4398 sp<DeviceDescriptor> devDesc =
4399 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4400 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004401 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004402 return BAD_VALUE;
4403 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004404
François Gaffie11d30102018-11-02 16:09:09 +01004405 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004406 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004407 NULL, // updatedSamplingRate
4408 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004409 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004410 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004411 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004412 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004413 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004414 return INVALID_OPERATION;
4415 }
4416 devices.add(devDesc);
4417 }
4418 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004419 return INVALID_OPERATION;
4420 }
Eric Laurent874c42872014-08-08 15:13:39 -07004421
Eric Laurent6a94d692014-05-20 11:18:06 -07004422 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004423 ALOGV("%s setting device %s on output %d",
4424 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
François Gaffie11d30102018-11-02 16:09:09 +01004425 setOutputDevices(outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004426 index = mAudioPatches.indexOfKey(*handle);
4427 if (index >= 0) {
4428 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004429 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004430 }
4431 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004432 patchDesc->setUid(uid);
4433 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004434 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004435 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004436 return INVALID_OPERATION;
4437 }
4438 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4439 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
4440 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07004441 // only one sink supported when connecting an input device to a mix
4442 if (patch->num_sinks > 1) {
4443 return INVALID_OPERATION;
4444 }
François Gaffie53615e22015-03-19 09:24:12 +01004445 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004446 if (inputDesc == NULL) {
4447 return BAD_VALUE;
4448 }
4449 if (patchDesc != 0) {
4450 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
4451 return BAD_VALUE;
4452 }
4453 }
François Gaffie11d30102018-11-02 16:09:09 +01004454 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07004455 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004456 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004457 return BAD_VALUE;
4458 }
4459
François Gaffie11d30102018-11-02 16:09:09 +01004460 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08004461 patch->sinks[0].sample_rate,
4462 NULL, /*updatedSampleRate*/
4463 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004464 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004465 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004466 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08004467 // FIXME for the parameter type,
4468 // and the NONE
4469 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07004470 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004471 return INVALID_OPERATION;
4472 }
4473 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01004474 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01004475 device->toString().c_str(), inputDesc->mIoHandle);
4476 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004477 index = mAudioPatches.indexOfKey(*handle);
4478 if (index >= 0) {
4479 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004480 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004481 }
4482 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004483 patchDesc->setUid(uid);
4484 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004485 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01004486 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004487 return INVALID_OPERATION;
4488 }
4489 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
4490 // device to device connection
4491 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004492 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004493 return BAD_VALUE;
4494 }
4495 }
François Gaffie11d30102018-11-02 16:09:09 +01004496 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07004497 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01004498 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07004499 return BAD_VALUE;
4500 }
Eric Laurent874c42872014-08-08 15:13:39 -07004501
Eric Laurent6a94d692014-05-20 11:18:06 -07004502 //update source and sink with our own data as the data passed in the patch may
4503 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01004504 PatchBuilder patchBuilder;
4505 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004506
4507 // if first sink is to MSD, establish single MSD patch
4508 if (getMsdAudioOutDevices().contains(
4509 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
4510 ALOGV("%s patching to MSD", __FUNCTION__);
4511 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
4512 goto installPatch;
4513 }
4514
François Gaffieafd4cea2019-11-18 15:50:22 +01004515 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
4516 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07004517
Eric Laurent874c42872014-08-08 15:13:39 -07004518 for (size_t i = 0; i < patch->num_sinks; i++) {
4519 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004520 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004521 return INVALID_OPERATION;
4522 }
François Gaffie11d30102018-11-02 16:09:09 +01004523 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07004524 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01004525 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07004526 return BAD_VALUE;
4527 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004528 audio_port_config sinkPortConfig = {};
4529 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
4530 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004531
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004532 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
4533 // volume management purpose (tracking activity)
4534 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
4535 // in config XML to reach the sink so that is can be declared as available.
4536 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
4537 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004538 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004539 // take care of dynamic routing for SwOutput selection,
4540 audio_attributes_t attributes = sourceDesc->attributes();
4541 audio_stream_type_t stream = sourceDesc->stream();
4542 audio_attributes_t resultAttr;
4543 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4544 config.sample_rate = sourceDesc->config().sample_rate;
4545 config.channel_mask = sourceDesc->config().channel_mask;
4546 config.format = sourceDesc->config().format;
4547 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4548 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
4549 bool isRequestedDeviceForExclusiveUse = false;
4550 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004551 bool isSpatialized;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004552 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
4553 &stream, sourceDesc->uid(), &config, &flags,
4554 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02004555 nullptr, &outputType, &isSpatialized);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004556 if (output == AUDIO_IO_HANDLE_NONE) {
4557 ALOGV("%s no output for device %s",
4558 __FUNCTION__, sinkDevice->toString().c_str());
4559 return INVALID_OPERATION;
4560 }
4561 outputDesc = mOutputs.valueFor(output);
4562 if (outputDesc->isDuplicated()) {
4563 ALOGE("%s output is duplicated", __func__);
4564 return INVALID_OPERATION;
4565 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004566 bool closeOutput = outputDesc->mDirectOpenCount != 0;
4567 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004568 } else {
4569 // Same for "raw patches" aka created from createAudioPatch API
4570 SortedVector<audio_io_handle_t> outputs =
4571 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
4572 // if the sink device is reachable via an opened output stream, request to
4573 // go via this output stream by adding a second source to the patch
4574 // description
4575 output = selectOutput(outputs);
4576 if (output == AUDIO_IO_HANDLE_NONE) {
4577 ALOGE("%s no output available for internal patch sink", __func__);
4578 return INVALID_OPERATION;
4579 }
4580 outputDesc = mOutputs.valueFor(output);
4581 if (outputDesc->isDuplicated()) {
4582 ALOGV("%s output for device %s is duplicated",
4583 __func__, sinkDevice->toString().c_str());
4584 return INVALID_OPERATION;
4585 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004586 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004587 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07004588 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08004589 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07004590 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02004591 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004592 // - called from startAudioSource (aka sourceDesc is not internal) and source device
4593 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01004594 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
4595 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01004596 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004597 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01004598 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07004599 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07004600 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07004601 return INVALID_OPERATION;
4602 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004603 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02004604 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004605 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08004606 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01004607 // for volume control, we may need a valid stream
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004608 srcMixPortConfig.ext.mix.usecase.stream = !sourceDesc->isInternal() ?
4609 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
4610 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01004611 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07004612 }
Eric Laurent83b88082014-06-20 18:31:16 -07004613 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004614 }
4615 // TODO: check from routing capabilities in config file and other conflicting patches
4616
Dean Wheatley8bee85a2021-02-10 16:02:23 +11004617installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01004618 status_t status = installPatch(
4619 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07004620 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004621 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07004622 return INVALID_OPERATION;
4623 }
4624 } else {
4625 return BAD_VALUE;
4626 }
4627 } else {
4628 return BAD_VALUE;
4629 }
4630 return NO_ERROR;
4631}
4632
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004633status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004634{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004635 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004636 ssize_t index = mAudioPatches.indexOfKey(handle);
4637
4638 if (index < 0) {
4639 return BAD_VALUE;
4640 }
4641 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004642 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
4643 __func__, mUidCached, patchDesc->getUid(), uid);
4644 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004645 return INVALID_OPERATION;
4646 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004647 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4648 for (size_t i = 0; i < mAudioSources.size(); i++) {
4649 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4650 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
4651 portId = sourceDesc->portId();
4652 break;
4653 }
4654 }
4655 return portId != AUDIO_PORT_HANDLE_NONE ?
4656 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01004657}
Eric Laurent6a94d692014-05-20 11:18:06 -07004658
François Gaffieafd4cea2019-11-18 15:50:22 +01004659status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004660 uint32_t delayMs,
4661 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01004662{
4663 ALOGV("%s patch %d", __func__, handle);
4664 if (mAudioPatches.indexOfKey(handle) < 0) {
4665 ALOGE("%s: no patch found with handle=%d", __func__, handle);
4666 return BAD_VALUE;
4667 }
4668 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004669 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01004670 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07004671 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004672 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004673 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004674 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004675 return BAD_VALUE;
4676 }
4677
François Gaffie11d30102018-11-02 16:09:09 +01004678 setOutputDevices(outputDesc,
4679 getNewOutputDevices(outputDesc, true /*fromCache*/),
4680 true,
4681 0,
4682 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07004683 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
4684 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01004685 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004686 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004687 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004688 return BAD_VALUE;
4689 }
4690 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08004691 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07004692 true,
4693 NULL);
4694 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004695 status_t status =
4696 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
4697 ALOGV("%s patch panel returned %d patchHandle %d",
4698 __func__, status, patchDesc->getAfHandle());
4699 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07004700 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07004701 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004702 // SW or HW Bridge
4703 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
4704 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02004705 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004706 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
4707 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
4708 outputDesc = sourceDesc->swOutput().promote();
4709 }
4710 if (outputDesc == nullptr) {
4711 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
4712 // releaseOutput has already called closeOutput in case of direct output
4713 return NO_ERROR;
4714 }
François Gaffie1765c5b2022-04-26 12:48:49 +02004715 patchHandle = outputDesc->getPatchHandle();
4716 // When a Sw bridge is released, the mixer used by this bridge will release its
4717 // patch at AudioFlinger side. Hence, the mixer audio patch must be recreated
4718 // Reuse patch handle to force audio flinger removing initial mixer patch removal
4719 // updating hal patch handle (prevent leaks).
4720 // While using a HwBridge, force reconsidering device only if not reusing an existing
4721 // output and no more activity on output (will force to close).
4722 bool force = sourceDesc->useSwBridge() ||
4723 (sourceDesc->canCloseOutput() && !outputDesc->isActive());
4724 // APM pattern is to have always outputs opened / patch realized for reachable devices.
4725 // Update device may result to NONE (empty), coupled with force, it releases the patch.
4726 // Reconsider device only for cases:
4727 // 1 / Active Output
4728 // 2 / Inactive Output previously hosting HwBridge
4729 // 3 / Inactive Output previously hosting SwBridge that can be closed.
4730 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
4731 sourceDesc->canCloseOutput();
4732 setOutputDevices(outputDesc,
4733 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
4734 outputDesc->devices(),
4735 force,
4736 0,
4737 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004738 } else {
4739 return BAD_VALUE;
4740 }
4741 } else {
4742 return BAD_VALUE;
4743 }
4744 return NO_ERROR;
4745}
4746
4747status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
4748 struct audio_patch *patches,
4749 unsigned int *generation)
4750{
François Gaffie53615e22015-03-19 09:24:12 +01004751 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004752 return BAD_VALUE;
4753 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004754 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01004755 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07004756}
4757
Eric Laurente1715a42014-05-20 11:30:42 -07004758status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07004759{
Eric Laurente1715a42014-05-20 11:30:42 -07004760 ALOGV("setAudioPortConfig()");
4761
4762 if (config == NULL) {
4763 return BAD_VALUE;
4764 }
4765 ALOGV("setAudioPortConfig() on port handle %d", config->id);
4766 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07004767 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
4768 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07004769 }
4770
Eric Laurenta121f902014-06-03 13:32:54 -07004771 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07004772 if (config->type == AUDIO_PORT_TYPE_MIX) {
4773 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004774 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004775 if (outputDesc == NULL) {
4776 return BAD_VALUE;
4777 }
Eric Laurent84c70242014-06-23 08:46:27 -07004778 ALOG_ASSERT(!outputDesc->isDuplicated(),
4779 "setAudioPortConfig() called on duplicated output %d",
4780 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07004781 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004782 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01004783 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07004784 if (inputDesc == NULL) {
4785 return BAD_VALUE;
4786 }
Eric Laurenta121f902014-06-03 13:32:54 -07004787 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004788 } else {
4789 return BAD_VALUE;
4790 }
4791 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
4792 sp<DeviceDescriptor> deviceDesc;
4793 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
4794 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
4795 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
4796 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
4797 } else {
4798 return BAD_VALUE;
4799 }
4800 if (deviceDesc == NULL) {
4801 return BAD_VALUE;
4802 }
Eric Laurenta121f902014-06-03 13:32:54 -07004803 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07004804 } else {
4805 return BAD_VALUE;
4806 }
4807
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004808 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004809 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
4810 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07004811 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07004812 audioPortConfig->toAudioPortConfig(&newConfig, config);
4813 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07004814 }
Eric Laurenta121f902014-06-03 13:32:54 -07004815 if (status != NO_ERROR) {
4816 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07004817 }
Eric Laurente1715a42014-05-20 11:30:42 -07004818
4819 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07004820}
4821
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004822void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
4823{
Eric Laurentd60560a2015-04-10 11:31:20 -07004824 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004825 clearAudioPatches(uid);
4826 clearSessionRoutes(uid);
4827}
4828
Eric Laurent6a94d692014-05-20 11:18:06 -07004829void AudioPolicyManager::clearAudioPatches(uid_t uid)
4830{
Eric Laurent0add0fd2014-12-04 18:58:14 -08004831 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004832 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01004833 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08004834 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07004835 }
4836 }
4837}
4838
François Gaffiec005e562018-11-06 15:04:49 +01004839void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004840{
François Gaffiec005e562018-11-06 15:04:49 +01004841 // Take the first attributes following the product strategy as it is used to retrieve the routed
4842 // device. All attributes wihin a strategy follows the same "routing strategy"
4843 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
4844 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01004845 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004846 for (size_t j = 0; j < mOutputs.size(); j++) {
4847 if (mOutputs.keyAt(j) == ouptutToSkip) {
4848 continue;
4849 }
4850 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01004851 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004852 continue;
4853 }
4854 // If the default device for this strategy is on another output mix,
4855 // invalidate all tracks in this strategy to force re connection.
4856 // Otherwise select new device on the output mix.
4857 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
François Gaffiec005e562018-11-06 15:04:49 +01004858 for (auto stream : mEngine->getStreamTypesForProductStrategy(ps)) {
4859 mpClientInterface->invalidateStream(stream);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004860 }
4861 } else {
François Gaffie11d30102018-11-02 16:09:09 +01004862 setOutputDevices(
4863 outputDesc, getNewOutputDevices(outputDesc, false /*fromCache*/), false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004864 }
4865 }
4866}
4867
4868void AudioPolicyManager::clearSessionRoutes(uid_t uid)
4869{
4870 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01004871 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07004872 for (size_t i = 0; i < mOutputs.size(); i++) {
4873 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004874 for (const auto& client : outputDesc->getClientIterable()) {
4875 if (client->hasPreferredDevice() && client->uid() == uid) {
4876 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01004877 auto clientStrategy = client->strategy();
4878 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
4879 end(affectedStrategies)) {
4880 continue;
4881 }
4882 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004883 }
4884 }
4885 }
4886 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004887 for (const auto& strategy : affectedStrategies) {
4888 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004889 }
4890
4891 // remove input routes associated with this uid
4892 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07004893 for (size_t i = 0; i < mInputs.size(); i++) {
4894 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07004895 for (const auto& client : inputDesc->getClientIterable()) {
4896 if (client->hasPreferredDevice() && client->uid() == uid) {
4897 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
4898 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004899 }
4900 }
4901 }
4902 // reroute inputs if necessary
4903 SortedVector<audio_io_handle_t> inputsToClose;
4904 for (size_t i = 0; i < mInputs.size(); i++) {
4905 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08004906 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004907 inputsToClose.add(inputDesc->mIoHandle);
4908 }
4909 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004910 for (const auto& input : inputsToClose) {
4911 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004912 }
4913}
4914
Eric Laurentd60560a2015-04-10 11:31:20 -07004915void AudioPolicyManager::clearAudioSources(uid_t uid)
4916{
4917 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004918 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
4919 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07004920 stopAudioSource(mAudioSources.keyAt(i));
4921 }
4922 }
4923}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07004924
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004925status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
4926 audio_io_handle_t *ioHandle,
4927 audio_devices_t *device)
4928{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08004929 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
4930 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01004931 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
François Gaffiec005e562018-11-06 15:04:49 +01004932 *device = mEngine->getInputDeviceForAttributes(attr)->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004933
François Gaffiedf372692015-03-19 10:43:27 +01004934 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07004935}
4936
Eric Laurentd60560a2015-04-10 11:31:20 -07004937status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004938 const audio_attributes_t *attributes,
4939 audio_port_handle_t *portId,
4940 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07004941{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004942 ALOGV("%s", __FUNCTION__);
4943 *portId = AUDIO_PORT_HANDLE_NONE;
4944
4945 if (source == NULL || attributes == NULL || portId == NULL) {
4946 ALOGW("%s invalid argument: source %p attributes %p handle %p",
4947 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07004948 return BAD_VALUE;
4949 }
4950
Eric Laurentd60560a2015-04-10 11:31:20 -07004951 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
4952 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004953 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
4954 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004955 return INVALID_OPERATION;
4956 }
4957
François Gaffie11d30102018-11-02 16:09:09 +01004958 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07004959 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08004960 String8(source->ext.device.address),
4961 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01004962 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004963 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07004964 return BAD_VALUE;
4965 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004966
jiabin4ef93452019-09-10 14:29:54 -07004967 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07004968
François Gaffieaaac0fd2018-11-22 17:56:39 +01004969 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01004970 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01004971 mEngine->getStreamTypeForAttributes(*attributes),
4972 mEngine->getProductStrategyForAttributes(*attributes),
4973 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07004974
4975 status_t status = connectAudioSource(sourceDesc);
4976 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004977 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07004978 }
4979 return status;
4980}
4981
Francois Gaffie601801d2021-06-22 13:27:39 +02004982sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
4983 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
4984{
4985 ALOGV("%s", __FUNCTION__);
4986 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
4987
4988 status_t status = startAudioSource(source, attributes, &portId, uid);
4989 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
4990 return mAudioSources.valueFor(portId);
4991}
4992
4993
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004994status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07004995{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07004996 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07004997
4998 // make sure we only have one patch per source.
4999 disconnectAudioSource(sourceDesc);
5000
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005001 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005002 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5003 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5004 sourceDesc->srcDevice()->type(),
5005 String8(sourceDesc->srcDevice()->address().c_str()),
5006 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005007 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005008 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005009 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005010 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005011 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5012 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5013 return INVALID_OPERATION;
5014 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005015 PatchBuilder patchBuilder;
5016 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5017 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005018
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005019 return connectAudioSourceToSink(
5020 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005021}
5022
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005023status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005024{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005025 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5026 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005027 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005028 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005029 return BAD_VALUE;
5030 }
5031 status_t status = disconnectAudioSource(sourceDesc);
5032
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005033 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005034 return status;
5035}
5036
Andy Hung2ddee192015-12-18 17:34:44 -08005037status_t AudioPolicyManager::setMasterMono(bool mono)
5038{
5039 if (mMasterMono == mono) {
5040 return NO_ERROR;
5041 }
5042 mMasterMono = mono;
5043 // if enabling mono we close all offloaded devices, which will invalidate the
5044 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5045 // for recreating the new AudioTrack as non-offloaded PCM.
5046 //
5047 // If disabling mono, we leave all tracks as is: we don't know which clients
5048 // and tracks are able to be recreated as offloaded. The next "song" should
5049 // play back offloaded.
5050 if (mMasterMono) {
5051 Vector<audio_io_handle_t> offloaded;
5052 for (size_t i = 0; i < mOutputs.size(); ++i) {
5053 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5054 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5055 offloaded.push(desc->mIoHandle);
5056 }
5057 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005058 for (const auto& handle : offloaded) {
5059 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005060 }
5061 }
5062 // update master mono for all remaining outputs
5063 for (size_t i = 0; i < mOutputs.size(); ++i) {
5064 updateMono(mOutputs.keyAt(i));
5065 }
5066 return NO_ERROR;
5067}
5068
5069status_t AudioPolicyManager::getMasterMono(bool *mono)
5070{
5071 *mono = mMasterMono;
5072 return NO_ERROR;
5073}
5074
Eric Laurentac9cef52017-06-09 15:46:26 -07005075float AudioPolicyManager::getStreamVolumeDB(
5076 audio_stream_type_t stream, int index, audio_devices_t device)
5077{
jiabin9a3361e2019-10-01 09:38:30 -07005078 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005079}
5080
jiabin81772902018-04-02 17:52:27 -07005081status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5082 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005083 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005084{
Kriti Dang6537def2021-03-02 13:46:59 +01005085 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5086 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005087 return BAD_VALUE;
5088 }
Kriti Dang6537def2021-03-02 13:46:59 +01005089 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5090 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005091
5092 size_t formatsWritten = 0;
5093 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005094
Kriti Dang6537def2021-03-02 13:46:59 +01005095 *numSurroundFormats = mConfig.getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005096 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5097 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Kriti Dang6537def2021-03-02 13:46:59 +01005098 for (const auto& format: mConfig.getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005099 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005100 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005101 bool formatEnabled = true;
5102 switch (forceUse) {
5103 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005104 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005105 break;
5106 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5107 formatEnabled = false;
5108 break;
5109 default: // AUTO or ALWAYS => true
5110 break;
jiabin81772902018-04-02 17:52:27 -07005111 }
5112 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5113 }
jiabin81772902018-04-02 17:52:27 -07005114 }
5115 return NO_ERROR;
5116}
5117
Kriti Dang6537def2021-03-02 13:46:59 +01005118status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5119 audio_format_t *surroundFormats) {
5120 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5121 return BAD_VALUE;
5122 }
5123 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5124 __func__, *numSurroundFormats, surroundFormats);
5125
5126 size_t formatsWritten = 0;
5127 size_t formatsMax = *numSurroundFormats;
5128 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5129
5130 // Return formats from all device profiles that have already been resolved by
5131 // checkOutputsForDevice().
5132 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5133 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5134 audio_devices_t deviceType = device->type();
5135 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5136 // returns formats reported by HDMI devices.
5137 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5138 continue;
5139 }
5140 // Formats reported by sink devices
5141 std::unordered_set<audio_format_t> formatset;
5142 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5143 formatset.insert(it->second.begin(), it->second.end());
5144 }
5145
5146 // Formats hard-coded in the in policy configuration file (if any).
5147 FormatVector encodedFormats = device->encodedFormats();
5148 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5149 // Filter the formats which are supported by the vendor hardware.
5150 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
5151 if (mConfig.getSurroundFormats().count(*it) != 0) {
5152 formats.insert(*it);
5153 } else {
5154 for (const auto& pair : mConfig.getSurroundFormats()) {
5155 if (pair.second.count(*it) != 0) {
5156 formats.insert(pair.first);
5157 break;
5158 }
5159 }
5160 }
5161 }
5162 }
5163 *numSurroundFormats = formats.size();
5164 for (const auto& format: formats) {
5165 if (formatsWritten < formatsMax) {
5166 surroundFormats[formatsWritten++] = format;
5167 }
5168 }
5169 return NO_ERROR;
5170}
5171
jiabin81772902018-04-02 17:52:27 -07005172status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5173{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005174 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005175 const auto& formatIter = mConfig.getSurroundFormats().find(audioFormat);
5176 if (formatIter == mConfig.getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005177 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005178 return BAD_VALUE;
5179 }
5180
Mikhail Naganov100f0122018-11-29 11:22:16 -08005181 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5182 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005183 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005184 return INVALID_OPERATION;
5185 }
5186
Mikhail Naganov100f0122018-11-29 11:22:16 -08005187 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005188 return NO_ERROR;
5189 }
5190
Mikhail Naganov100f0122018-11-29 11:22:16 -08005191 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005192 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005193 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005194 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005195 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005196 }
5197 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005198 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005199 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005200 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005201 }
5202 }
5203
5204 sp<SwAudioOutputDescriptor> outputDesc;
5205 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005206 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5207 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005208 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5209 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005210 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005211 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005212 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5213 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5214 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005215 name.c_str(),
5216 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005217 if (status != NO_ERROR) {
5218 continue;
5219 }
5220 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5221 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5222 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005223 name.c_str(),
5224 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005225 profileUpdated |= (status == NO_ERROR);
5226 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005227 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005228 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005229 AUDIO_DEVICE_IN_HDMI);
5230 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5231 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005232 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005233 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005234 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5235 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5236 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005237 name.c_str(),
5238 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005239 if (status != NO_ERROR) {
5240 continue;
5241 }
5242 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5243 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5244 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005245 name.c_str(),
5246 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005247 profileUpdated |= (status == NO_ERROR);
5248 }
5249
jiabin81772902018-04-02 17:52:27 -07005250 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005251 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005252 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005253 }
5254
5255 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5256}
5257
Eric Laurent5ada82e2019-08-29 17:53:54 -07005258void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005259{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005260 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005261 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005262 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005263 }
5264}
5265
jiabin6012f912018-11-02 17:06:30 -07005266bool AudioPolicyManager::isHapticPlaybackSupported()
5267{
5268 for (const auto& hwModule : mHwModules) {
5269 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5270 for (const auto &outProfile : outputProfiles) {
5271 struct audio_port audioPort;
5272 outProfile->toAudioPort(&audioPort);
5273 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5274 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5275 return true;
5276 }
5277 }
5278 }
5279 }
5280 return false;
5281}
5282
Carter Hsu325a8eb2022-01-19 19:56:51 +08005283bool AudioPolicyManager::isUltrasoundSupported()
5284{
5285 bool hasUltrasoundOutput = false;
5286 bool hasUltrasoundInput = false;
5287 for (const auto& hwModule : mHwModules) {
5288 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5289 if (!hasUltrasoundOutput) {
5290 for (const auto &outProfile : outputProfiles) {
5291 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5292 hasUltrasoundOutput = true;
5293 break;
5294 }
5295 }
5296 }
5297
5298 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5299 if (!hasUltrasoundInput) {
5300 for (const auto &inputProfile : inputProfiles) {
5301 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5302 hasUltrasoundInput = true;
5303 break;
5304 }
5305 }
5306 }
5307
5308 if (hasUltrasoundOutput && hasUltrasoundInput)
5309 return true;
5310 }
5311 return false;
5312}
5313
Eric Laurent8340e672019-11-06 11:01:08 -08005314bool AudioPolicyManager::isCallScreenModeSupported()
5315{
5316 return getConfig().isCallScreenModeSupported();
5317}
5318
5319
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005320status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005321{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005322 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005323 if (!sourceDesc->isConnected()) {
5324 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5325 return NO_ERROR;
5326 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005327 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5328 if (swOutput != 0) {
5329 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005330 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005331 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005332 }
jiabinbce0c1d2020-10-05 11:20:18 -07005333 if (releaseOutput(sourceDesc->portId())) {
5334 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5335 // no need to release audio patch here but just return NO_ERROR.
5336 return NO_ERROR;
5337 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005338 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005339 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005340 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005341 // close Hwoutput and remove from mHwOutputs
5342 } else {
5343 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5344 }
5345 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005346 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005347 sourceDesc->disconnect();
5348 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005349}
5350
François Gaffiec005e562018-11-06 15:04:49 +01005351sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5352 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005353{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005354 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005355 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005356 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005357 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005358 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5359 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005360 source = sourceDesc;
5361 break;
5362 }
5363 }
5364 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005365}
5366
Eric Laurentb4f42a92022-01-17 17:37:31 +01005367bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005368 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005369 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005370{
5371 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5372 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005373 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005374 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005375 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5376 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5377 return false;
5378 }
5379 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5380 return false;
5381 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005382 }
5383
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005384 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005385 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005386 if (profile == nullptr) {
5387 return false;
5388 }
5389
5390 // The caller can have the audio config criteria ignored by either passing a null ptr or
5391 // the AUDIO_CONFIG_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005392 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurent39095982021-08-24 18:29:27 +02005393 // some positional channel masks.
Eric Laurent39095982021-08-24 18:29:27 +02005394
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005395 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005396 if (!audio_is_channel_mask_spatialized(config->channel_mask)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005397 return false;
5398 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005399 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005400 return true;
5401}
5402
5403void AudioPolicyManager::checkVirtualizerClientRoutes() {
5404 std::set<audio_stream_type_t> streamsToInvalidate;
5405 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02005406 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
5407 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005408 audio_attributes_t attr = client->attributes();
5409 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
5410 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5411 audio_config_base_t clientConfig = client->config();
5412 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02005413 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005414 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005415 streamsToInvalidate.insert(client->stream());
5416 }
5417 }
5418 }
5419
5420 for (audio_stream_type_t stream : streamsToInvalidate) {
5421 mpClientInterface->invalidateStream(stream);
5422 }
5423}
5424
Eric Laurente191d1b2022-04-15 11:59:25 +02005425
5426bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
5427 const sp<SwAudioOutputDescriptor>& outputDesc) {
5428 if (outputDesc->isDuplicated()) {
5429 return false;
5430 }
5431 DeviceVector devices = outputDesc->supportedDevices();
5432 for (size_t i = 0; i < mOutputs.size(); i++) {
5433 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5434 if (desc == outputDesc || desc->isDuplicated()) {
5435 continue;
5436 }
5437 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
5438 if (!sharedDevices.isEmpty()
5439 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
5440 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
5441 return false;
5442 }
5443 }
5444 return true;
5445}
5446
5447
Eric Laurentfa0f6742021-08-17 18:39:44 +02005448status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005449 const audio_attributes_t *attr,
5450 audio_io_handle_t *output) {
5451 *output = AUDIO_IO_HANDLE_NONE;
5452
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005453 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
5454 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
5455 audio_config_t *configPtr = nullptr;
5456 audio_config_t config;
5457 if (mixerConfig != nullptr) {
5458 config = audio_config_initializer(mixerConfig);
5459 configPtr = &config;
5460 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005461 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005462 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005463 return BAD_VALUE;
5464 }
5465
5466 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02005467 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005468 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02005469 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005470 return BAD_VALUE;
5471 }
5472
Eric Laurente191d1b2022-04-15 11:59:25 +02005473 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02005474 for (size_t i = 0; i < mOutputs.size(); i++) {
5475 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02005476 if (!desc->isDuplicated()
5477 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
5478 spatializerOutputs.push_back(desc);
5479 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02005480 }
5481 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005482 mSpatializerOutput.clear();
5483 bool outputsChanged = false;
5484 for (const auto& desc : spatializerOutputs) {
5485 if (desc->mProfile == profile
5486 && (configPtr == nullptr
5487 || configPtr->channel_mask == desc->mMixerChannelMask)) {
5488 mSpatializerOutput = desc;
5489 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
5490 } else {
5491 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
5492 " and devices %s", __func__, desc->mIoHandle,
5493 configPtr != nullptr ? configPtr->channel_mask : 0,
5494 devices.toString().c_str());
5495 closeOutput(desc->mIoHandle);
5496 outputsChanged = true;
5497 }
Eric Laurent39095982021-08-24 18:29:27 +02005498 }
5499
Eric Laurente191d1b2022-04-15 11:59:25 +02005500 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01005501 sp<SwAudioOutputDescriptor> desc =
5502 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02005503 if (desc != nullptr) {
5504 mSpatializerOutput = desc;
5505 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005506 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005507 }
5508
5509 checkVirtualizerClientRoutes();
5510
Eric Laurente191d1b2022-04-15 11:59:25 +02005511 if (outputsChanged) {
5512 mPreviousOutputs = mOutputs;
5513 mpClientInterface->onAudioPortListUpdate();
5514 }
5515
5516 if (mSpatializerOutput == nullptr) {
5517 ALOGV("%s could not open spatializer output with requested config", __func__);
5518 return BAD_VALUE;
5519 }
Eric Laurent39095982021-08-24 18:29:27 +02005520 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02005521 ALOGV("%s returning new spatializer output %d", __func__, *output);
5522 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005523}
5524
Eric Laurentfa0f6742021-08-17 18:39:44 +02005525status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
5526 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005527 return INVALID_OPERATION;
5528 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02005529 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005530 return BAD_VALUE;
5531 }
Eric Laurent39095982021-08-24 18:29:27 +02005532
Eric Laurente191d1b2022-04-15 11:59:25 +02005533 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
5534 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
5535 closeOutput(mSpatializerOutput->mIoHandle);
5536 //from now on mSpatializerOutput is null
5537 checkVirtualizerClientRoutes();
5538 }
Eric Laurent39095982021-08-24 18:29:27 +02005539
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005540 return NO_ERROR;
5541}
5542
Eric Laurente552edb2014-03-10 17:42:56 -07005543// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07005544// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07005545// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07005546uint32_t AudioPolicyManager::nextAudioPortGeneration()
5547{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08005548 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005549}
5550
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005551static status_t deserializeAudioPolicyXmlConfig(AudioPolicyConfig &config) {
Mikhail Naganov946c0032020-10-21 13:04:58 -07005552 if (std::string audioPolicyXmlConfigFile = audio_get_audio_policy_config_file();
5553 !audioPolicyXmlConfigFile.empty()) {
5554 status_t ret = deserializeAudioPolicyFile(audioPolicyXmlConfigFile.c_str(), &config);
5555 if (ret == NO_ERROR) {
5556 config.setSource(audioPolicyXmlConfigFile);
Cheney Ni6851adb2018-11-01 06:30:37 +08005557 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005558 return ret;
Petri Gyntherf497f292018-04-17 18:46:10 -07005559 }
Mikhail Naganov946c0032020-10-21 13:04:58 -07005560 return BAD_VALUE;
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005561}
Jaekyun Seok0d4a6af2017-02-17 17:10:17 +09005562
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005563AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface,
5564 bool /*forTesting*/)
Eric Laurente552edb2014-03-10 17:42:56 -07005565 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07005566 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005567 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07005568 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07005569 mA2dpSuspended(false),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005570 mConfig(mHwModulesAll, mOutputDevicesAll, mInputDevicesAll, mDefaultOutputDevice),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07005571 mAudioPortGeneration(1),
5572 mBeaconMuteRefCount(0),
5573 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07005574 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08005575 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07005576 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08005577 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07005578{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005579}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005580
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005581AudioPolicyManager::AudioPolicyManager(AudioPolicyClientInterface *clientInterface)
5582 : AudioPolicyManager(clientInterface, false /*forTesting*/)
5583{
5584 loadConfig();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005585}
François Gaffied1ab2bd2015-12-02 18:20:06 +01005586
Kevin Rocarddfa1e8a2018-10-26 16:42:07 -07005587void AudioPolicyManager::loadConfig() {
5588 if (deserializeAudioPolicyXmlConfig(getConfig()) != NO_ERROR) {
François Gaffied1ab2bd2015-12-02 18:20:06 +01005589 ALOGE("could not load audio policy configuration file, setting defaults");
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005590 getConfig().setDefault();
François Gaffied1ab2bd2015-12-02 18:20:06 +01005591 }
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005592}
5593
5594status_t AudioPolicyManager::initialize() {
Mikhail Naganov47835552019-05-14 10:32:51 -07005595 {
5596 auto engLib = EngineLibrary::load(
5597 "libaudiopolicyengine" + getConfig().getEngineLibraryNameSuffix() + ".so");
5598 if (!engLib) {
5599 ALOGE("%s: Failed to load the engine library", __FUNCTION__);
5600 return NO_INIT;
5601 }
5602 mEngine = engLib->createEngine();
5603 if (mEngine == nullptr) {
5604 ALOGE("%s: Failed to instantiate the APM engine", __FUNCTION__);
5605 return NO_INIT;
5606 }
François Gaffie2110e042015-03-24 08:41:51 +01005607 }
5608 mEngine->setObserver(this);
5609 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005610 if (status != NO_ERROR) {
5611 LOG_FATAL("Policy engine not initialized(err=%d)", status);
5612 return status;
5613 }
François Gaffie2110e042015-03-24 08:41:51 +01005614
Eric Laurent1a8b45f2022-04-13 16:01:47 +02005615 mEngine->updateDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01005616 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
5617 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
5618
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005619 // after parsing the config, mOutputDevicesAll and mInputDevicesAll contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07005620 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005621 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01005622
Eric Laurent3a4311c2014-03-17 12:00:47 -07005623 // make sure default device is reachable
François Gaffie11d30102018-11-02 16:09:09 +01005624 if (mDefaultOutputDevice == 0 || !mAvailableOutputDevices.contains(mDefaultOutputDevice)) {
5625 ALOGE_IF(mDefaultOutputDevice != 0, "Default device %s is unreachable",
5626 mDefaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005627 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07005628 }
jiabin9ff780e2018-03-19 18:19:52 -07005629 // If microphones address is empty, set it according to device type
Eric Laurent736a1022019-03-27 18:28:46 -07005630 for (size_t i = 0; i < mAvailableInputDevices.size(); i++) {
jiabince9f20e2019-09-12 16:29:15 -07005631 if (mAvailableInputDevices[i]->address().empty()) {
jiabin9ff780e2018-03-19 18:19:52 -07005632 if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BUILTIN_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005633 mAvailableInputDevices[i]->setAddress(AUDIO_BOTTOM_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005634 } else if (mAvailableInputDevices[i]->type() == AUDIO_DEVICE_IN_BACK_MIC) {
jiabince9f20e2019-09-12 16:29:15 -07005635 mAvailableInputDevices[i]->setAddress(AUDIO_BACK_MICROPHONE_ADDRESS);
jiabin9ff780e2018-03-19 18:19:52 -07005636 }
5637 }
5638 }
Eric Laurente552edb2014-03-10 17:42:56 -07005639
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005640 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07005641
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09005642 // Silence ALOGV statements
5643 property_set("log.tag." LOG_TAG, "D");
5644
Eric Laurente552edb2014-03-10 17:42:56 -07005645 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08005646 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07005647}
5648
Eric Laurente0720872014-03-11 09:30:41 -07005649AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07005650{
Eric Laurente552edb2014-03-10 17:42:56 -07005651 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005652 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005653 }
5654 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08005655 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07005656 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07005657 mAvailableOutputDevices.clear();
5658 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07005659 mOutputs.clear();
5660 mInputs.clear();
5661 mHwModules.clear();
Mikhail Naganovd4120142017-12-06 15:49:22 -08005662 mHwModulesAll.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005663 mManualSurroundFormats.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07005664}
5665
Eric Laurente0720872014-03-11 09:30:41 -07005666status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07005667{
Eric Laurent87ffa392015-05-22 10:32:38 -07005668 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07005669}
5670
Eric Laurente552edb2014-03-10 17:42:56 -07005671// ---
5672
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005673void AudioPolicyManager::onNewAudioModulesAvailable()
5674{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005675 DeviceVector newDevices;
5676 onNewAudioModulesAvailableInt(&newDevices);
5677 if (!newDevices.empty()) {
5678 nextAudioPortGeneration();
5679 mpClientInterface->onAudioPortListUpdate();
5680 }
5681}
5682
5683void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
5684{
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005685 for (const auto& hwModule : mHwModulesAll) {
5686 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
5687 continue;
5688 }
5689 hwModule->setHandle(mpClientInterface->loadHwModule(hwModule->getName()));
5690 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
5691 ALOGW("could not open HW module %s", hwModule->getName());
5692 continue;
5693 }
5694 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10005695 // open all output streams needed to access attached devices.
5696 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005697 // This also validates mAvailableOutputDevices list
5698 for (const auto& outProfile : hwModule->getOutputProfiles()) {
5699 if (!outProfile->canOpenNewIo()) {
5700 ALOGE("Invalid Output profile max open count %u for profile %s",
5701 outProfile->maxOpenCount, outProfile->getTagName().c_str());
5702 continue;
5703 }
5704 if (!outProfile->hasSupportedDevices()) {
5705 ALOGW("Output profile contains no device on module %s", hwModule->getName());
5706 continue;
5707 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08005708 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
5709 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005710 mTtsOutputAvailable = true;
5711 }
5712
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005713 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
5714 DeviceVector availProfileDevices = supportedDevices.filter(mOutputDevicesAll);
5715 sp<DeviceDescriptor> supportedDevice = 0;
5716 if (supportedDevices.contains(mDefaultOutputDevice)) {
5717 supportedDevice = mDefaultOutputDevice;
5718 } else {
5719 // choose first device present in profile's SupportedDevices also part of
5720 // mAvailableOutputDevices.
5721 if (availProfileDevices.isEmpty()) {
5722 continue;
5723 }
5724 supportedDevice = availProfileDevices.itemAt(0);
5725 }
5726 if (!mOutputDevicesAll.contains(supportedDevice)) {
5727 continue;
5728 }
5729 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
5730 mpClientInterface);
5731 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02005732 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
5733 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005734 AUDIO_STREAM_DEFAULT,
5735 AUDIO_OUTPUT_FLAG_NONE, &output);
5736 if (status != NO_ERROR) {
5737 ALOGW("Cannot open output stream for devices %s on hw module %s",
5738 supportedDevice->toString().c_str(), hwModule->getName());
5739 continue;
5740 }
5741 for (const auto &device : availProfileDevices) {
5742 // give a valid ID to an attached device once confirmed it is reachable
5743 if (!device->isAttached()) {
5744 device->attach(hwModule);
5745 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07005746 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005747 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005748 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5749 }
5750 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005751 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005752 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
5753 mPrimaryOutput = outputDesc;
5754 }
Eric Laurent39095982021-08-24 18:29:27 +02005755 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07005756 outputDesc->close();
5757 } else {
5758 addOutput(output, outputDesc);
5759 setOutputDevices(outputDesc,
5760 DeviceVector(supportedDevice),
5761 true,
5762 0,
5763 NULL);
5764 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005765 }
5766 // open input streams needed to access attached devices to validate
5767 // mAvailableInputDevices list
5768 for (const auto& inProfile : hwModule->getInputProfiles()) {
5769 if (!inProfile->canOpenNewIo()) {
5770 ALOGE("Invalid Input profile max open count %u for profile %s",
5771 inProfile->maxOpenCount, inProfile->getTagName().c_str());
5772 continue;
5773 }
5774 if (!inProfile->hasSupportedDevices()) {
5775 ALOGW("Input profile contains no device on module %s", hwModule->getName());
5776 continue;
5777 }
5778 // chose first device present in profile's SupportedDevices also part of
5779 // available input devices
5780 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
5781 DeviceVector availProfileDevices = supportedDevices.filter(mInputDevicesAll);
5782 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01005783 ALOGV("%s: Input device list is empty! for profile %s",
5784 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005785 continue;
5786 }
5787 sp<AudioInputDescriptor> inputDesc =
5788 new AudioInputDescriptor(inProfile, mpClientInterface);
5789
5790 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
5791 status_t status = inputDesc->open(nullptr,
5792 availProfileDevices.itemAt(0),
5793 AUDIO_SOURCE_MIC,
5794 AUDIO_INPUT_FLAG_NONE,
5795 &input);
5796 if (status != NO_ERROR) {
5797 ALOGW("Cannot open input stream for device %s on hw module %s",
5798 availProfileDevices.toString().c_str(),
5799 hwModule->getName());
5800 continue;
5801 }
5802 for (const auto &device : availProfileDevices) {
5803 // give a valid ID to an attached device once confirmed it is reachable
5804 if (!device->isAttached()) {
5805 device->attach(hwModule);
5806 device->importAudioPortAndPickAudioProfile(inProfile, true);
5807 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07005808 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005809 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
5810 }
5811 }
5812 inputDesc->close();
5813 }
5814 }
Eric Laurente191d1b2022-04-15 11:59:25 +02005815
5816 // Check if spatializer outputs can be closed until used.
5817 // mOutputs vector never contains duplicated outputs at this point.
5818 std::vector<audio_io_handle_t> outputsClosed;
5819 for (size_t i = 0; i < mOutputs.size(); i++) {
5820 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5821 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
5822 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
5823 outputsClosed.push_back(desc->mIoHandle);
5824 desc->close();
5825 }
5826 }
5827 for (auto output : outputsClosed) {
5828 removeOutput(output);
5829 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00005830}
5831
Eric Laurent98e38192018-02-15 18:31:53 -08005832void AudioPolicyManager::addOutput(audio_io_handle_t output,
5833 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07005834{
Eric Laurent1c333e22014-05-20 10:48:17 -07005835 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07005836 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08005837 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07005838 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07005839 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07005840}
5841
François Gaffie53615e22015-03-19 09:24:12 +01005842void AudioPolicyManager::removeOutput(audio_io_handle_t output)
5843{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02005844 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
5845 ALOGV("%s: removing primary output", __func__);
5846 mPrimaryOutput = nullptr;
5847 }
François Gaffie53615e22015-03-19 09:24:12 +01005848 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07005849 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01005850}
5851
Eric Laurent98e38192018-02-15 18:31:53 -08005852void AudioPolicyManager::addInput(audio_io_handle_t input,
5853 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07005854{
Eric Laurent1c333e22014-05-20 10:48:17 -07005855 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07005856 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07005857}
Eric Laurente552edb2014-03-10 17:42:56 -07005858
François Gaffie11d30102018-11-02 16:09:09 +01005859status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01005860 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01005861 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07005862{
François Gaffie11d30102018-11-02 16:09:09 +01005863 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07005864 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07005865 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07005866
François Gaffie11d30102018-11-02 16:09:09 +01005867 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07005868 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01005869 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07005870 }
Eric Laurente552edb2014-03-10 17:42:56 -07005871
Eric Laurent3b73df72014-03-11 09:06:29 -07005872 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07005873 // first call getAudioPort to get the supported attributes from the HAL
5874 struct audio_port_v7 port = {};
5875 device->toAudioPort(&port);
5876 status_t status = mpClientInterface->getAudioPort(&port);
5877 if (status == NO_ERROR) {
5878 device->importAudioPort(port);
5879 }
5880
5881 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07005882 for (size_t i = 0; i < mOutputs.size(); i++) {
5883 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005884 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07005885 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01005886 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
5887 mOutputs.keyAt(i), device->toString().c_str());
5888 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07005889 }
5890 }
5891 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07005892 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005893 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005894 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5895 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01005896 if (profile->supportsDevice(device)) {
5897 profiles.add(profile);
5898 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
5899 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07005900 }
5901 }
5902 }
5903
Eric Laurent7b279bb2015-12-14 10:18:23 -08005904 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005905
Eric Laurente552edb2014-03-10 17:42:56 -07005906 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005907 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005908 return BAD_VALUE;
5909 }
5910
5911 // open outputs for matching profiles if needed. Direct outputs are also opened to
5912 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
5913 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07005914 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07005915
5916 // nothing to do if one output is already opened for this profile
5917 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005918 for (j = 0; j < outputs.size(); j++) {
5919 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07005920 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005921 // matching profile: save the sample rates, format and channel masks supported
5922 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01005923 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07005924 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005925 }
Eric Laurente552edb2014-03-10 17:42:56 -07005926 break;
5927 }
5928 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005929 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07005930 continue;
5931 }
5932
Eric Laurent3974e3b2017-12-07 17:58:43 -08005933 if (!profile->canOpenNewIo()) {
5934 ALOGW("Max Output number %u already opened for this profile %s",
5935 profile->maxOpenCount, profile->getTagName().c_str());
5936 continue;
5937 }
5938
Eric Laurent83efe1c2017-07-09 16:51:08 -07005939 ALOGV("opening output for device %08x with params %s profile %p name %s",
jiabin5740f082019-08-19 15:08:30 -07005940 deviceType, address.string(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07005941 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
5942 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07005943 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01005944 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005945 profiles.removeAt(profile_index);
5946 profile_index--;
5947 } else {
5948 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07005949 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01005950 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07005951 // TODO: when getAudioPort is ready, it may not be needed to import the audio
5952 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07005953 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07005954 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07005955
François Gaffie11d30102018-11-02 16:09:09 +01005956 if (device_distinguishes_on_address(deviceType)) {
5957 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
5958 device->toString().c_str());
5959 setOutputDevices(desc, DeviceVector(device), true/*force*/, 0/*delay*/,
5960 NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005961 }
Eric Laurente552edb2014-03-10 17:42:56 -07005962 ALOGV("checkOutputsForDevice(): adding output %d", output);
5963 }
5964 }
5965
5966 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01005967 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07005968 return BAD_VALUE;
5969 }
Eric Laurentd4692962014-05-05 18:13:44 -07005970 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07005971 // check if one opened output is not needed any more after disconnecting one device
5972 for (size_t i = 0; i < mOutputs.size(); i++) {
5973 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005974 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08005975 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005976 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01005977 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01005978 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01005979 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005980 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
5981 mOutputs.keyAt(i));
5982 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07005983 }
Eric Laurente552edb2014-03-10 17:42:56 -07005984 }
5985 }
Eric Laurentd4692962014-05-05 18:13:44 -07005986 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08005987 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08005988 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
5989 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07005990 if (!profile->supportsDevice(device)) {
5991 continue;
5992 }
5993 ALOGV("checkOutputsForDevice(): "
5994 "clearing direct output profile %zu on module %s",
5995 j, hwModule->getName());
5996 profile->clearAudioProfiles();
5997 if (!profile->hasDynamicAudioProfile()) {
5998 continue;
5999 }
6000 // When a device is disconnected, if there is an IOProfile that contains dynamic
6001 // profiles and supports the disconnected device, call getAudioPort to repopulate
6002 // the capabilities of the devices that is supported by the IOProfile.
6003 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6004 if (supportedDevice == device ||
6005 !mAvailableOutputDevices.contains(supportedDevice)) {
6006 continue;
6007 }
6008 struct audio_port_v7 port;
6009 supportedDevice->toAudioPort(&port);
6010 status_t status = mpClientInterface->getAudioPort(&port);
6011 if (status == NO_ERROR) {
6012 supportedDevice->importAudioPort(port);
6013 }
Eric Laurente552edb2014-03-10 17:42:56 -07006014 }
6015 }
6016 }
6017 }
6018 return NO_ERROR;
6019}
6020
François Gaffie11d30102018-11-02 16:09:09 +01006021status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006022 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006023{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006024 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006025
François Gaffie11d30102018-11-02 16:09:09 +01006026 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006027 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006028 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006029 }
6030
Eric Laurentd4692962014-05-05 18:13:44 -07006031 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Eric Laurent0dd51852019-04-19 18:18:58 -07006032 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006033 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006034 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006035 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006036 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006037 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006038 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006039
François Gaffie11d30102018-11-02 16:09:09 +01006040 if (profile->supportsDevice(device)) {
6041 profiles.add(profile);
6042 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6043 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006044 }
6045 }
6046 }
6047
Eric Laurent0dd51852019-04-19 18:18:58 -07006048 if (profiles.isEmpty()) {
6049 ALOGW("%s: No input profile available for device %s",
6050 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006051 return BAD_VALUE;
6052 }
6053
6054 // open inputs for matching profiles if needed. Direct inputs are also opened to
6055 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6056 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6057
Eric Laurent1c333e22014-05-20 10:48:17 -07006058 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006059
Eric Laurentd4692962014-05-05 18:13:44 -07006060 // nothing to do if one input is already opened for this profile
6061 size_t input_index;
6062 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6063 desc = mInputs.valueAt(input_index);
6064 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006065 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006066 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006067 }
Eric Laurentd4692962014-05-05 18:13:44 -07006068 break;
6069 }
6070 }
6071 if (input_index != mInputs.size()) {
6072 continue;
6073 }
6074
Eric Laurent3974e3b2017-12-07 17:58:43 -08006075 if (!profile->canOpenNewIo()) {
6076 ALOGW("Max Input number %u already opened for this profile %s",
6077 profile->maxOpenCount, profile->getTagName().c_str());
6078 continue;
6079 }
6080
Eric Laurentfe231122017-11-17 17:48:06 -08006081 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006082 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Eric Laurentfe231122017-11-17 17:48:06 -08006083 status_t status = desc->open(nullptr,
6084 device,
Eric Laurentfe231122017-11-17 17:48:06 -08006085 AUDIO_SOURCE_MIC,
6086 AUDIO_INPUT_FLAG_NONE,
6087 &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006088
Eric Laurentcf2c0212014-07-25 16:20:43 -07006089 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006090 const String8& address = String8(device->address().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006091 if (!address.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006092 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006093 mpClientInterface->setParameters(input, String8(param));
6094 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006095 }
François Gaffie11d30102018-11-02 16:09:09 +01006096 updateAudioProfiles(device, input, profile->getAudioProfiles());
François Gaffie112b0af2015-11-19 16:13:25 +01006097 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006098 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006099 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006100 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006101 }
6102
Eric Laurent0dd51852019-04-19 18:18:58 -07006103 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006104 addInput(input, desc);
6105 }
6106 } // endif input != 0
6107
Eric Laurentcf2c0212014-07-25 16:20:43 -07006108 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006109 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006110 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006111 profiles.removeAt(profile_index);
6112 profile_index--;
6113 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006114 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006115 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006116 }
Eric Laurentd4692962014-05-05 18:13:44 -07006117 ALOGV("checkInputsForDevice(): adding input %d", input);
6118 }
6119 } // end scan profiles
6120
6121 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006122 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006123 return BAD_VALUE;
6124 }
6125 } else {
6126 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006127 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006128 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006129 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006130 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006131 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006132 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006133 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006134 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6135 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006136 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006137 }
6138 }
6139 }
6140 } // end disconnect
6141
6142 return NO_ERROR;
6143}
6144
6145
Eric Laurente0720872014-03-11 09:30:41 -07006146void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006147{
6148 ALOGV("closeOutput(%d)", output);
6149
François Gaffie1c878552018-11-22 16:53:21 +01006150 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6151 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006152 ALOGW("closeOutput() unknown output %d", output);
6153 return;
6154 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006155 const bool closingOutputWasActive = closingOutput->isActive();
François Gaffie1c878552018-11-22 16:53:21 +01006156 mPolicyMixes.closeOutput(closingOutput);
Eric Laurent275e8e92014-11-30 15:14:47 -08006157
Eric Laurente552edb2014-03-10 17:42:56 -07006158 // look for duplicated outputs connected to the output being removed.
6159 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006160 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6161 if (dupOutput->isDuplicated() &&
6162 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6163 sp<SwAudioOutputDescriptor> remainingOutput =
6164 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006165 // As all active tracks on duplicated output will be deleted,
6166 // and as they were also referenced on the other output, the reference
6167 // count for their stream type must be adjusted accordingly on
6168 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006169 const bool wasActive = remainingOutput->isActive();
6170 // Note: no-op on the closing output where all clients has already been set inactive
6171 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006172 // stop() will be a no op if the output is still active but is needed in case all
6173 // active streams refcounts where cleared above
6174 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006175 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006176 }
Eric Laurente552edb2014-03-10 17:42:56 -07006177 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6178 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6179
6180 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006181 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006182 }
6183 }
6184
Eric Laurent05b90f82014-08-27 15:32:29 -07006185 nextAudioPortGeneration();
6186
François Gaffie1c878552018-11-22 16:53:21 +01006187 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006188 if (index >= 0) {
6189 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006190 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6191 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006192 mAudioPatches.removeItemsAt(index);
6193 mpClientInterface->onAudioPatchListUpdate();
6194 }
6195
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006196 if (closingOutputWasActive) {
6197 closingOutput->stop();
6198 }
François Gaffie1c878552018-11-22 16:53:21 +01006199 closingOutput->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006200
François Gaffie53615e22015-03-19 09:24:12 +01006201 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006202 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006203 if (closingOutput == mSpatializerOutput) {
6204 mSpatializerOutput.clear();
6205 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006206
6207 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6208 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006209 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006210 bool directOutputOpen = false;
6211 for (size_t i = 0; i < mOutputs.size(); i++) {
6212 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6213 directOutputOpen = true;
6214 break;
6215 }
6216 }
6217 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006218 ALOGV("no direct outputs open, reset MSD patches");
6219 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6220 // how output devices for patching are resolved. Avoid by caching and reusing the
6221 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6222 // devices to patch to. This may be complicated by the fact that devices may become
6223 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006224 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006225 }
6226 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006227}
6228
6229void AudioPolicyManager::closeInput(audio_io_handle_t input)
6230{
6231 ALOGV("closeInput(%d)", input);
6232
6233 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6234 if (inputDesc == NULL) {
6235 ALOGW("closeInput() unknown input %d", input);
6236 return;
6237 }
6238
Eric Laurent6a94d692014-05-20 11:18:06 -07006239 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006240
François Gaffie11d30102018-11-02 16:09:09 +01006241 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006242 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006243 if (index >= 0) {
6244 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006245 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6246 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006247 mAudioPatches.removeItemsAt(index);
6248 mpClientInterface->onAudioPatchListUpdate();
6249 }
6250
Eric Laurentfe231122017-11-17 17:48:06 -08006251 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006252 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006253
François Gaffie11d30102018-11-02 16:09:09 +01006254 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6255 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006256 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006257 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006258 }
Eric Laurente552edb2014-03-10 17:42:56 -07006259}
6260
François Gaffie11d30102018-11-02 16:09:09 +01006261SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6262 const DeviceVector &devices,
6263 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006264{
6265 SortedVector<audio_io_handle_t> outputs;
6266
François Gaffie11d30102018-11-02 16:09:09 +01006267 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006268 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006269 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006270 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006271 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006272 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006273 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006274 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006275 outputs.add(openOutputs.keyAt(i));
6276 }
6277 }
6278 return outputs;
6279}
6280
Mikhail Naganov37977152018-07-11 15:54:44 -07006281void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6282{
6283 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6284 // output is suspended before any tracks are moved to it
6285 checkA2dpSuspend();
6286 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006287 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006288 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006289 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006290 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006291 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6292 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6293 // configuration changes will ultimately be rerouted correctly. We can still avoid
6294 // unnecessary rerouting by caching and reusing the arguments to
6295 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6296 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006297 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006298 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006299 // an event that changed routing likely occurred, inform upper layers
6300 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006301}
6302
François Gaffiec005e562018-11-06 15:04:49 +01006303bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6304 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006305{
François Gaffiec005e562018-11-06 15:04:49 +01006306 return mEngine->getProductStrategyForAttributes(lAttr) ==
6307 mEngine->getProductStrategyForAttributes(rAttr);
6308}
6309
Francois Gaffieff1eb522020-05-06 18:37:04 +02006310void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6311{
6312 for (size_t i = 0; i < mAudioSources.size(); i++) {
6313 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6314 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006315 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006316 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006317 connectAudioSource(sourceDesc);
6318 }
6319 }
6320}
6321
6322void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6323{
6324 for (size_t i = 0; i < mAudioSources.size(); i++) {
6325 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6326 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6327 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6328 disconnectAudioSource(sourceDesc);
6329 }
6330 }
6331}
6332
François Gaffiec005e562018-11-06 15:04:49 +01006333void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6334{
6335 auto psId = mEngine->getProductStrategyForAttributes(attr);
6336
6337 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6338 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006339
François Gaffie11d30102018-11-02 16:09:09 +01006340 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6341 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006342
Eric Laurentc209fe42020-06-05 18:11:23 -07006343 uint32_t maxLatency = 0;
6344 bool invalidate = false;
6345 // take into account dynamic audio policies related changes: if a client is now associated
6346 // to a different policy mix than at creation time, invalidate corresponding stream
6347 for (size_t i = 0; i < mPreviousOutputs.size() && !invalidate; i++) {
6348 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6349 if (desc->isDuplicated()) {
6350 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006351 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006352 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6353 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6354 continue;
6355 }
6356 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006357 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6358 client->uid(), client->flags(), primaryMix, nullptr);
Eric Laurentc209fe42020-06-05 18:11:23 -07006359 if (status != OK) {
6360 continue;
6361 }
yucliuf4de36d2020-09-14 14:57:56 -07006362 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006363 invalidate = true;
6364 if (desc->isStrategyActive(psId)) {
6365 maxLatency = desc->latency();
6366 }
6367 break;
6368 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006369 }
6370 }
6371
Eric Laurentc209fe42020-06-05 18:11:23 -07006372 if (srcOutputs != dstOutputs || invalidate) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006373 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6374 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006375 for (audio_io_handle_t srcOut : srcOutputs) {
6376 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006377 if (desc == nullptr) continue;
6378
6379 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006380 maxLatency = desc->latency();
6381 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006382
6383 if (invalidate) continue;
6384
6385 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006386 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006387 // a client on a non direct outputs has necessarily a linear PCM format
6388 // so we can call selectOutput() safely
6389 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6390 client->flags(),
6391 client->config().format,
6392 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006393 client->config().sample_rate,
6394 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006395 if (newOutput != srcOut) {
6396 invalidate = true;
6397 break;
6398 }
6399 } else {
6400 sp<IOProfile> profile = getProfileForOutput(newDevices,
6401 client->config().sample_rate,
6402 client->config().format,
6403 client->config().channel_mask,
6404 client->flags(),
6405 true /* directOnly */);
6406 if (profile != desc->mProfile) {
6407 invalidate = true;
6408 break;
6409 }
6410 }
6411 }
Eric Laurentac3a6902018-05-11 16:39:10 -07006412 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006413
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006414 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
François Gaffiec005e562018-11-06 15:04:49 +01006415 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006416 std::to_string(srcOutputs[0]).c_str(),
6417 std::to_string(dstOutputs[0]).c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006418 // mute strategy while moving tracks from one output to another
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006419 for (audio_io_handle_t srcOut : srcOutputs) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006420 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006421 if (desc == nullptr) continue;
6422
6423 if (desc->isStrategyActive(psId)) {
François Gaffiec005e562018-11-06 15:04:49 +01006424 setStrategyMute(psId, true, desc);
6425 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
François Gaffie11d30102018-11-02 16:09:09 +01006426 newDevices.types());
Eric Laurente552edb2014-03-10 17:42:56 -07006427 }
François Gaffiec005e562018-11-06 15:04:49 +01006428 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006429 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006430 connectAudioSource(source);
6431 }
Eric Laurente552edb2014-03-10 17:42:56 -07006432 }
6433
François Gaffiec005e562018-11-06 15:04:49 +01006434 // Move effects associated to this stream from previous output to new output
6435 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07006436 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07006437 }
François Gaffiec005e562018-11-06 15:04:49 +01006438 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurentaa02db82019-09-05 17:31:49 -07006439 if (invalidate) {
6440 for (auto stream : mEngine->getStreamTypesForProductStrategy(psId)) {
6441 mpClientInterface->invalidateStream(stream);
6442 }
jiabin49256852022-03-09 11:21:35 -08006443 for (audio_io_handle_t srcOut : srcOutputs) {
6444 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
6445 if (desc == nullptr) continue;
6446
6447 desc->setTracksInvalidatedStatusByStrategy(psId);
6448 }
Eric Laurente552edb2014-03-10 17:42:56 -07006449 }
6450 }
6451}
6452
Eric Laurente0720872014-03-11 09:30:41 -07006453void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07006454{
François Gaffiec005e562018-11-06 15:04:49 +01006455 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
6456 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
6457 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02006458 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01006459 }
Eric Laurente552edb2014-03-10 17:42:56 -07006460}
6461
Kevin Rocard153f92d2018-12-18 18:33:28 -08006462void AudioPolicyManager::checkSecondaryOutputs() {
6463 std::set<audio_stream_type_t> streamsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00006464 TrackSecondaryOutputsMap trackSecondaryOutputs;
Kevin Rocard153f92d2018-12-18 18:33:28 -08006465 for (size_t i = 0; i < mOutputs.size(); i++) {
6466 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
6467 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006468 sp<AudioPolicyMix> primaryMix;
6469 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006470 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
6471 client->uid(), client->flags(), primaryMix, &secondaryMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07006472 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
6473 for (auto &secondaryMix : secondaryMixes) {
6474 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
6475 if (outputDesc != nullptr &&
6476 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
6477 secondaryDescs.push_back(outputDesc);
6478 }
6479 }
6480
jiabin10a03f12021-05-07 23:46:28 +00006481 if (status != OK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08006482 streamsToInvalidate.insert(client->stream());
jiabin10a03f12021-05-07 23:46:28 +00006483 } else if (!std::equal(
6484 client->getSecondaryOutputs().begin(),
6485 client->getSecondaryOutputs().end(),
6486 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00006487 if (!audio_is_linear_pcm(client->config().format)) {
6488 // If the format is not PCM, the tracks should be invalidated to get correct
6489 // behavior when the secondary output is changed.
6490 streamsToInvalidate.insert(client->stream());
6491 } else {
6492 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
6493 std::vector<audio_io_handle_t> secondaryOutputIds;
6494 for (const auto &secondaryDesc: secondaryDescs) {
6495 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
6496 weakSecondaryDescs.push_back(secondaryDesc);
6497 }
6498 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
6499 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00006500 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006501 }
6502 }
6503 }
jiabin10a03f12021-05-07 23:46:28 +00006504 if (!trackSecondaryOutputs.empty()) {
6505 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
6506 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08006507 for (audio_stream_type_t stream : streamsToInvalidate) {
jiabin10a03f12021-05-07 23:46:28 +00006508 ALOGD("%s Invalidate stream %d due to fail getting output for attr", __func__, stream);
Kevin Rocard153f92d2018-12-18 18:33:28 -08006509 mpClientInterface->invalidateStream(stream);
6510 }
6511}
6512
Eric Laurent2517af32020-11-25 15:31:27 +01006513bool AudioPolicyManager::isScoRequestedForComm() const {
6514 AudioDeviceTypeAddrVector devices;
6515 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
6516 for (const auto &device : devices) {
6517 if (audio_is_bluetooth_out_sco_device(device.mType)) {
6518 return true;
6519 }
6520 }
6521 return false;
6522}
6523
Eric Laurent1a8b45f2022-04-13 16:01:47 +02006524bool AudioPolicyManager::isHearingAidUsedForComm() const {
6525 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
6526 true /*fromCache*/);
6527 for (const auto &device : devices) {
6528 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
6529 return true;
6530 }
6531 }
6532 return false;
6533}
6534
6535
Eric Laurente0720872014-03-11 09:30:41 -07006536void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07006537{
François Gaffie53615e22015-03-19 09:24:12 +01006538 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08006539 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07006540 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07006541 return;
6542 }
6543
Eric Laurent3a4311c2014-03-17 12:00:47 -07006544 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07006545 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
6546 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01006547 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07006548
6549 // if suspended, restore A2DP output if:
6550 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01006551 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07006552 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006553 //
Eric Laurentf732e072016-08-03 19:30:28 -07006554 // if not suspended, suspend A2DP output if:
6555 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01006556 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07006557 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07006558 //
6559 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07006560 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01006561 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07006562 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01006563 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006564
6565 mpClientInterface->restoreOutput(a2dpOutput);
6566 mA2dpSuspended = false;
6567 }
6568 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07006569 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01006570 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07006571 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01006572 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07006573
6574 mpClientInterface->suspendOutput(a2dpOutput);
6575 mA2dpSuspended = true;
6576 }
6577 }
6578}
6579
François Gaffie11d30102018-11-02 16:09:09 +01006580DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6581 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07006582{
François Gaffie11d30102018-11-02 16:09:09 +01006583 DeviceVector devices;
6584
Jean-Michel Triviff155c62016-02-26 12:07:16 -08006585 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006586 if (index >= 0) {
6587 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006588 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006589 ALOGV("%s device %s forced by patch %d", __func__,
6590 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
6591 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07006592 }
6593 }
6594
Dean Wheatley514b4312020-06-17 21:45:00 +10006595 // Do not retrieve engine device for outputs through MSD
6596 // TODO: support explicit routing requests by resetting MSD patch to engine device.
6597 if (outputDesc->devices() == getMsdAudioOutDevices()) {
6598 return outputDesc->devices();
6599 }
6600
Eric Laurent97ac8712018-07-27 18:59:02 -07006601 // Honor explicit routing requests only if no client using default routing is active on this
6602 // input: a specific app can not force routing for other apps by setting a preferred device.
6603 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01006604 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01006605 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01006606 if (device != nullptr) {
6607 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07006608 }
6609
François Gaffiea807ef92018-11-05 10:44:33 +01006610 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
6611 // of setForceUse / Default Bus device here
6612 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
6613 if (device != nullptr) {
6614 return DeviceVector(device);
6615 }
6616
François Gaffiec005e562018-11-06 15:04:49 +01006617 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
6618 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
6619 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306620 auto hasStreamActive = [&](auto stream) {
6621 return hasStream(streams, stream) && isStreamActive(stream, 0);
6622 };
Eric Laurent484e9272018-06-07 17:29:23 -07006623
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306624 auto doGetOutputDevicesForVoice = [&]() {
6625 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006626 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306627 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02006628 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
6629 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306630 };
6631
6632 // With low-latency playing on speaker, music on WFD, when the first low-latency
6633 // output is stopped, getNewOutputDevices checks for a product strategy
6634 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00006635 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05306636 // devices are returned for STRATEGY_SONIFICATION without checking whether the
6637 // stream is associated to the output descriptor.
6638 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
6639 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
6640 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
6641 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01006642 // Retrieval of devices for voice DL is done on primary output profile, cannot
6643 // check the route (would force modifying configuration file for this profile)
6644 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
6645 break;
6646 }
Eric Laurente552edb2014-03-10 17:42:56 -07006647 }
François Gaffiec005e562018-11-06 15:04:49 +01006648 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01006649 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07006650}
6651
François Gaffie11d30102018-11-02 16:09:09 +01006652sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
6653 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07006654{
François Gaffie11d30102018-11-02 16:09:09 +01006655 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07006656
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006657 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07006658 if (index >= 0) {
6659 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006660 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01006661 ALOGV("getNewInputDevice() device %s forced by patch %d",
6662 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
6663 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07006664 }
6665 }
6666
Eric Laurent97ac8712018-07-27 18:59:02 -07006667 // Honor explicit routing requests only if no client using default routing is active on this
6668 // input: a specific app can not force routing for other apps by setting a preferred device.
6669 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01006670 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
6671 if (device != nullptr) {
6672 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07006673 }
6674
Eric Laurentdc95a252018-04-12 12:46:56 -07006675 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08006676 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08006677 audio_attributes_t attributes;
6678 uid_t uid;
6679 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
6680 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006681 attributes = topClient->attributes();
6682 uid = topClient->uid();
yuanjiahsu0735bf32021-03-18 08:12:54 +08006683 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01006684 attributes = { .source = AUDIO_SOURCE_DEFAULT };
6685 uid = 0;
yuanjiahsu0735bf32021-03-18 08:12:54 +08006686 }
6687
Francois Gaffie716e1432019-01-14 16:58:59 +01006688 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
6689 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07006690 }
Francois Gaffie716e1432019-01-14 16:58:59 +01006691 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
yuanjiahsu0735bf32021-03-18 08:12:54 +08006692 device = mEngine->getInputDeviceForAttributes(attributes, uid);
Eric Laurentfb66dd92016-01-28 18:32:03 -08006693 }
Eric Laurent1c333e22014-05-20 10:48:17 -07006694
Eric Laurente552edb2014-03-10 17:42:56 -07006695 return device;
6696}
6697
Eric Laurent794fde22016-03-11 09:50:45 -08006698bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
6699 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08006700 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08006701}
6702
Dorin Drimusf2196d82022-01-03 12:11:18 +01006703// TODO - consider MSD routes b/214971780
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006704status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08006705 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006706 if (devices == nullptr) {
6707 return BAD_VALUE;
6708 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006709
6710 // Devices are determined in the following precedence:
6711 //
6712 // 1) Devices associated with a dynamic policy matching the attributes. This is often
6713 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
6714 //
6715 // If no such dynamic policy then
6716 // 2) Devices containing an active client using setPreferredDevice
6717 // with same strategy as the attributes.
6718 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6719 //
6720 // If no corresponding active client with setPreferredDevice then
6721 // 3) Devices associated with the strategy determined by the attributes
6722 // (from the default Engine::getOutputDevicesForAttributes() implementation).
6723 //
6724 // See related getOutputForAttrInt().
6725
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006726 // check dynamic policies but only for primary descriptors (secondary not used for audible
6727 // audio routing, only used for duplication for playback capture)
Eric Laurentc529cf62020-04-17 18:19:10 -07006728 sp<AudioPolicyMix> policyMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006729 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
6730 0 /*uid unknown here*/, AUDIO_OUTPUT_FLAG_NONE, policyMix, nullptr);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006731 if (status != OK) {
6732 return status;
6733 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006734
6735 DeviceVector curDevices;
6736 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
6737 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
6738 // as they are unaffected by device/stream volume
6739 // (per SwAudioOutputDescriptor::isFixedVolume()).
6740 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
6741 ) {
6742 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
6743 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
6744 curDevices.add(deviceDesc);
6745 } else {
6746 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
6747 // which selects setPreferredDevice if active. This means forVolume call
6748 // will take an active setPreferredDevice, if such exists.
6749
6750 curDevices = mEngine->getOutputDevicesForAttributes(
6751 attr, nullptr /* preferredDevice */, false /* fromCache */);
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006752 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08006753
6754 if (forVolume) {
6755 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
6756 // for single volume control in AudioService (such relationship should exist if
6757 // SPEAKER_SAFE is present).
6758 //
6759 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
6760 DeviceVector speakerSafeDevices =
6761 curDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
6762 if (!speakerSafeDevices.isEmpty()) {
6763 curDevices.merge(
6764 mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
6765 curDevices.remove(speakerSafeDevices);
6766 }
6767 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08006768 for (const auto& device : curDevices) {
6769 devices->push_back(device->getDeviceTypeAddr());
6770 }
6771 return NO_ERROR;
6772}
6773
Eric Laurente0720872014-03-11 09:30:41 -07006774void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07006775 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07006776 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01006777 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07006778 updateDevicesAndOutputs();
6779 break;
6780 default:
6781 break;
6782 }
6783}
6784
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006785uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07006786
6787 // skip beacon mute management if a dedicated TTS output is available
6788 if (mTtsOutputAvailable) {
6789 return 0;
6790 }
6791
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006792 switch(event) {
6793 case STARTING_OUTPUT:
6794 mBeaconMuteRefCount++;
6795 break;
6796 case STOPPING_OUTPUT:
6797 if (mBeaconMuteRefCount > 0) {
6798 mBeaconMuteRefCount--;
6799 }
6800 break;
6801 case STARTING_BEACON:
6802 mBeaconPlayingRefCount++;
6803 break;
6804 case STOPPING_BEACON:
6805 if (mBeaconPlayingRefCount > 0) {
6806 mBeaconPlayingRefCount--;
6807 }
6808 break;
6809 }
6810
6811 if (mBeaconMuteRefCount > 0) {
6812 // any playback causes beacon to be muted
6813 return setBeaconMute(true);
6814 } else {
6815 // no other playback: unmute when beacon starts playing, mute when it stops
6816 return setBeaconMute(mBeaconPlayingRefCount == 0);
6817 }
6818}
6819
6820uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
6821 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
6822 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
6823 // keep track of muted state to avoid repeating mute/unmute operations
6824 if (mBeaconMuted != mute) {
6825 // mute/unmute AUDIO_STREAM_TTS on all outputs
6826 ALOGV("\t muting %d", mute);
6827 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01006828 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
6829 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
6830 ALOGV("\t no tts volume source available");
6831 return 0;
6832 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006833 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07006834 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07006835 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006836 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07006837 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006838 maxLatency = latency;
6839 }
6840 }
6841 mBeaconMuted = mute;
6842 return maxLatency;
6843 }
6844 return 0;
6845}
6846
Eric Laurente0720872014-03-11 09:30:41 -07006847void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07006848{
François Gaffiec005e562018-11-06 15:04:49 +01006849 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07006850 mPreviousOutputs = mOutputs;
6851}
6852
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07006853uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01006854 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07006855 uint32_t delayMs)
6856{
6857 // mute/unmute strategies using an incompatible device combination
6858 // if muting, wait for the audio in pcm buffer to be drained before proceeding
6859 // if unmuting, unmute only after the specified delay
6860 if (outputDesc->isDuplicated()) {
6861 return 0;
6862 }
6863
6864 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01006865 DeviceVector devices = outputDesc->devices();
6866 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07006867
François Gaffiec005e562018-11-06 15:04:49 +01006868 auto productStrategies = mEngine->getOrderedProductStrategies();
6869 for (const auto &productStrategy : productStrategies) {
6870 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
6871 DeviceVector curDevices =
6872 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
6873 curDevices = curDevices.filter(outputDesc->supportedDevices());
6874 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006875 bool doMute = false;
6876
François Gaffiec005e562018-11-06 15:04:49 +01006877 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006878 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006879 outputDesc->setStrategyMutedByDevice(productStrategy, true);
6880 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07006881 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01006882 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07006883 }
Eric Laurent99401132014-05-07 19:48:15 -07006884 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07006885 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07006886 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07006887 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01006888 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07006889 continue;
6890 }
François Gaffiec005e562018-11-06 15:04:49 +01006891 ALOGVV("%s() %s (curDevice %s)", __func__,
6892 mute ? "muting" : "unmuting", curDevices.toString().c_str());
6893 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
6894 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07006895 if (mute) {
6896 // FIXME: should not need to double latency if volume could be applied
6897 // immediately by the audioflinger mixer. We must account for the delay
6898 // between now and the next time the audioflinger thread for this output
6899 // will process a buffer (which corresponds to one buffer size,
6900 // usually 1/2 or 1/4 of the latency).
6901 if (muteWaitMs < desc->latency() * 2) {
6902 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07006903 }
6904 }
6905 }
6906 }
6907 }
6908 }
6909
Eric Laurent99401132014-05-07 19:48:15 -07006910 // temporary mute output if device selection changes to avoid volume bursts due to
6911 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01006912 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07006913 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006914
Eric Laurentdc462862016-07-19 12:29:53 -07006915 if (muteWaitMs < tempMuteWaitMs) {
6916 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07006917 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08006918
6919 // If recommended duration is defined, replace temporary mute duration to avoid
6920 // truncated notifications at beginning, which depends on duration of changing path in HAL.
6921 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
6922 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
6923 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
6924 tempRecommendedMuteDuration : outputDesc->latency() * 4;
6925
François Gaffieaaac0fd2018-11-22 17:56:39 +01006926 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
6927 // make sure that we do not start the temporary mute period too early in case of
6928 // delayed device change
6929 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
6930 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01006931 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07006932 }
6933 }
6934
Eric Laurente552edb2014-03-10 17:42:56 -07006935 // wait for the PCM output buffers to empty before proceeding with the rest of the command
6936 if (muteWaitMs > delayMs) {
6937 muteWaitMs -= delayMs;
6938 usleep(muteWaitMs * 1000);
6939 return muteWaitMs;
6940 }
6941 return 0;
6942}
6943
François Gaffie11d30102018-11-02 16:09:09 +01006944uint32_t AudioPolicyManager::setOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
6945 const DeviceVector &devices,
6946 bool force,
6947 int delayMs,
6948 audio_patch_handle_t *patchHandle,
Francois Gaffie3523ab32021-06-22 13:24:34 +02006949 bool requiresMuteCheck, bool requiresVolumeCheck)
Eric Laurente552edb2014-03-10 17:42:56 -07006950{
François Gaffie11d30102018-11-02 16:09:09 +01006951 ALOGV("%s device %s delayMs %d", __func__, devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07006952 uint32_t muteWaitMs;
6953
6954 if (outputDesc->isDuplicated()) {
François Gaffie11d30102018-11-02 16:09:09 +01006955 muteWaitMs = setOutputDevices(outputDesc->subOutput1(), devices, force, delayMs,
6956 nullptr /* patchHandle */, requiresMuteCheck);
6957 muteWaitMs += setOutputDevices(outputDesc->subOutput2(), devices, force, delayMs,
6958 nullptr /* patchHandle */, requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07006959 return muteWaitMs;
6960 }
Eric Laurente552edb2014-03-10 17:42:56 -07006961
6962 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01006963 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01006964 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02006965 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006966
François Gaffie11d30102018-11-02 16:09:09 +01006967 ALOGV("setOutputDevices() prevDevice %s", prevDevices.toString().c_str());
6968
6969 if (!filteredDevices.isEmpty()) {
6970 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07006971 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006972
6973 // if the outputs are not materially active, there is no need to mute.
6974 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01006975 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00006976 } else {
6977 ALOGV("%s: suppressing checkDeviceMuteStrategies", __func__);
6978 muteWaitMs = 0;
6979 }
Eric Laurente552edb2014-03-10 17:42:56 -07006980
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006981 bool outputRouted = outputDesc->isRouted();
6982
Eric Laurent79ea9582020-06-11 18:49:24 -07006983 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
6984 // output profile or if new device is not supported AND previous device(s) is(are) still
6985 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02006986 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Eric Laurent79ea9582020-06-11 18:49:24 -07006987 ALOGV("%s: unsupported device %s for output", __func__, devices.toString().c_str());
6988 // restore previous device after evaluating strategy mute state
6989 outputDesc->setDevices(prevDevices);
6990 return muteWaitMs;
6991 }
6992
Eric Laurente552edb2014-03-10 17:42:56 -07006993 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07006994 // the requested device is AUDIO_DEVICE_NONE
6995 // OR the requested device is the same as current device
6996 // AND force is not specified
6997 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01006998 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006999 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
François Gaffie11d30102018-11-02 16:09:09 +01007000 ALOGV("%s setting same device %s or null device, force=%d, patch handle=%d", __func__,
7001 filteredDevices.toString().c_str(), force, outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007002 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
7003 ALOGV("%s setting same device on routed output, force apply volumes", __func__);
7004 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7005 }
Eric Laurente552edb2014-03-10 17:42:56 -07007006 return muteWaitMs;
7007 }
7008
François Gaffie11d30102018-11-02 16:09:09 +01007009 ALOGV("%s changing device to %s", __func__, filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007010
Eric Laurente552edb2014-03-10 17:42:56 -07007011 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007012 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007013 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007014 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007015 PatchBuilder patchBuilder;
7016 patchBuilder.addSource(outputDesc);
7017 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7018 for (const auto &filteredDevice : filteredDevices) {
7019 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007020 }
7021
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007022 // Add half reported latency to delayMs when muteWaitMs is null in order
7023 // to avoid disordered sequence of muting volume and changing devices.
7024 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(),
7025 muteWaitMs == 0 ? (delayMs + (outputDesc->latency() / 2)) : delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007026 }
Eric Laurente552edb2014-03-10 17:42:56 -07007027
7028 // update stream volumes according to new device
François Gaffie11d30102018-11-02 16:09:09 +01007029 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007030
7031 return muteWaitMs;
7032}
7033
Eric Laurentc75307b2015-03-17 15:29:32 -07007034status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007035 int delayMs,
7036 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007037{
Eric Laurent6a94d692014-05-20 11:18:06 -07007038 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007039 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7040 return INVALID_OPERATION;
7041 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007042 if (patchHandle) {
7043 index = mAudioPatches.indexOfKey(*patchHandle);
7044 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007045 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007046 }
7047 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007048 return INVALID_OPERATION;
7049 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007050 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007051 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007052 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007053 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007054 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007055 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007056 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007057 return status;
7058}
7059
7060status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007061 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007062 bool force,
7063 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007064{
7065 status_t status = NO_ERROR;
7066
Eric Laurent1f2f2232014-06-02 12:01:23 -07007067 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007068 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7069 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007070
François Gaffie11d30102018-11-02 16:09:09 +01007071 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007072 PatchBuilder patchBuilder;
7073 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007074 // AUDIO_SOURCE_HOTWORD is for internal use only:
7075 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007076 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7077 auto result = usecase;
7078 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7079 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7080 }
7081 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007082 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007083 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007084 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007085 }
7086 }
7087 return status;
7088}
7089
Eric Laurent6a94d692014-05-20 11:18:06 -07007090status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7091 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007092{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007093 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007094 ssize_t index;
7095 if (patchHandle) {
7096 index = mAudioPatches.indexOfKey(*patchHandle);
7097 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007098 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007099 }
7100 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007101 return INVALID_OPERATION;
7102 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007103 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007104 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007105 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007106 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007107 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007108 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007109 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007110 return status;
7111}
7112
François Gaffie11d30102018-11-02 16:09:09 +01007113sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007114 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007115 audio_format_t& format,
7116 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007117 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007118{
7119 // Choose an input profile based on the requested capture parameters: select the first available
7120 // profile supporting all requested parameters.
Andy Hungf129b032015-04-07 13:45:50 -07007121 //
7122 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7123 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007124
Glenn Kasten730b9262018-03-29 15:01:26 -07007125 sp<IOProfile> firstInexact;
7126 uint32_t updatedSamplingRate = 0;
7127 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7128 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007129 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007130 for (const auto& profile : hwModule->getInputProfiles()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007131 // profile->log();
Glenn Kasten730b9262018-03-29 15:01:26 -07007132 //updatedFormat = format;
François Gaffie11d30102018-11-02 16:09:09 +01007133 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
Glenn Kasten730b9262018-03-29 15:01:26 -07007134 &samplingRate /*updatedSamplingRate*/,
Andy Hungf129b032015-04-07 13:45:50 -07007135 format,
Glenn Kasten730b9262018-03-29 15:01:26 -07007136 &format, /*updatedFormat*/
Andy Hungf129b032015-04-07 13:45:50 -07007137 channelMask,
Glenn Kasten730b9262018-03-29 15:01:26 -07007138 &channelMask /*updatedChannelMask*/,
7139 // FIXME ugly cast
7140 (audio_output_flags_t) flags,
7141 true /*exactMatchRequiredForInputFlags*/)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007142 return profile;
7143 }
François Gaffie11d30102018-11-02 16:09:09 +01007144 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
Glenn Kasten730b9262018-03-29 15:01:26 -07007145 samplingRate,
7146 &updatedSamplingRate,
7147 format,
7148 &updatedFormat,
7149 channelMask,
7150 &updatedChannelMask,
7151 // FIXME ugly cast
7152 (audio_output_flags_t) flags,
7153 false /*exactMatchRequiredForInputFlags*/)) {
7154 firstInexact = profile;
7155 }
7156
Eric Laurente552edb2014-03-10 17:42:56 -07007157 }
7158 }
Glenn Kasten730b9262018-03-29 15:01:26 -07007159 if (firstInexact != nullptr) {
7160 samplingRate = updatedSamplingRate;
7161 format = updatedFormat;
7162 channelMask = updatedChannelMask;
7163 return firstInexact;
7164 }
Eric Laurente552edb2014-03-10 17:42:56 -07007165 return NULL;
7166}
7167
François Gaffieaaac0fd2018-11-22 17:56:39 +01007168float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7169 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007170 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007171 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007172{
jiabin9a3361e2019-10-01 09:38:30 -07007173 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007174
7175 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7176 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7177 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7178 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007179 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7180 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7181 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7182 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7183 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007184
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007185 if (volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007186 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7187 mOutputs.isActive(ringVolumeSrc, 0)) {
7188 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007189 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007190 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007191 }
7192
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007193 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007194 if ((volumeSource != callVolumeSrc && (isInCall() ||
7195 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007196 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007197 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7198 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007199 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7200 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7201 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007202 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007203 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007204 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007205 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007206 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007207 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007208 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7209 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7210 // programmatically muted.
7211 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7212 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7213 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007214 bool exemptFromCapping =
7215 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7216 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007217 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7218 volumeSource, volumeDb);
7219 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007220 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7221 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7222 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007223 }
7224 }
Eric Laurente552edb2014-03-10 17:42:56 -07007225 // if a headset is connected, apply the following rules to ring tones and notifications
7226 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007227 // - always attenuate notifications volume by 6dB
7228 // - attenuate ring tones volume by 6dB unless music is not playing and
7229 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007230 // - if music is playing, always limit the volume to current music volume,
7231 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007232 if (!Intersection(deviceTypes,
7233 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7234 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007235 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7236 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007237 ((volumeSource == alarmVolumeSrc ||
7238 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007239 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7240 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7241 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007242 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7243 curves.canBeMuted()) {
7244
Eric Laurente552edb2014-03-10 17:42:56 -07007245 // when the phone is ringing we must consider that music could have been paused just before
7246 // by the music application and behave as if music was active if the last music track was
7247 // just stopped
Eric Laurent3b73df72014-03-11 09:06:29 -07007248 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY) ||
Eric Laurente552edb2014-03-10 17:42:56 -07007249 mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01007250 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007251 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007252 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7253 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007254 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007255 float musicVolDb = computeVolume(musicCurves,
7256 musicVolumeSrc,
7257 musicCurves.getVolumeIndex(musicDevice),
7258 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007259 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7260 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7261 if (volumeDb > minVolDb) {
7262 volumeDb = minVolDb;
7263 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007264 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007265 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7266 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7267 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007268 // on A2DP, also ensure notification volume is not too low compared to media when
7269 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007270 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007271 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007272 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7273 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007274 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7275 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007276 }
7277 }
jiabin9a3361e2019-10-01 09:38:30 -07007278 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007279 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007280 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007281 }
7282 }
7283
François Gaffie43c73442018-11-08 08:21:55 +01007284 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007285}
7286
Eric Laurent3839bc02018-07-10 18:33:34 -07007287int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007288 VolumeSource fromVolumeSource,
7289 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007290{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007291 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007292 return srcIndex;
7293 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007294 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7295 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007296 float minSrc = (float)srcCurves.getVolumeIndexMin();
7297 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7298 float minDst = (float)dstCurves.getVolumeIndexMin();
7299 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007300
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007301 // preserve mute request or correct range
7302 if (srcIndex < minSrc) {
7303 if (srcIndex == 0) {
7304 return 0;
7305 }
7306 srcIndex = minSrc;
7307 } else if (srcIndex > maxSrc) {
7308 srcIndex = maxSrc;
7309 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007310 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7311}
7312
François Gaffieaaac0fd2018-11-22 17:56:39 +01007313status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7314 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007315 int index,
7316 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007317 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007318 int delayMs,
7319 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007320{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007321 // do not change actual attributes volume if the attributes is muted
7322 if (outputDesc->isMuted(volumeSource)) {
7323 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7324 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007325 return NO_ERROR;
7326 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007327 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7328 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7329 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7330 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007331
Eric Laurent2517af32020-11-25 15:31:27 +01007332 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007333 bool isHAUsed = isHearingAidUsedForComm();
7334
Eric Laurente552edb2014-03-10 17:42:56 -07007335 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007336 // if sco and call follow same curves, bypass forceUseForComm
7337 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007338 ((isVoiceVolSrc && isScoRequested) ||
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007339 (isBtScoVolSrc && !(isScoRequested || isHAUsed)))) {
Eric Laurent2517af32020-11-25 15:31:27 +01007340 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007341 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007342 // Do not return an error here as AudioService will always set both voice call
7343 // and bluetooth SCO volumes due to stream aliasing.
7344 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007345 }
jiabin9a3361e2019-10-01 09:38:30 -07007346 if (deviceTypes.empty()) {
7347 deviceTypes = outputDesc->devices().types();
Eric Laurentc75307b2015-03-17 15:29:32 -07007348 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007349
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007350 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7351 ALOGE("invalid volume index range");
7352 return BAD_VALUE;
7353 }
7354
jiabin9a3361e2019-10-01 09:38:30 -07007355 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7356 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007357 // Force VoIP volume to max for bluetooth SCO device except if muted
7358 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007359 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007360 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007361 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007362 const bool muted = (index == 0) && (volumeDb != 0.0f);
jiabin9a3361e2019-10-01 09:38:30 -07007363 outputDesc->setVolume(
Francois Gaffie593634d2021-06-22 13:31:31 +02007364 volumeDb, muted, volumeSource, curves.getStreamTypes(), deviceTypes, delayMs, force);
Eric Laurentc75307b2015-03-17 15:29:32 -07007365
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007366 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007367 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007368 // 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 +01007369 if (isVoiceVolSrc) {
7370 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007371 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007372 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007373 }
Eric Laurent18fba842016-03-31 14:41:26 -07007374 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007375 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7376 mLastVoiceVolume = voiceVolume;
7377 }
7378 }
Eric Laurente552edb2014-03-10 17:42:56 -07007379 return NO_ERROR;
7380}
7381
Eric Laurentc75307b2015-03-17 15:29:32 -07007382void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007383 const DeviceTypeSet& deviceTypes,
7384 int delayMs,
7385 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007386{
jiabincd510522020-01-22 09:40:55 -08007387 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007388 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7389 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7390 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007391 curves.getVolumeIndex(deviceTypes),
7392 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007393 }
7394}
7395
François Gaffiec005e562018-11-06 15:04:49 +01007396void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7397 bool on,
7398 const sp<AudioOutputDescriptor>& outputDesc,
7399 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007400 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007401{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007402 std::vector<VolumeSource> sourcesToMute;
7403 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7404 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7405 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007406 VolumeSource source = toVolumeSource(attributes, false);
7407 if ((source != VOLUME_SOURCE_NONE) &&
7408 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7409 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007410 sourcesToMute.push_back(source);
7411 }
Eric Laurente552edb2014-03-10 17:42:56 -07007412 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007413 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007414 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007415 }
7416
Eric Laurente552edb2014-03-10 17:42:56 -07007417}
7418
François Gaffieaaac0fd2018-11-22 17:56:39 +01007419void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
7420 bool on,
7421 const sp<AudioOutputDescriptor>& outputDesc,
7422 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007423 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007424{
jiabin9a3361e2019-10-01 09:38:30 -07007425 if (deviceTypes.empty()) {
7426 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07007427 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007428 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007429 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007430 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007431 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007432 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007433 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
7434 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07007435 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007436 }
7437 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007438 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
7439 // ignored
7440 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07007441 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007442 if (!outputDesc->isMuted(volumeSource)) {
7443 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07007444 return;
7445 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007446 if (outputDesc->decMuteCount(volumeSource) == 0) {
7447 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07007448 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07007449 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007450 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07007451 delayMs);
7452 }
7453 }
7454}
7455
François Gaffie53615e22015-03-19 09:24:12 +01007456bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
7457{
François Gaffiec005e562018-11-06 15:04:49 +01007458 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08007459 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
7460 return true;
7461 }
7462
7463 // has known usage?
7464 switch (paa->usage) {
7465 case AUDIO_USAGE_UNKNOWN:
7466 case AUDIO_USAGE_MEDIA:
7467 case AUDIO_USAGE_VOICE_COMMUNICATION:
7468 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
7469 case AUDIO_USAGE_ALARM:
7470 case AUDIO_USAGE_NOTIFICATION:
7471 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
7472 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
7473 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
7474 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
7475 case AUDIO_USAGE_NOTIFICATION_EVENT:
7476 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
7477 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
7478 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
7479 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08007480 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08007481 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08007482 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08007483 case AUDIO_USAGE_EMERGENCY:
7484 case AUDIO_USAGE_SAFETY:
7485 case AUDIO_USAGE_VEHICLE_STATUS:
7486 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08007487 break;
7488 default:
7489 return false;
7490 }
7491 return true;
7492}
7493
François Gaffie2110e042015-03-24 08:41:51 +01007494audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
7495{
7496 return mEngine->getForceUse(usage);
7497}
7498
Eric Laurent96d1dda2022-03-14 17:14:19 +01007499bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01007500 return isStateInCall(mEngine->getPhoneState());
7501}
7502
Eric Laurent96d1dda2022-03-14 17:14:19 +01007503bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01007504 return is_state_in_call(state);
7505}
7506
Eric Laurent74b71512019-11-06 17:21:57 -08007507bool AudioPolicyManager::isCallAudioAccessible()
7508{
7509 audio_mode_t mode = mEngine->getPhoneState();
7510 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007511 || (mode == AUDIO_MODE_CALL_SCREEN)
7512 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08007513}
7514
Eric Laurentd60560a2015-04-10 11:31:20 -07007515void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
7516{
7517 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07007518 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007519 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007520 sourceDesc->sinkDevice()->equals(deviceDesc))
7521 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007522 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007523 }
7524 }
7525
7526 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
7527 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
7528 bool release = false;
7529 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
7530 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
7531 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
7532 source->ext.device.type == deviceDesc->type()) {
7533 release = true;
7534 }
7535 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007536 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07007537 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
7538 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
7539 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02007540 sink->ext.device.type == deviceDesc->type() &&
7541 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
7542 || strncmp(sink->ext.device.address, address,
7543 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007544 release = true;
7545 }
7546 }
7547 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007548 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
7549 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07007550 }
7551 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007552
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007553 mInputs.clearSessionRoutesForDevice(deviceDesc);
7554
Francois Gaffie716e1432019-01-14 16:58:59 +01007555 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07007556}
7557
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007558void AudioPolicyManager::modifySurroundFormats(
7559 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007560 std::unordered_set<audio_format_t> enforcedSurround(
7561 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007562 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
7563 for (const auto& pair : mConfig.getSurroundFormats()) {
7564 allSurround.insert(pair.first);
7565 for (const auto& subformat : pair.second) allSurround.insert(subformat);
7566 }
Phil Burk09bc4612016-02-24 15:58:15 -08007567
7568 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7569 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07007570 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08007571 // This is the resulting set of formats depending on the surround mode:
7572 // 'all surround' = allSurround
7573 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
7574 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
7575 // 'manual surround' = mManualSurroundFormats
7576 // AUTO: formats v 'enforced surround'
7577 // ALWAYS: formats v 'all surround' v 'enforced surround'
7578 // NEVER: formats ^ 'non-surround'
7579 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08007580
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007581 std::unordered_set<audio_format_t> formatSet;
7582 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
7583 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007584 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007585 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007586 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007587 formatSet.insert(*formatIter);
7588 }
7589 }
7590 } else {
7591 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
7592 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007593 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007594
jiabin81772902018-04-02 17:52:27 -07007595 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08007596 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007597 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
7598 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
7599 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08007600 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007601 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
7602 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
7603 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07007604 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08007605 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08007606 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007607 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07007608 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007609 }
Phil Burk0709b0a2016-03-31 12:54:57 -07007610}
7611
jiabin06e4bab2019-07-29 10:13:34 -07007612void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
7613 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07007614 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
7615 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
7616
7617 // If NEVER, then remove support for channelMasks > stereo.
7618 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07007619 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
7620 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007621 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01007622 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07007623 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07007624 } else {
jiabin06e4bab2019-07-29 10:13:34 -07007625 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07007626 }
7627 }
jiabin81772902018-04-02 17:52:27 -07007628 // If ALWAYS or MANUAL, then make sure we at least support 5.1
7629 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
7630 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007631 bool supports5dot1 = false;
7632 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007633 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07007634 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
7635 supports5dot1 = true;
7636 break;
7637 }
7638 }
7639 // If not then add 5.1 support.
7640 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07007641 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01007642 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07007643 }
Phil Burk09bc4612016-02-24 15:58:15 -08007644 }
7645}
7646
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007647void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07007648 audio_io_handle_t ioHandle,
François Gaffie112b0af2015-11-19 16:13:25 +01007649 AudioProfileVector &profiles)
7650{
7651 String8 reply;
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007652 audio_devices_t device = devDesc->type();
Phil Burk0709b0a2016-03-31 12:54:57 -07007653
François Gaffie112b0af2015-11-19 16:13:25 +01007654 // Format MUST be checked first to update the list of AudioProfile
7655 if (profiles.hasDynamicFormat()) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007656 reply = mpClientInterface->getParameters(
7657 ioHandle, String8(AudioParameter::keyStreamSupportedFormats));
jiabin81772902018-04-02 17:52:27 -07007658 ALOGV("%s: supported formats %d, %s", __FUNCTION__, ioHandle, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007659 AudioParameter repliedParameters(reply);
7660 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007661 String8(AudioParameter::keyStreamSupportedFormats), reply) != NO_ERROR) {
François Gaffie112b0af2015-11-19 16:13:25 +01007662 ALOGE("%s: failed to retrieve format, bailing out", __FUNCTION__);
7663 return;
7664 }
Phil Burk09bc4612016-02-24 15:58:15 -08007665 FormatVector formats = formatsFromString(reply.string());
Kriti Dangef6be8f2020-11-05 11:58:19 +01007666 mReportedFormatsMap[devDesc] = formats;
Mikhail Naganov100f0122018-11-29 11:22:16 -08007667 if (device == AUDIO_DEVICE_OUT_HDMI
7668 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007669 modifySurroundFormats(devDesc, &formats);
Phil Burk00eeb322016-03-31 12:41:00 -07007670 }
jiabin3e277cc2019-09-10 14:27:34 -07007671 addProfilesForFormats(profiles, formats);
François Gaffie112b0af2015-11-19 16:13:25 +01007672 }
François Gaffie112b0af2015-11-19 16:13:25 +01007673
Mikhail Naganovcf84e592017-12-07 11:25:11 -08007674 for (audio_format_t format : profiles.getSupportedFormats()) {
jiabin06e4bab2019-07-29 10:13:34 -07007675 ChannelMaskSet channelMasks;
7676 SampleRateSet samplingRates;
François Gaffie112b0af2015-11-19 16:13:25 +01007677 AudioParameter requestedParameters;
Mikhail Naganov388360c2016-10-17 17:09:41 -07007678 requestedParameters.addInt(String8(AudioParameter::keyFormat), format);
François Gaffie112b0af2015-11-19 16:13:25 +01007679
7680 if (profiles.hasDynamicRateFor(format)) {
Mikhail Naganov388360c2016-10-17 17:09:41 -07007681 reply = mpClientInterface->getParameters(
7682 ioHandle,
7683 requestedParameters.toString() + ";" +
7684 AudioParameter::keyStreamSupportedSamplingRates);
François Gaffie112b0af2015-11-19 16:13:25 +01007685 ALOGV("%s: supported sampling rates %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007686 AudioParameter repliedParameters(reply);
7687 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007688 String8(AudioParameter::keyStreamSupportedSamplingRates), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007689 samplingRates = samplingRatesFromString(reply.string());
François Gaffie112b0af2015-11-19 16:13:25 +01007690 }
7691 }
7692 if (profiles.hasDynamicChannelsFor(format)) {
7693 reply = mpClientInterface->getParameters(ioHandle,
7694 requestedParameters.toString() + ";" +
Mikhail Naganov388360c2016-10-17 17:09:41 -07007695 AudioParameter::keyStreamSupportedChannels);
François Gaffie112b0af2015-11-19 16:13:25 +01007696 ALOGV("%s: supported channel masks %s", __FUNCTION__, reply.string());
Eric Laurent62e4bc52016-02-02 18:37:28 -08007697 AudioParameter repliedParameters(reply);
7698 if (repliedParameters.get(
Mikhail Naganov388360c2016-10-17 17:09:41 -07007699 String8(AudioParameter::keyStreamSupportedChannels), reply) == NO_ERROR) {
Eric Laurent62e4bc52016-02-02 18:37:28 -08007700 channelMasks = channelMasksFromString(reply.string());
Mikhail Naganov100f0122018-11-29 11:22:16 -08007701 if (device == AUDIO_DEVICE_OUT_HDMI
7702 || isDeviceOfModule(devDesc, AUDIO_HARDWARE_MODULE_ID_MSD)) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08007703 modifySurroundChannelMasks(&channelMasks);
Phil Burk0709b0a2016-03-31 12:54:57 -07007704 }
François Gaffie112b0af2015-11-19 16:13:25 +01007705 }
7706 }
jiabin3e277cc2019-09-10 14:27:34 -07007707 addDynamicAudioProfileAndSort(
7708 profiles, new AudioProfile(format, channelMasks, samplingRates));
François Gaffie112b0af2015-11-19 16:13:25 +01007709 }
7710}
Eric Laurentd60560a2015-04-10 11:31:20 -07007711
Mikhail Naganovdc769682018-05-04 15:34:08 -07007712status_t AudioPolicyManager::installPatch(const char *caller,
7713 audio_patch_handle_t *patchHandle,
7714 AudioIODescriptorInterface *ioDescriptor,
7715 const struct audio_patch *patch,
7716 int delayMs)
7717{
7718 ssize_t index = mAudioPatches.indexOfKey(
7719 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
7720 *patchHandle : ioDescriptor->getPatchHandle());
7721 sp<AudioPatch> patchDesc;
7722 status_t status = installPatch(
7723 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
7724 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007725 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07007726 }
7727 return status;
7728}
7729
7730status_t AudioPolicyManager::installPatch(const char *caller,
7731 ssize_t index,
7732 audio_patch_handle_t *patchHandle,
7733 const struct audio_patch *patch,
7734 int delayMs,
7735 uid_t uid,
7736 sp<AudioPatch> *patchDescPtr)
7737{
7738 sp<AudioPatch> patchDesc;
7739 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
7740 if (index >= 0) {
7741 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007742 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007743 }
7744
7745 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
7746 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
7747 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
7748 if (status == NO_ERROR) {
7749 if (index < 0) {
7750 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01007751 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007752 } else {
7753 patchDesc->mPatch = *patch;
7754 }
François Gaffieafd4cea2019-11-18 15:50:22 +01007755 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007756 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01007757 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07007758 }
7759 nextAudioPortGeneration();
7760 mpClientInterface->onAudioPatchListUpdate();
7761 }
7762 if (patchDescPtr) *patchDescPtr = patchDesc;
7763 return status;
7764}
7765
jiabinbce0c1d2020-10-05 11:20:18 -07007766bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
7767{
7768 const TrackClientVector activeClients = output->getActiveClients();
7769 if (activeClients.empty()) {
7770 return true;
7771 }
7772 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
7773 if (index < 0) {
7774 ALOGE("%s, no audio patch found while there are active clients on output %d",
7775 __func__, output->getId());
7776 return false;
7777 }
7778 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
7779 DeviceVector routedDevices;
7780 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
7781 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
7782 patchDesc->mPatch.sinks[i].id);
7783 if (device == nullptr) {
7784 ALOGE("%s, no audio device found with id(%d)",
7785 __func__, patchDesc->mPatch.sinks[i].id);
7786 return false;
7787 }
7788 routedDevices.add(device);
7789 }
7790 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08007791 if (client->isInvalid()) {
7792 // No need to take care about invalidated clients.
7793 continue;
7794 }
jiabinbce0c1d2020-10-05 11:20:18 -07007795 sp<DeviceDescriptor> preferredDevice =
7796 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
7797 if (mEngine->getOutputDevicesForAttributes(
7798 client->attributes(), preferredDevice, false) == routedDevices) {
7799 return false;
7800 }
7801 }
7802 return true;
7803}
7804
7805sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01007806 const sp<IOProfile>& profile, const DeviceVector& devices,
7807 const audio_config_base_t *mixerConfig)
jiabinbce0c1d2020-10-05 11:20:18 -07007808{
7809 for (const auto& device : devices) {
7810 // TODO: This should be checking if the profile supports the device combo.
7811 if (!profile->supportsDevice(device)) {
7812 return nullptr;
7813 }
7814 }
7815 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
7816 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007817 status_t status = desc->open(nullptr /* halConfig */, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007818 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7819 if (status != NO_ERROR) {
7820 return nullptr;
7821 }
7822
7823 // Here is where the out_set_parameters() for card & device gets called
7824 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
7825 const audio_devices_t deviceType = device->type();
7826 const String8 &address = String8(device->address().c_str());
7827 if (!address.isEmpty()) {
7828 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
7829 mpClientInterface->setParameters(output, String8(param));
7830 free(param);
7831 }
7832 updateAudioProfiles(device, output, profile->getAudioProfiles());
7833 if (!profile->hasValidAudioProfile()) {
7834 ALOGW("%s() missing param", __func__);
7835 desc->close();
7836 return nullptr;
7837 } else if (profile->hasDynamicAudioProfile()) {
7838 desc->close();
7839 output = AUDIO_IO_HANDLE_NONE;
7840 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
7841 profile->pickAudioProfile(
7842 config.sample_rate, config.channel_mask, config.format);
7843 config.offload_info.sample_rate = config.sample_rate;
7844 config.offload_info.channel_mask = config.channel_mask;
7845 config.offload_info.format = config.format;
7846
Eric Laurentb4f42a92022-01-17 17:37:31 +01007847 status = desc->open(&config, mixerConfig, devices,
jiabinbce0c1d2020-10-05 11:20:18 -07007848 AUDIO_STREAM_DEFAULT, AUDIO_OUTPUT_FLAG_NONE, &output);
7849 if (status != NO_ERROR) {
7850 return nullptr;
7851 }
7852 }
7853
7854 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01007855
jiabinbce0c1d2020-10-05 11:20:18 -07007856 if (audio_is_remote_submix_device(deviceType) && address != "0") {
7857 sp<AudioPolicyMix> policyMix;
7858 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
7859 policyMix->setOutput(desc);
7860 desc->mPolicyMix = policyMix;
7861 } else {
7862 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
7863 address.string());
7864 }
7865
Eric Laurentb4f42a92022-01-17 17:37:31 +01007866 } else if (hasPrimaryOutput() && profile->getModule()
7867 != mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY)
7868 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
7869 // no duplicated output for:
7870 // - direct outputs
7871 // - outputs used by dynamic policy mixes
7872 // - outputs opened on the primary HW module
jiabinbce0c1d2020-10-05 11:20:18 -07007873 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
7874
7875 //TODO: configure audio effect output stage here
7876
7877 // open a duplicating output thread for the new output and the primary output
7878 sp<SwAudioOutputDescriptor> dupOutputDesc =
7879 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
7880 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
7881 if (status == NO_ERROR) {
7882 // add duplicated output descriptor
7883 addOutput(duplicatedOutput, dupOutputDesc);
7884 } else {
7885 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
7886 mPrimaryOutput->mIoHandle, output);
7887 desc->close();
7888 removeOutput(output);
7889 nextAudioPortGeneration();
7890 return nullptr;
7891 }
7892 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02007893 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
7894 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
7895 mPrimaryOutput = desc;
7896 }
jiabinbce0c1d2020-10-05 11:20:18 -07007897 return desc;
7898}
7899
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08007900} // namespace android