blob: 5b736ca9d24cd45e28341154491acd029064eeb9 [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
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Eric Laurentb2fb4102024-06-21 12:25:26 +000069using com::android::media::audioserver::fix_call_audio_patch;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000070using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070071
Eric Laurentdc462862016-07-19 12:29:53 -070072//FIXME: workaround for truncated touch sounds
73// to be removed when the problem is handled by system UI
74#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070075
76// Largest difference in dB on earpiece in call between the voice volume and another
77// media / notification / system volume.
78constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
79
jiabin06e4bab2019-07-29 10:13:34 -070080template <typename T>
81bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
82{
83 if (left.size() != right.size()) {
84 return false;
85 }
86 for (size_t index = 0; index < right.size(); index++) {
87 if (left[index] != right[index]) {
88 return false;
89 }
90 }
91 return true;
92}
93
94template <typename T>
95bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
96{
97 return !(left == right);
98}
99
Eric Laurente552edb2014-03-10 17:42:56 -0700100// ----------------------------------------------------------------------------
101// AudioPolicyInterface implementation
102// ----------------------------------------------------------------------------
103
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100104status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
105 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
106 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800107 nextAudioPortGeneration();
108 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800109}
110
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100111status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
112 audio_policy_dev_state_t state,
113 const char* device_address,
114 const char* device_name,
115 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800116 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100117 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
118 status == OK) {
119 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
120 } else {
121 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
122 return status;
123 }
124}
125
François Gaffie11d30102018-11-02 16:09:09 +0100126void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000127 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200128{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000129 audio_port_v7 devicePort;
130 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000131 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000132 status != OK) {
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700133 ALOGE("Error %d while setting connected state %d for device %s",
134 status, static_cast<int>(state),
Mikhail Naganov516d3982022-02-01 23:53:59 +0000135 device->getDeviceTypeAddr().toString(false).c_str());
136 }
François Gaffie44481e72016-04-20 07:49:57 +0200137}
138
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100139status_t AudioPolicyManager::setDeviceConnectionStateInt(
140 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
141 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100142 if (port.ext.getTag() != AudioPortExt::device) {
143 return BAD_VALUE;
144 }
145 audio_devices_t device_type;
146 std::string device_address;
147 if (status_t status = aidl2legacy_AudioDevice_audio_device(
148 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
149 status != OK) {
150 return status;
151 };
152 const char* device_name = port.name.c_str();
153 // connect/disconnect only 1 device at a time
154 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
155 return BAD_VALUE;
156
157 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
158 device_type, device_address.c_str(), device_name, encodedFormat,
159 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000160 if (device == nullptr) {
161 return INVALID_OPERATION;
162 }
163 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
164 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
165 }
166 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100167}
168
François Gaffie11d30102018-11-02 16:09:09 +0100169status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800170 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100171 const char* device_address,
172 const char* device_name,
173 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800174 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100175 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
176 status == OK) {
177 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
178 } else {
179 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
180 return status;
181 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700182}
Paul McLeane743a472015-01-28 11:07:31 -0800183
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700184status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
185 audio_policy_dev_state_t state)
186{
Eric Laurente552edb2014-03-10 17:42:56 -0700187 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700188 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700189 SortedVector <audio_io_handle_t> outputs;
190
François Gaffie11d30102018-11-02 16:09:09 +0100191 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700192
Eric Laurente552edb2014-03-10 17:42:56 -0700193 // save a copy of the opened output descriptors before any output is opened or closed
194 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
195 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100196
197 bool wasLeUnicastActive = isLeUnicastActive();
198
Eric Laurente552edb2014-03-10 17:42:56 -0700199 switch (state)
200 {
201 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800202 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700203 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100204 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700205 return INVALID_OPERATION;
206 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800207 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700208 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700209
Eric Laurente552edb2014-03-10 17:42:56 -0700210 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200211 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700212 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700213 }
214
François Gaffie44481e72016-04-20 07:49:57 +0200215 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
216 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000217 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200218
François Gaffie11d30102018-11-02 16:09:09 +0100219 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
220 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200221
jiabinc0048632023-04-27 22:04:31 +0000222 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700223
224 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700225 return INVALID_OPERATION;
226 }
François Gaffie2110e042015-03-24 08:41:51 +0100227
jiabin1c4794b2020-05-05 10:08:05 -0700228 // Populate encapsulation information when a output device is connected.
229 device->setEncapsulationInfoFromHal(mpClientInterface);
230
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700231 // outputs should never be empty here
232 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
233 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100234 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800235
Eric Laurent3ae5f312015-02-03 17:12:08 -0800236 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700237 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700238 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700239 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100240 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700241 return INVALID_OPERATION;
242 }
243
François Gaffie11d30102018-11-02 16:09:09 +0100244 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700245
jiabinc0048632023-04-27 22:04:31 +0000246 // Notify the HAL to prepare to disconnect device
247 broadcastDeviceConnectionState(
248 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700249
Eric Laurente552edb2014-03-10 17:42:56 -0700250 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100251 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700252
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100253 mOutputs.clearSessionRoutesForDevice(device);
254
François Gaffie11d30102018-11-02 16:09:09 +0100255 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100256
jiabinc0048632023-04-27 22:04:31 +0000257 // Send Disconnect to HALs
258 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
259
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800260 // Reset active device codec
261 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
262
Kriti Dangef6be8f2020-11-05 11:58:19 +0100263 // remove device from mReportedFormatsMap cache
264 mReportedFormatsMap.erase(device);
265
jiabina84c3d32022-12-02 18:59:55 +0000266 // remove preferred mixer configurations
267 mPreferredMixerAttrInfos.erase(device->getId());
268
Eric Laurente552edb2014-03-10 17:42:56 -0700269 } break;
270
271 default:
François Gaffie11d30102018-11-02 16:09:09 +0100272 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700273 return BAD_VALUE;
274 }
275
Eric Laurent736a1022019-03-27 18:28:46 -0700276 // Propagate device availability to Engine
277 setEngineDeviceConnectionState(device, state);
278
Eric Laurentae970022019-01-29 14:25:04 -0800279 // No need to evaluate playback routing when connecting a remote submix
280 // output device used by a dynamic policy of type recorder as no
281 // playback use case is affected.
282 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700283 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800284 for (audio_io_handle_t output : outputs) {
285 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800286 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
287 if (policyMix != nullptr
288 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000289 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800290 doCheckForDeviceAndOutputChanges = false;
291 break;
292 }
293 }
294 }
295
296 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700297 // outputs must be closed after checkOutputForAllStrategies() is executed
298 if (!outputs.isEmpty()) {
299 for (audio_io_handle_t output : outputs) {
300 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100301 // close unused outputs after device disconnection or direct outputs that have
302 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200303 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200304 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
305 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200306 (desc->mDirectOpenCount == 0))
307 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
308 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200309 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700310 closeOutput(output);
311 }
Eric Laurente552edb2014-03-10 17:42:56 -0700312 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700313 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
314 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700315 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700316 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800317 };
318
319 if (doCheckForDeviceAndOutputChanges) {
320 checkForDeviceAndOutputChanges(checkCloseOutputs);
321 } else {
322 checkCloseOutputs();
323 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100324 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100325 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700326 const DeviceVector activeMediaDevices =
327 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000328 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700329 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700330 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530331 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
332 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100333 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700334 // do not force device change on duplicated output because if device is 0, it will
335 // also force a device 0 for the two outputs it is duplicated to which may override
336 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100337 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100338 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700339 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700340 // always force when disconnecting (a non-duplicated device)
341 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000342 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000343 // If the device is using preferred mixer attributes, the output need to reopen
344 // with default configuration when the new selected devices are different from
345 // current routing devices
346 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
347 continue;
348 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530349 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700350 }
jiabinbce0c1d2020-10-05 11:20:18 -0700351 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000352 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700353 desc->supportsDevicesForPlayback(activeMediaDevices)) {
354 // Reopen the output to query the dynamic profiles when there is not active
355 // clients or all active clients will be rerouted. Otherwise, set the flag
356 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
357 // can be reopened to query dynamic profiles when all clients are inactive.
358 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000359 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700360 } else {
361 desc->mPendingReopenToQueryProfiles = true;
362 }
363 }
364 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
365 // Clear the flag that previously set for re-querying profiles.
366 desc->mPendingReopenToQueryProfiles = false;
367 }
368 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000369 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700370
Eric Laurentd60560a2015-04-10 11:31:20 -0700371 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100372 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700373 }
374
Eric Laurent96d1dda2022-03-14 17:14:19 +0100375 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
376
Eric Laurent72aa32f2014-05-30 18:51:48 -0700377 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700378 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700379 } // end if is output device
380
Eric Laurente552edb2014-03-10 17:42:56 -0700381 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700382 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700384 switch (state)
385 {
386 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700387 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700388 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100389 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700390 return INVALID_OPERATION;
391 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700392
393 if (mAvailableInputDevices.add(device) < 0) {
394 return NO_MEMORY;
395 }
396
François Gaffie44481e72016-04-20 07:49:57 +0200397 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
398 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000399 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700400 // Propagate device availability to Engine
401 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200402
Eric Laurent0dd51852019-04-19 18:18:58 -0700403 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700404 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
405
Eric Laurent0dd51852019-04-19 18:18:58 -0700406 mAvailableInputDevices.remove(device);
407
jiabinc0048632023-04-27 22:04:31 +0000408 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100409
410 mHwModules.cleanUpForDevice(device);
411
Eric Laurentd4692962014-05-05 18:13:44 -0700412 return INVALID_OPERATION;
413 }
414
Eric Laurentd4692962014-05-05 18:13:44 -0700415 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700416
417 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700418 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700419 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100420 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700421 return INVALID_OPERATION;
422 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700423
François Gaffie11d30102018-11-02 16:09:09 +0100424 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700425
jiabinc0048632023-04-27 22:04:31 +0000426 // Notify the HAL to prepare to disconnect device
427 broadcastDeviceConnectionState(
428 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700429
François Gaffie11d30102018-11-02 16:09:09 +0100430 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700431
432 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100433
jiabinc0048632023-04-27 22:04:31 +0000434 // Set Disconnect to HALs
435 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
436
Kriti Dangef6be8f2020-11-05 11:58:19 +0100437 // remove device from mReportedFormatsMap cache
438 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700439
440 // Propagate device availability to Engine
441 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700442 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700443
444 default:
François Gaffie11d30102018-11-02 16:09:09 +0100445 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700446 return BAD_VALUE;
447 }
448
Eric Laurent0dd51852019-04-19 18:18:58 -0700449 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700450 // As the input device list can impact the output device selection, update
451 // getDeviceForStrategy() cache
452 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700453
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100454 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200455 // Reconnect Audio Source
456 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
457 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
458 checkAudioSourceForAttributes(attributes);
459 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700460 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100461 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700462 }
463
Eric Laurentb52c1522014-05-20 11:27:36 -0700464 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700465 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700466 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700467
François Gaffie11d30102018-11-02 16:09:09 +0100468 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700469 return BAD_VALUE;
470}
471
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100472status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
473 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800474 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700475 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
476 devDescr->setName(device_name);
477 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100478}
479
Eric Laurent736a1022019-03-27 18:28:46 -0700480void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
481 audio_policy_dev_state_t state) {
482
483 // the Engine does not have to know about remote submix devices used by dynamic audio policies
484 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
485 return;
486 }
487 mEngine->setDeviceConnectionState(device, state);
488}
489
490
Eric Laurente0720872014-03-11 09:30:41 -0700491audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100492 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700493{
Eric Laurent634b7142016-04-20 13:48:02 -0700494 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800495 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
496 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700497 (strlen(device_address) != 0)/*matchAddress*/);
498
499 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100500 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700501 device, device_address);
502 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
503 }
François Gaffie53615e22015-03-19 09:24:12 +0100504
Eric Laurent3a4311c2014-03-17 12:00:47 -0700505 DeviceVector *deviceVector;
506
Eric Laurente552edb2014-03-10 17:42:56 -0700507 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700508 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700509 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700510 deviceVector = &mAvailableInputDevices;
511 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100512 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700513 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700514 }
Eric Laurent634b7142016-04-20 13:48:02 -0700515
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800516 return (deviceVector->getDevice(
517 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700518 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800519}
520
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800521status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
522 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800523 const char *device_name,
524 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800526 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
527 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800528
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800529 // connect/disconnect only 1 device at a time
530 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
531
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800532 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700533 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800534 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800535 // Nothing to do: device is not connected
536 return NO_ERROR;
537 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800538 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800539
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700540 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800541 // configure codecs.
542 // Handle two specific cases by sending a set parameter to
543 // configure A2DP codecs. No need to toggle device state.
544 // Case 1: A2DP active device switches from primary to primary
545 // module
546 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100547 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700548 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800549 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
550 if (availablePrimaryOutputDevices().contains(devDesc) &&
551 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100552 bool isA2dp = audio_is_a2dp_out_device(device);
553 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
554 : String8(AudioParameter::keyReconfigLeSupported);
555 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800556 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100557 int isReconfigSupported;
558 repliedParameters.getInt(supportKey, isReconfigSupported);
559 if (isReconfigSupported) {
560 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
561 : String8(AudioParameter::keyReconfigLe);
562 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800563 param.add(key, String8("true"));
564 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
565 devDesc->setEncodedFormat(encodedFormat);
566 return NO_ERROR;
567 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700568 }
569 }
cnx421bd2dcc42020-07-11 14:58:44 +0800570 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000571 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800572 for (size_t i = 0; i < mOutputs.size(); i++) {
573 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000574 // mute media strategies to avoid sending the music tail into
575 // the earpiece or headset.
576 if (desc->isStrategyActive(musicStrategy)) {
577 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
578 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
579 tempRecommendedMuteDuration : desc->latency() * 4;
580 if (muteWaitMs < tempMuteDurationMs) {
581 muteWaitMs = tempMuteDurationMs;
582 }
583 }
cnx421bd2dcc42020-07-11 14:58:44 +0800584 setStrategyMute(musicStrategy, true, desc);
585 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
586 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
587 nullptr, true /*fromCache*/).types());
588 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000589 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
590 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
591 // happens after the actual device switch.
592 if (muteWaitMs > 0) {
593 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
594 usleep(muteWaitMs * 1000);
595 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800596 // Toggle the device state: UNAVAILABLE -> AVAILABLE
597 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100598 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800599 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800600 device_address, device_name,
601 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800602 if (status != NO_ERROR) {
603 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
604 status);
605 return status;
606 }
607
608 status = setDeviceConnectionState(device,
609 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800610 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800611 if (status != NO_ERROR) {
612 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
613 status);
614 return status;
615 }
616
617 return NO_ERROR;
618}
619
Pattydd807582021-11-04 21:01:03 +0800620status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
621 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800622{
Pattydd807582021-11-04 21:01:03 +0800623 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800624 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800625 std::unordered_set<audio_format_t> formatSet;
626 sp<HwModule> primaryModule =
627 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700628 if (primaryModule == nullptr) {
629 ALOGE("%s() unable to get primary module", __func__);
630 return NO_INIT;
631 }
Pattydd807582021-11-04 21:01:03 +0800632
633 DeviceTypeSet audioDeviceSet;
634
635 switch(device) {
636 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
637 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
638 break;
639 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800640 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
641 break;
642 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
643 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800644 break;
645 default:
646 ALOGE("%s() device type 0x%08x not supported", __func__, device);
647 return BAD_VALUE;
648 }
649
jiabin9a3361e2019-10-01 09:38:30 -0700650 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800651 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800652 for (const auto& device : declaredDevices) {
653 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800654 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800655 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800656 return status;
657}
658
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100659DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
660{
661 DeviceVector rxSinkdevices{};
662 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
663 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
664 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
665 auto rxSinkDevice = rxSinkdevices.itemAt(0);
666 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
667 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
668 // retrieve Rx Source device descriptor
669 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
670 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
671
672 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
673 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
674 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
675 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
676 return DeviceVector(rxSinkDevice);
677 }
678 }
679 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
680 // the device returned is not necessarily reachable via this output
681 // (filter later by setOutputDevices())
682 return getNewOutputDevices(mPrimaryOutput, fromCache);
683}
684
685status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
686{
François Gaffiedb1755b2023-09-01 11:50:35 +0200687 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100688 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
689 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
690 }
691 return INVALID_OPERATION;
692}
693
694status_t AudioPolicyManager::updateCallRoutingInternal(
695 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700696{
697 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100698 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700699 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200700 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700701 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100702 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700703 }
François Gaffie11d30102018-11-02 16:09:09 +0100704
Francois Gaffie716e1432019-01-14 16:58:59 +0100705 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100706 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200707
Eric Laurentb2fb4102024-06-21 12:25:26 +0000708 if (!fix_call_audio_patch()) {
709 disconnectTelephonyAudioSource(mCallRxSourceClient);
710 disconnectTelephonyAudioSource(mCallTxSourceClient);
711 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200712
713 if (rxDevices.isEmpty()) {
714 ALOGW("%s() no selected output device", __func__);
715 return INVALID_OPERATION;
716 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000717 if (txSourceDevice == nullptr) {
718 ALOGE("%s() selected input device not available", __func__);
719 return INVALID_OPERATION;
720 }
François Gaffiec005e562018-11-06 15:04:49 +0100721
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100722 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100723 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700724
François Gaffie9eb18552018-11-05 10:33:26 +0100725 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700726 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100727 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700728 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100729 // retrieve Rx Source and Tx Sink device descriptors
730 sp<DeviceDescriptor> rxSourceDevice =
731 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
732 String8(),
733 AUDIO_FORMAT_DEFAULT);
734 sp<DeviceDescriptor> txSinkDevice =
735 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
736 String8(),
737 AUDIO_FORMAT_DEFAULT);
738
739 // RX and TX Telephony device are declared by Primary Audio HAL
740 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
741 (telephonyRxModule->getHalVersionMajor() >= 3)) {
742 if (rxSourceDevice == 0 || txSinkDevice == 0) {
743 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100744 ALOGE("%s() no telephony Tx and/or RX device", __func__);
745 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100746 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100747 // createAudioPatchInternal now supports both HW / SW bridging
748 createRxPatch = true;
749 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100750 } else {
751 // If the RX device is on the primary HW module, then use legacy routing method for
752 // voice calls via setOutputDevice() on primary output.
753 // Otherwise, create two audio patches for TX and RX path.
754 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
755 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700756 // If the TX device is also on the primary HW module, setOutputDevice() will take care
757 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100758 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
759 (txSinkDevice != 0);
760 }
761 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
762 // Otherwise, create two audio patches for TX and RX path.
763 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000764 if (fix_call_audio_patch()) {
765 disconnectTelephonyAudioSource(mCallRxSourceClient);
766 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200767 if (!hasPrimaryOutput()) {
768 ALOGW("%s() no primary output available", __func__);
769 return INVALID_OPERATION;
770 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530771 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700772 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200773 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800774 // If the TX device is on the primary HW module but RX device is
775 // on other HW module, SinkMetaData of telephony input should handle it
776 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700777 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700778 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100779 // terminate active capture if on the same HW module as the call TX source device
780 // FIXME: would be better to refine to only inputs whose profile connects to the
781 // call TX device but this information is not in the audio patch and logic here must be
782 // symmetric to the one in startInput()
783 for (const auto& activeDesc : mInputs.getActiveInputs()) {
784 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
785 closeActiveClients(activeDesc);
786 }
787 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200788 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000789 } else if (fix_call_audio_patch()) {
790 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800791 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100792 if (waitMs != nullptr) {
793 *waitMs = muteWaitMs;
794 }
795 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800796}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700797
Mikhail Naganov100f0122018-11-29 11:22:16 -0800798bool AudioPolicyManager::isDeviceOfModule(
799 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
800 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
801 if (module != 0) {
802 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
803 .indexOf(devDesc) != NAME_NOT_FOUND
804 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
805 .indexOf(devDesc) != NAME_NOT_FOUND;
806 }
807 return false;
808}
809
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200810void AudioPolicyManager::connectTelephonyRxAudioSource()
811{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000812 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
813
814 if (fix_call_audio_patch()) {
815 if (mCallRxSourceClient != nullptr) {
816 DeviceVector rxDevices =
817 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
818 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
819 "connectTelephonyRxAudioSource(): no device found for call RX source");
820 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
821 if (mCallRxSourceClient->isConnected()
822 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
823 return;
824 }
825 disconnectTelephonyAudioSource(mCallRxSourceClient);
826 }
827 } else {
828 disconnectTelephonyAudioSource(mCallRxSourceClient);
829 }
830
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200831 const struct audio_port_config source = {
832 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
833 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
834 };
Eric Laurent541a2002024-01-15 18:11:42 +0100835 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000836
Eric Laurentccbd7872024-06-20 12:34:15 +0000837 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
838 true /*internal*/, true /*isCallRx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100839 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
840 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000841 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
842 mCallRxSourceClient->srcDevice()->toString().c_str(),
843 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200844 ALOGE_IF(mCallRxSourceClient == nullptr,
845 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200846}
847
Francois Gaffie601801d2021-06-22 13:27:39 +0200848void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200849{
Francois Gaffie601801d2021-06-22 13:27:39 +0200850 if (clientDesc == nullptr) {
851 return;
852 }
853 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
854 "%s error stopping audio source", __func__);
855 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200856}
857
858void AudioPolicyManager::connectTelephonyTxAudioSource(
859 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
860 uint32_t delayMs)
861{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200862 if (srcDevice == nullptr || sinkDevice == nullptr) {
863 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
864 return;
865 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000866
867 if (fix_call_audio_patch()) {
868 if (mCallTxSourceClient != nullptr) {
869 if (mCallTxSourceClient->isConnected()
870 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
871 return;
872 }
873 disconnectTelephonyAudioSource(mCallTxSourceClient);
874 }
875 } else {
876 disconnectTelephonyAudioSource(mCallTxSourceClient);
877 }
878
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200879 PatchBuilder patchBuilder;
880 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000881
Francois Gaffie601801d2021-06-22 13:27:39 +0200882 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200883 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
884
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200885 struct audio_port_config source = {};
886 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100887 mCallTxSourceClient = new SourceClientDescriptor(
888 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000889 mCommunnicationStrategy, toVolumeSource(aa), true,
890 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100891 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
892
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200893 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
894 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200895 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
896 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200897 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000898 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
899 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200900 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200901 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200902 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200903}
904
Eric Laurente0720872014-03-11 09:30:41 -0700905void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700906{
907 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100908 // store previous phone state for management of sonification strategy below
909 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100910 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100911
912 if (mEngine->setPhoneState(state) != NO_ERROR) {
913 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700914 return;
915 }
François Gaffie2110e042015-03-24 08:41:51 +0100916 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700917 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700918 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700919 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800920 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700921 }
922
François Gaffie2110e042015-03-24 08:41:51 +0100923 /**
924 * Switching to or from incall state or switching between telephony and VoIP lead to force
925 * routing command.
926 */
Eric Laurent74b71512019-11-06 17:21:57 -0800927 bool force = ((isStateInCall(oldState) != isStateInCall(state))
928 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700929
930 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700931 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700932
Eric Laurente552edb2014-03-10 17:42:56 -0700933 int delayMs = 0;
934 if (isStateInCall(state)) {
935 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100936 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
937 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700938 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700939 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700940 // mute media and sonification strategies and delay device switch by the largest
941 // latency of any output where either strategy is active.
942 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100943 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
944 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
945 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700946 (delayMs < (int)desc->latency()*2)) {
947 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700948 }
François Gaffiec005e562018-11-06 15:04:49 +0100949 setStrategyMute(musicStrategy, true, desc);
950 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
951 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
952 nullptr, true /*fromCache*/).types());
953 setStrategyMute(sonificationStrategy, true, desc);
954 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
955 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
956 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700957 }
958 }
959
François Gaffiedb1755b2023-09-01 11:50:35 +0200960 if (state == AUDIO_MODE_IN_CALL) {
961 (void)updateCallRouting(false /*fromCache*/, delayMs);
962 } else {
963 if (oldState == AUDIO_MODE_IN_CALL) {
964 disconnectTelephonyAudioSource(mCallRxSourceClient);
965 disconnectTelephonyAudioSource(mCallTxSourceClient);
966 }
967 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100968 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
969 // force routing command to audio hardware when ending call
970 // even if no device change is needed
971 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
972 rxDevices = mPrimaryOutput->devices();
973 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530974 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700975 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700976 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700977
jiabin3ff8d7d2022-12-13 06:27:44 +0000978 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700979 // reevaluate routing on all outputs in case tracks have been started during the call
980 for (size_t i = 0; i < mOutputs.size(); i++) {
981 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100982 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000983 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
984 && desc->mPreferredAttrInfo != nullptr) {
985 // If the output is using preferred mixer attributes and the audio mode is not normal,
986 // the output need to reopen with default configuration.
987 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
988 continue;
989 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200990 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
991 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530992 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200993 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700994 }
995 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000996 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700997
Eric Laurent96d1dda2022-03-14 17:14:19 +0100998 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
999
Eric Laurente552edb2014-03-10 17:42:56 -07001000 if (isStateInCall(state)) {
1001 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001002 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001003 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001004 }
1005
1006 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001007 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1008 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001009}
1010
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001011audio_mode_t AudioPolicyManager::getPhoneState() {
1012 return mEngine->getPhoneState();
1013}
1014
Eric Laurente0720872014-03-11 09:30:41 -07001015void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001016 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001017{
François Gaffie2110e042015-03-24 08:41:51 +01001018 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001019 if (config == mEngine->getForceUse(usage)) {
1020 return;
1021 }
Eric Laurente552edb2014-03-10 17:42:56 -07001022
François Gaffie2110e042015-03-24 08:41:51 +01001023 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1024 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1025 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001026 }
François Gaffie2110e042015-03-24 08:41:51 +01001027 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1028 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1029 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001030
1031 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001032 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001033
Eric Laurent22fcda22019-05-17 16:28:47 -07001034 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1035 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001036 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001037 }
1038
Eric Laurentdc462862016-07-19 12:29:53 -07001039 //FIXME: workaround for truncated touch sounds
1040 // to be removed when the problem is handled by system UI
1041 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001042 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1043 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1044 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001045
1046 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001047 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001048}
1049
Eric Laurente0720872014-03-11 09:30:41 -07001050void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001051{
1052 ALOGV("setSystemProperty() property %s, value %s", property, value);
1053}
1054
Dorin Drimusecc9f422022-03-09 17:57:40 +01001055// Find an MSD output profile compatible with the parameters passed.
1056// When "directOnly" is set, restrict search to profiles for direct outputs.
1057sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1058 const DeviceVector& devices,
1059 uint32_t samplingRate,
1060 audio_format_t format,
1061 audio_channel_mask_t channelMask,
1062 audio_output_flags_t flags,
1063 bool directOnly)
1064{
1065 flags = getRelevantFlags(flags, directOnly);
1066
1067 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1068 if (msdModule != nullptr) {
1069 // for the msd module check if there are patches to the output devices
1070 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1071 HwModuleCollection modules;
1072 modules.add(msdModule);
1073 return searchCompatibleProfileHwModules(
1074 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1075 flags, directOnly);
1076 }
1077 }
1078 return nullptr;
1079}
1080
Michael Chana94fbb22018-04-24 14:31:19 +10001081// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1082// search to profiles for direct outputs.
1083sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001084 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001085 uint32_t samplingRate,
1086 audio_format_t format,
1087 audio_channel_mask_t channelMask,
1088 audio_output_flags_t flags,
1089 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001090{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001091 flags = getRelevantFlags(flags, directOnly);
1092
1093 return searchCompatibleProfileHwModules(
1094 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1095}
1096
1097audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1098 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001099 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001100 // only retain flags that will drive the direct output profile selection
1101 // if explicitly requested
1102 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001103 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001104 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1105 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001106 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001107 return flags;
1108}
Eric Laurent861a6282015-05-18 15:40:16 -07001109
Dorin Drimusecc9f422022-03-09 17:57:40 +01001110sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1111 const HwModuleCollection& hwModules,
1112 const DeviceVector& devices,
1113 uint32_t samplingRate,
1114 audio_format_t format,
1115 audio_channel_mask_t channelMask,
1116 audio_output_flags_t flags,
1117 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001118 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001119 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001120 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001121 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001122 samplingRate, NULL /*updatedSamplingRate*/,
1123 format, NULL /*updatedFormat*/,
1124 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001125 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001126 continue;
1127 }
1128 // reject profiles not corresponding to a device currently available
1129 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1130 continue;
1131 }
1132 // reject profiles if connected device does not support codec
1133 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1134 continue;
1135 }
1136 if (!directOnly) {
1137 return curProfile;
1138 }
1139
1140 // when searching for direct outputs, if several profiles are compatible, give priority
1141 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001142 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001143 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001144 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001145 }
1146 profile = curProfile;
1147 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1148 break;
1149 }
Eric Laurente552edb2014-03-10 17:42:56 -07001150 }
1151 }
Eric Laurent861a6282015-05-18 15:40:16 -07001152 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001153}
1154
Eric Laurentfa0f6742021-08-17 18:39:44 +02001155sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001156 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001157{
1158 for (const auto& hwModule : mHwModules) {
1159 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001160 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001161 continue;
1162 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001163 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001164 // reject profiles not corresponding to a device currently available
1165 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1166 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1167 continue;
1168 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001169 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1170 != devices.size()) {
1171 continue;
1172 }
1173 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001174 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1175 return curProfile;
1176 }
1177 }
1178 return nullptr;
1179}
1180
Eric Laurentf4e63452017-11-06 19:31:46 +00001181audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001182{
François Gaffiec005e562018-11-06 15:04:49 +01001183 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001184
1185 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1186 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1187 // format, flags, etc. This may result in some discrepancy for functions that utilize
1188 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1189 // and AudioSystem::getOutputSamplingRate().
1190
François Gaffie11d30102018-11-02 16:09:09 +01001191 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001192 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1193 if (stream == AUDIO_STREAM_MUSIC &&
1194 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1195 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1196 }
1197 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001198
François Gaffie11d30102018-11-02 16:09:09 +01001199 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1200 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001201 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001202}
1203
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001204status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1205 const audio_attributes_t *srcAttr,
1206 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001207{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001208 if (srcAttr != NULL) {
1209 if (!isValidAttributes(srcAttr)) {
1210 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1211 __func__,
1212 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1213 srcAttr->tags);
1214 return BAD_VALUE;
1215 }
1216 *dstAttr = *srcAttr;
1217 } else {
1218 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1219 ALOGE("%s: invalid stream type", __func__);
1220 return BAD_VALUE;
1221 }
François Gaffiec005e562018-11-06 15:04:49 +01001222 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001223 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001224
1225 // Only honor audibility enforced when required. The client will be
1226 // forced to reconnect if the forced usage changes.
1227 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001228 dstAttr->flags = static_cast<audio_flags_mask_t>(
1229 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001230 }
1231
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001232 return NO_ERROR;
1233}
1234
Kevin Rocard153f92d2018-12-18 18:33:28 -08001235status_t AudioPolicyManager::getOutputForAttrInt(
1236 audio_attributes_t *resultAttr,
1237 audio_io_handle_t *output,
1238 audio_session_t session,
1239 const audio_attributes_t *attr,
1240 audio_stream_type_t *stream,
1241 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001242 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001243 audio_output_flags_t *flags,
1244 audio_port_handle_t *selectedDeviceId,
1245 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001246 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001247 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001248 bool *isSpatialized,
1249 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001250{
François Gaffiec005e562018-11-06 15:04:49 +01001251 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001252 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001253 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001254 const sp<DeviceDescriptor> requestedDevice =
1255 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1256
Eric Laurent8a1095a2019-11-08 14:44:16 -08001257 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001258 *isSpatialized = false;
1259
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001260 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1261 if (status != NO_ERROR) {
1262 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001263 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001264 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001265 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001266 }
François Gaffiec005e562018-11-06 15:04:49 +01001267 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001268
François Gaffiec005e562018-11-06 15:04:49 +01001269 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1270 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001271
Oscar Azucena873d10f2023-01-12 18:34:42 -08001272 bool usePrimaryOutputFromPolicyMixes = false;
1273
Kevin Rocard153f92d2018-12-18 18:33:28 -08001274 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1275 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1276 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001277 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001278 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1279 .channel_mask = config->channel_mask,
1280 .format = config->format,
1281 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001282 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001283 mAvailableOutputDevices, requestedDevice, primaryMix,
1284 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001285 if (status != OK) {
1286 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001287 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001288
Kevin Rocard153f92d2018-12-18 18:33:28 -08001289 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001290 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1291 && !audio_is_linear_pcm(config->format)) {
1292 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001293 return BAD_VALUE;
1294 }
1295 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001296 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001297 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1298 primaryMix->mDeviceAddress,
1299 AUDIO_FORMAT_DEFAULT);
1300 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001301 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001302 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1303 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001304 // if a direct output can be opened to deliver the track's multi-channel content to the
1305 // output rather than being downmixed by the primary output, then use this direct
1306 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1307 // mix.
1308 bool tryDirectForChannelMask = policyDesc != nullptr
1309 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1310 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001311 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001312 audio_io_handle_t newOutput;
1313 status = openDirectOutput(
1314 *stream, session, config,
1315 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangf6e304f2024-07-09 23:06:58 -07001316 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001317 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001318 policyDesc = mOutputs.valueFor(newOutput);
1319 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001320 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001321 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001322 policyDesc = nullptr;
1323 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001324 }
1325 if (policyDesc != nullptr) {
1326 policyDesc->mPolicyMix = primaryMix;
1327 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001328 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1329 : AUDIO_PORT_HANDLE_NONE;
1330 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1331 // Remove direct flag as it is not on a direct output.
1332 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1333 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001334
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001335 ALOGV("getOutputForAttr() returns output %d", *output);
1336 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1337 *outputType = API_OUT_MIX_PLAYBACK;
1338 } else {
1339 *outputType = API_OUTPUT_LEGACY;
1340 }
1341 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001342 } else {
1343 if (policyMixDevice != nullptr) {
1344 ALOGE("%s, try to use primary mix but no output found", __func__);
1345 return INVALID_OPERATION;
1346 }
1347 // Fallback to default engine selection as the selected primary mix device is not
1348 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001349 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001350 }
François Gaffiec005e562018-11-06 15:04:49 +01001351 // Virtual sources must always be dynamicaly or explicitly routed
1352 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1353 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1354 return BAD_VALUE;
1355 }
1356 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1357 // in order to let the choice of the order to future vendor engine
1358 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001359
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001360 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001361 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001362 }
1363
Nadav Barb2f18162018-07-18 13:01:53 +03001364 // Set incall music only if device was explicitly set, and fallback to the device which is
1365 // chosen by the engine if not.
1366 // FIXME: provide a more generic approach which is not device specific and move this back
1367 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001368 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001369 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001370 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001371 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001372 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001373 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001374 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001375 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001376 }
1377 }
1378
François Gaffiec005e562018-11-06 15:04:49 +01001379 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1380 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1381 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001382
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001383 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001384 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001385 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001386 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001387 ALOGV("%s() Using MSD devices %s instead of devices %s",
1388 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001389 } else {
1390 *output = AUDIO_IO_HANDLE_NONE;
1391 }
1392 }
1393 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001394 sp<PreferredMixerAttributesInfo> info = nullptr;
1395 if (outputDevices.size() == 1) {
1396 info = getPreferredMixerAttributesInfo(
1397 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001398 mEngine->getProductStrategyForAttributes(*resultAttr),
1399 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001400 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1401 // and it is currently active.
1402 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001403 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001404 info = nullptr;
1405 }
jiabin220eea12024-05-17 17:55:20 +00001406 if (com::android::media::audioserver::
1407 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1408 if (info != nullptr && info->getUid() == uid &&
1409 info->configMatches(*config) &&
1410 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1411 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1412 [this, &outputDevices](audio_usage_t usage) {
1413 return mOutputs.isUsageActiveOnDevice(
1414 usage, outputDevices[0]); }))) {
1415 // Bit-perfect request is not allowed when the phone mode is not normal or
1416 // there is any higher priority user case active.
1417 return INVALID_OPERATION;
1418 }
1419 }
jiabina84c3d32022-12-02 18:59:55 +00001420 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001421 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001422 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001423 // The client will be active if the client is currently preferred mixer owner and the
1424 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001425 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001426 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001427 && info->getUid() == uid
1428 && *output != AUDIO_IO_HANDLE_NONE
1429 // When bit-perfect output is selected for the preferred mixer attributes owner,
1430 // only need to consider the config matches.
1431 && mOutputs.valueFor(*output)->isConfigurationMatched(
1432 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001433
1434 if (*isBitPerfect) {
1435 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1436 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001437 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001438 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001439 AudioProfileVector profiles;
1440 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1441 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001442 const auto channels = profiles[0]->getChannels();
1443 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1444 config->channel_mask = *channels.begin();
1445 }
1446 const auto sampleRates = profiles[0]->getSampleRates();
1447 if (!sampleRates.empty() &&
1448 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1449 config->sample_rate = *sampleRates.begin();
1450 }
jiabinf1c73972022-04-14 16:28:52 -07001451 config->format = profiles[0]->getFormat();
1452 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001453 return INVALID_OPERATION;
1454 }
Paul McLeanaa981192015-03-21 09:55:15 -07001455
François Gaffiec005e562018-11-06 15:04:49 +01001456 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001457 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001458 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001459 *selectedDeviceId = outputDevice->getId();
1460 break;
1461 }
1462 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001463
Eric Laurent8a1095a2019-11-08 14:44:16 -08001464 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1465 *outputType = API_OUTPUT_TELEPHONY_TX;
1466 } else {
1467 *outputType = API_OUTPUT_LEGACY;
1468 }
1469
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001470 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1471
1472 return NO_ERROR;
1473}
1474
1475status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1476 audio_io_handle_t *output,
1477 audio_session_t session,
1478 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001479 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001480 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001481 audio_output_flags_t *flags,
1482 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001483 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001484 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001485 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001486 bool *isSpatialized,
1487 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001488{
1489 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1490 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1491 return INVALID_OPERATION;
1492 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001493 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001494 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001495 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001496 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001497 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001498 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001499 const sp<DeviceDescriptor> requestedDevice =
1500 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1501
1502 // Prevent from storing invalid requested device id in clients
1503 const audio_port_handle_t sanitizedRequestedPortId =
1504 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1505 *selectedDeviceId = sanitizedRequestedPortId;
1506
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001507 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001508 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001509 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1510 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001511 if (status != NO_ERROR) {
1512 return status;
1513 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001514 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001515 if (secondaryOutputs != nullptr) {
1516 for (auto &secondaryMix : secondaryMixes) {
1517 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1518 if (outputDesc != nullptr &&
1519 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1520 secondaryOutputs->push_back(outputDesc->mIoHandle);
1521 weakSecondaryOutputDescs.push_back(outputDesc);
1522 }
1523 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001524 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001525
Eric Laurent8fc147b2018-07-22 19:13:55 -07001526 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001527 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001528 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001529 };
jiabin4ef93452019-09-10 14:29:54 -07001530 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001531
Eric Laurentc209fe42020-06-05 18:11:23 -07001532 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001533 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001534 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001535 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001536 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001537 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001538 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001539 std::move(weakSecondaryOutputDescs),
1540 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001541 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001542
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001543 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1544 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001545
Eric Laurente83b55d2014-11-14 10:06:21 -08001546 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001547}
1548
Eric Laurentc529cf62020-04-17 18:19:10 -07001549status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1550 audio_session_t session,
1551 const audio_config_t *config,
1552 audio_output_flags_t flags,
1553 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001554 audio_io_handle_t *output,
1555 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001556
1557 *output = AUDIO_IO_HANDLE_NONE;
1558
1559 // skip direct output selection if the request can obviously be attached to a mixed output
1560 // and not explicitly requested
1561 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1562 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1563 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1564 return NAME_NOT_FOUND;
1565 }
1566
1567 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1568 // This prevents creating an offloaded track and tearing it down immediately after start
1569 // when audioflinger detects there is an active non offloadable effect.
1570 // FIXME: We should check the audio session here but we do not have it in this context.
1571 // This may prevent offloading in rare situations where effects are left active by apps
1572 // in the background.
1573 sp<IOProfile> profile;
1574 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1575 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1576 profile = getProfileForOutput(
1577 devices, config->sample_rate, config->format, config->channel_mask,
1578 flags, true /* directOnly */);
1579 }
1580
1581 if (profile == nullptr) {
1582 return NAME_NOT_FOUND;
1583 }
1584
1585 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1586 for (size_t i = 0; i < mOutputs.size(); i++) {
1587 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1588 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1589 // reuse direct output if currently open by the same client
1590 // and configured with same parameters
1591 if ((config->sample_rate == desc->getSamplingRate()) &&
1592 (config->format == desc->getFormat()) &&
1593 (config->channel_mask == desc->getChannelMask()) &&
1594 (session == desc->mDirectClientSession)) {
1595 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001596 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001597 mOutputs.keyAt(i), session);
1598 *output = mOutputs.keyAt(i);
1599 return NO_ERROR;
1600 }
1601 }
1602 }
1603
1604 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001605 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1606 return NAME_NOT_FOUND;
1607 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1608 // MMAP gracefully handles lack of an exclusive track resource by mixing
1609 // above the audio framework. For AAudio to know that the limit is reached,
1610 // return an error.
1611 return NAME_NOT_FOUND;
1612 } else {
1613 // Close outputs on this profile, if available, to free resources for this request
1614 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1615 const auto desc = mOutputs.valueAt(i);
1616 if (desc->mProfile == profile) {
1617 closeOutput(desc->mIoHandle);
1618 }
1619 }
1620 }
1621 }
1622
1623 // Unable to close streams to find free resources for this request
1624 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001625 return NAME_NOT_FOUND;
1626 }
1627
Atneya Nairb16666a2023-12-11 20:18:33 -08001628 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001629
Michael Chan6fb34492020-12-08 15:44:49 +11001630 // An MSD patch may be using the only output stream that can service this request. Release
1631 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001632 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001633
Eric Laurentf1f22e72021-07-13 14:04:14 +02001634 status_t status =
Haofan Wangf6e304f2024-07-09 23:06:58 -07001635 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output,
1636 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001637
1638 // only accept an output with the requested parameters
1639 if (status != NO_ERROR ||
1640 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1641 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1642 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1643 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1644 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1645 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1646 config->channel_mask, outputDesc->getChannelMask());
1647 if (*output != AUDIO_IO_HANDLE_NONE) {
1648 outputDesc->close();
1649 }
1650 // fall back to mixer output if possible when the direct output could not be open
1651 if (audio_is_linear_pcm(config->format) &&
1652 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1653 return NAME_NOT_FOUND;
1654 }
1655 *output = AUDIO_IO_HANDLE_NONE;
1656 return BAD_VALUE;
1657 }
1658 outputDesc->mDirectOpenCount = 1;
1659 outputDesc->mDirectClientSession = session;
1660
1661 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001662 setOutputDevices(__func__, outputDesc,
1663 devices,
1664 true,
1665 0,
1666 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001667 mPreviousOutputs = mOutputs;
1668 ALOGV("%s returns new direct output %d", __func__, *output);
1669 mpClientInterface->onAudioPortListUpdate();
1670 return NO_ERROR;
1671}
1672
François Gaffie11d30102018-11-02 16:09:09 +01001673audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1674 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001675 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001676 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001677 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001678 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001679 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001680 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001681 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001682{
Andy Hungc88b0642018-04-27 15:42:35 -07001683 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001684
jiabine375d412019-02-26 12:54:53 -08001685 // Discard haptic channel mask when forcing muting haptic channels.
1686 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001687 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1688 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001689
Eric Laurente552edb2014-03-10 17:42:56 -07001690 // open a direct output if required by specified parameters
1691 //force direct flag if offload flag is set: offloading implies a direct output stream
1692 // and all common behaviors are driven by checking only the direct flag
1693 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001694 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1695 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001696 }
Nadav Bar766fb022018-01-07 12:18:03 +02001697 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1698 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001699 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001700
1701 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1702
Eric Laurente83b55d2014-11-14 10:06:21 -08001703 // only allow deep buffering for music stream type
1704 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001705 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001706 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001707 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001708 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1709 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001710 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001711 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001712 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001713 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001714 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001715 audio_is_linear_pcm(config->format) &&
1716 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001717 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001718 AUDIO_OUTPUT_FLAG_DIRECT);
1719 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001720 }
Eric Laurente552edb2014-03-10 17:42:56 -07001721
Carter Hsua3abb402021-10-26 11:11:20 +08001722 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1723 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1724 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1725 }
1726
Eric Laurentf9230d52024-01-26 18:49:09 +01001727 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001728 // was specified and offload or direct playback is not explicitly requested, and there is no
1729 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001730 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001731 if (mSpatializerOutput != nullptr &&
1732 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1733 prefMixerConfigInfo == nullptr &&
1734 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1735 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001736 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001737 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001738 }
1739
Eric Laurentc529cf62020-04-17 18:19:10 -07001740 audio_config_t directConfig = *config;
1741 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001742
1743 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1744 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001745 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001746 return output;
1747 }
1748
Eric Laurent14cbfca2016-03-17 09:42:16 -07001749 // A request for HW A/V sync cannot fallback to a mixed output because time
1750 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001751 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001752 return AUDIO_IO_HANDLE_NONE;
1753 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001754 // A request for Tuner cannot fallback to a mixed output
1755 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1756 return AUDIO_IO_HANDLE_NONE;
1757 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001758
Eric Laurente552edb2014-03-10 17:42:56 -07001759 // ignoring channel mask due to downmix capability in mixer
1760
1761 // open a non direct output
1762
1763 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001764 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001765 // get which output is suitable for the specified stream. The actual
1766 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001767 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001768 if (prefMixerConfigInfo != nullptr) {
1769 for (audio_io_handle_t outputHandle : outputs) {
1770 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1771 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1772 output = outputHandle;
1773 break;
1774 }
1775 }
1776 if (output == AUDIO_IO_HANDLE_NONE) {
1777 // No output open with the preferred profile. Open a new one.
1778 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1779 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1780 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1781 config.format = prefMixerConfigInfo->getConfigBase().format;
1782 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1783 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1784 &config, prefMixerConfigInfo->getFlags());
1785 if (preferredOutput == nullptr) {
1786 ALOGE("%s failed to open output with preferred mixer config", __func__);
1787 } else {
1788 output = preferredOutput->mIoHandle;
1789 }
1790 }
1791 } else {
1792 // at this stage we should ignore the DIRECT flag as no direct output could be
1793 // found earlier
1794 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001795 if (com::android::media::audioserver::
1796 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1797 // If the preferred mixer attributes is null, do not select the bit-perfect output
1798 // unless the bit-perfect output is the only output.
1799 // The bit-perfect output can exist while the passed in preferred mixer attributes
1800 // info is null when it is a high priority client. The high priority clients are
1801 // ringtone or alarm, which is not a bit-perfect use case.
1802 size_t i = 0;
1803 while (i < outputs.size() && outputs.size() > 1) {
1804 auto desc = mOutputs.valueFor(outputs[i]);
1805 // The output descriptor must not be null here.
1806 if (desc->isBitPerfect()) {
1807 outputs.removeItemsAt(i);
1808 } else {
1809 i += 1;
1810 }
1811 }
1812 }
jiabina84c3d32022-12-02 18:59:55 +00001813 output = selectOutput(
1814 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1815 }
Eric Laurente552edb2014-03-10 17:42:56 -07001816 }
François Gaffie11d30102018-11-02 16:09:09 +01001817 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001818 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001819 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001820
Eric Laurente552edb2014-03-10 17:42:56 -07001821 return output;
1822}
1823
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001824sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001825 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1826 mAvailableInputDevices);
1827 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1828}
1829
1830DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1831 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1832 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001833}
1834
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001835const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001836 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001837 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1838 if (msdModule != 0) {
1839 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1840 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1841 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1842 const struct audio_port_config *source = &patch->mPatch.sources[j];
1843 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1844 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001845 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001846 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001847 }
1848 }
1849 }
1850 return msdPatches;
1851}
1852
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001853bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1854 ssize_t index = mAudioPatches.indexOfKey(handle);
1855 if (index < 0) {
1856 return false;
1857 }
1858 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1859 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1860 if (msdModule == nullptr) {
1861 return false;
1862 }
1863 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1864 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1865 return true;
1866 }
1867 index = getMsdOutputPatches().indexOfKey(handle);
1868 if (index < 0) {
1869 return false;
1870 }
1871 return true;
1872}
1873
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001874status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1875 const InputProfileCollection &inputProfiles,
1876 const OutputProfileCollection &outputProfiles,
1877 const sp<DeviceDescriptor> &sourceDevice,
1878 const sp<DeviceDescriptor> &sinkDevice,
1879 AudioProfileVector& sourceProfiles,
1880 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001881 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001882 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001883 return NO_INIT;
1884 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001885 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001886 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001887 return NO_INIT;
1888 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001889 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001890 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1891 inProfile->supportsDevice(sourceDevice)) {
1892 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001893 }
1894 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001895 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001896 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001897 outProfile->supportsDevice(sinkDevice)) {
1898 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001899 }
1900 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001901 return NO_ERROR;
1902}
1903
1904status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1905 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1906 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1907{
Dean Wheatley16809da2022-12-09 14:55:46 +11001908 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1909 static const std::vector<audio_format_t> formatsOrder = {{
1910 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001911 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1912 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001913 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1914 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1915 // preferred).
1916 std::vector<audio_channel_mask_t> masks = {{
1917 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1918 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1919 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1920 // insert index masks (higher counts most preferred) as preferred over position masks
1921 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1922 masks.insert(
1923 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1924 }
1925 return masks;
1926 }();
1927
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001928 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001929 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1930 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001931 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001932 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1933 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001934 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001935 }
1936 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1937 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1938 sinkConfig->format = bestSinkConfig.format;
1939 // For encoded streams force direct flag to prevent downstream mixing.
1940 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1941 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001942 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1943 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001944 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001945 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1946 // raw and IEC61937 framed streams.
1947 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1948 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1949 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001950 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1951 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001952 sourceConfig->channel_mask =
1953 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1954 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1955 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001956 sourceConfig->format = bestSinkConfig.format;
1957 // Copy input stream directly without any processing (e.g. resampling).
1958 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1959 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1960 if (hwAvSync) {
1961 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1962 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1963 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1964 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1965 }
1966 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1967 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1968 sinkConfig->config_mask |= config_mask;
1969 sourceConfig->config_mask |= config_mask;
1970 return NO_ERROR;
1971}
1972
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001973PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1974 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001975{
1976 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001977 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1978 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1979 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1980 if (deviceModule == nullptr) {
1981 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1982 return patchBuilder;
1983 }
1984 const InputProfileCollection inputProfiles = msdIsSource ?
1985 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1986 const OutputProfileCollection outputProfiles = msdIsSource ?
1987 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1988
1989 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1990 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1991 device : getMsdAudioOutDevices().itemAt(0);
1992 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1993
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001994 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1995 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001996 AudioProfileVector sourceProfiles;
1997 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001998 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1999 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002000 for (auto hwAvSync : { true, false }) {
2001 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2002 sourceProfiles, sinkProfiles) != NO_ERROR) {
2003 continue;
2004 }
2005 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2006 &sinkConfig) == NO_ERROR) {
2007 // Found a matching config. Re-create PatchBuilder with this config.
2008 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2009 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002010 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002011 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002012 " supporting PCM format conversion.", __func__);
2013 return patchBuilder;
2014}
2015
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002016status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002017 DeviceVector devices;
2018 if (outputDevices != nullptr && outputDevices->size() > 0) {
2019 devices.add(*outputDevices);
2020 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002021 // Use media strategy for unspecified output device. This should only
2022 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2023 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002024 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002025 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002026 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002027 }
Michael Chan6fb34492020-12-08 15:44:49 +11002028 std::vector<PatchBuilder> patchesToCreate;
2029 for (auto i = 0u; i < devices.size(); ++i) {
2030 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002031 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002032 }
2033 // Retain only the MSD patches associated with outputDevices request.
2034 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002035 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002036 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2037 auto retainedPatch = false;
2038 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2039 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2040 patchesToRemove.removeItemsAt(i);
2041 retainedPatch = true;
2042 break;
2043 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002044 }
Michael Chan6fb34492020-12-08 15:44:49 +11002045 if (retainedPatch) {
2046 it = patchesToCreate.erase(it);
2047 continue;
2048 }
2049 ++it;
2050 }
2051 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2052 return NO_ERROR;
2053 }
2054 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2055 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002056 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002057 }
Michael Chan6fb34492020-12-08 15:44:49 +11002058 status_t status = NO_ERROR;
2059 for (const auto &p : patchesToCreate) {
2060 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2061 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2062 char message[256];
2063 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2064 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2065 currStatus == NO_ERROR ? "Success" : "Error",
2066 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2067 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2068 if (currStatus == NO_ERROR) {
2069 ALOGD("%s", message);
2070 } else {
2071 ALOGE("%s", message);
2072 if (status == NO_ERROR) {
2073 status = currStatus;
2074 }
2075 }
2076 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002077 return status;
2078}
2079
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002080void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2081 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002082 for (size_t i = 0; i < msdPatches.size(); i++) {
2083 const auto& patch = msdPatches[i];
2084 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2085 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2086 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2087 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2088 releaseAudioPatch(patch->getHandle(), mUidCached);
2089 break;
2090 }
2091 }
2092 }
2093}
2094
Dorin Drimus94d94412022-02-02 09:05:02 +01002095bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002096 DeviceVector devicesToCheck =
2097 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002098 AudioPatchCollection msdPatches = getMsdOutputPatches();
2099 for (size_t i = 0; i < msdPatches.size(); i++) {
2100 const auto& patch = msdPatches[i];
2101 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2102 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2103 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2104 const auto& foundDevice = devicesToCheck.getDevice(
2105 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2106 if (foundDevice != nullptr) {
2107 devicesToCheck.remove(foundDevice);
2108 if (devicesToCheck.isEmpty()) {
2109 return true;
2110 }
2111 }
2112 }
2113 }
2114 }
2115 return false;
2116}
2117
Eric Laurente0720872014-03-11 09:30:41 -07002118audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002119 audio_output_flags_t flags,
2120 audio_format_t format,
2121 audio_channel_mask_t channelMask,
2122 uint32_t samplingRate,
2123 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002124{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002125 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2126 "%s called with format %#x", __func__, format);
2127
jiabinebb6af42020-06-09 17:31:17 -07002128 // Return the output that haptic-generating attached to when 1) session id is specified,
2129 // 2) haptic-generating effect exists for given session id and 3) the output that
2130 // haptic-generating effect attached to is in given outputs.
2131 if (sessionId != AUDIO_SESSION_NONE) {
2132 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2133 sessionId, FX_IID_HAPTICGENERATOR);
2134 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2135 return hapticGeneratingOutput;
2136 }
2137 }
2138
Eric Laurent16c66dd2019-05-01 17:54:10 -07002139 // Flags disqualifying an output: the match must happen before calling selectOutput()
2140 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2141 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2142
2143 // Flags expressing a functional request: must be honored in priority over
2144 // other criteria
2145 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2146 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002147 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2148 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002149 // Flags expressing a performance request: have lower priority than serving
2150 // requested sampling rate or channel mask
2151 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2152 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2153 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2154
2155 const audio_output_flags_t functionalFlags =
2156 (audio_output_flags_t)(flags & kFunctionalFlags);
2157 const audio_output_flags_t performanceFlags =
2158 (audio_output_flags_t)(flags & kPerformanceFlags);
2159
2160 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2161
Eric Laurente552edb2014-03-10 17:42:56 -07002162 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002163 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002164 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002165 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002166 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002167 // with tiebreak preferring the minimum number of extra functional flags
2168 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002169 // 3: the output supporting the exact channel mask
2170 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002171 // 5: the output with the highest sampling rate if the requested sample rate is
2172 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002173 // 6: the output with the highest number of requested performance flags
2174 // 7: the output with the bit depth the closest to the requested one
2175 // 8: the primary output
2176 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002177
Eric Laurent16c66dd2019-05-01 17:54:10 -07002178 // matching criteria values in priority order for best matching output so far
2179 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002180
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002181 const bool hasOrphanHaptic =
2182 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002183 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2184 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2185 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002186
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002187 for (audio_io_handle_t output : outputs) {
2188 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002189 // matching criteria values in priority order for current output
2190 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002191
Eric Laurent16c66dd2019-05-01 17:54:10 -07002192 if (outputDesc->isDuplicated()) {
2193 continue;
2194 }
2195 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2196 continue;
2197 }
Eric Laurent8838a382014-09-08 16:44:28 -07002198
Eric Laurent16c66dd2019-05-01 17:54:10 -07002199 // If haptic channel is specified, use the haptic output if present.
2200 // When using haptic output, same audio format and sample rate are required.
2201 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002202 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002203 // skip if haptic channel specified but output does not support it, or output support haptic
2204 // but there is no haptic channel requested AND no orphan haptic effect exist
2205 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2206 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002207 continue;
2208 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002209 // In the case of audio-coupled-haptic playback, there is no format conversion and
2210 // resampling in the framework, same format/channel/sampleRate for client and the output
2211 // thread is required. In the case of HapticGenerator effect, do not require format
2212 // matching.
2213 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2214 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002215 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002216 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002217 }
2218
2219 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002220 const int matchingFunctionalFlags =
2221 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2222 const int totalFunctionalFlags =
2223 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2224 // Prefer matching functional flags, but subtract unnecessary functional flags.
2225 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002226
2227 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002228 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2229 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002230 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2231 channelCount <= outputChannelCount) {
2232 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002233 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2234 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002235 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002236 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002237 currentMatchCriteria[3] = outputChannelCount;
2238 }
2239
2240 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002241 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002242 int diff; // avoid unsigned integer overflow.
2243 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2244
2245 // prefer the closest output sampling rate greater than or equal to target
2246 // if none exists, prefer the closest output sampling rate less than target.
2247 //
2248 // criteria is offset to make non-negative.
2249 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002250 }
2251
2252 // performance flags match
2253 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2254
2255 // format match
2256 if (format != AUDIO_FORMAT_INVALID) {
2257 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002258 PolicyAudioPort::kFormatDistanceMax -
2259 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002260 }
2261
2262 // primary output match
2263 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2264
2265 // compare match criteria by priority then value
2266 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2267 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2268 bestMatchCriteria = currentMatchCriteria;
2269 bestOutput = output;
2270
2271 std::stringstream result;
2272 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2273 std::ostream_iterator<int>(result, " "));
2274 ALOGV("%s new bestOutput %d criteria %s",
2275 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002276 }
2277 }
2278
Eric Laurent16c66dd2019-05-01 17:54:10 -07002279 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002280}
2281
Eric Laurent8fc147b2018-07-22 19:13:55 -07002282status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002283{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002284 ALOGV("%s portId %d", __FUNCTION__, portId);
2285
2286 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2287 if (outputDesc == 0) {
2288 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002289 return BAD_VALUE;
2290 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002291 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002292
Eric Laurent8fc147b2018-07-22 19:13:55 -07002293 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002294 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002295
jiabin220eea12024-05-17 17:55:20 +00002296 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2297 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2298 && outputDesc->isBitPerfect()) {
2299 // Usually, APM selects bit-perfect output for high priority use cases only when
2300 // bit-perfect output is the only output that can be routed to the selected device.
2301 // However, here is no need to play high priority use cases such as ringtone and alarm
2302 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2303 // can attach to new output.
2304 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2305 __func__, client->stream());
2306 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2307 return DEAD_OBJECT;
2308 }
2309
Eric Laurent733ce942017-12-07 12:18:25 -08002310 status_t status = outputDesc->start();
2311 if (status != NO_ERROR) {
2312 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002313 }
2314
Eric Laurent97ac8712018-07-27 18:59:02 -07002315 uint32_t delayMs;
2316 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002317
2318 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002319 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002320 if (status == DEAD_OBJECT) {
2321 sp<SwAudioOutputDescriptor> desc =
2322 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2323 if (desc == nullptr) {
2324 // This is not common, it may indicate something wrong with the HAL.
2325 ALOGE("%s unable to open output with default config", __func__);
2326 return status;
2327 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002328 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002329 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002330 }
jiabina84c3d32022-12-02 18:59:55 +00002331
2332 // If the client is the first one active on preferred mixer parameters, reopen the output
2333 // if the current mixer parameters doesn't match the preferred one.
2334 if (outputDesc->devices().size() == 1) {
2335 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2336 outputDesc->devices()[0]->getId(), client->strategy());
2337 if (info != nullptr && info->getUid() == client->uid()) {
2338 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2339 info->getConfigBase(), info->getFlags())) {
2340 stopSource(outputDesc, client);
2341 outputDesc->stop();
2342 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2343 config.channel_mask = info->getConfigBase().channel_mask;
2344 config.sample_rate = info->getConfigBase().sample_rate;
2345 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002346 sp<SwAudioOutputDescriptor> desc =
2347 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2348 if (desc == nullptr) {
2349 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002350 }
jiabin220eea12024-05-17 17:55:20 +00002351 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002352 // Intentionally return error to let the client side resending request for
2353 // creating and starting.
2354 return DEAD_OBJECT;
2355 }
2356 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002357 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002358 // If it is first bit-perfect client, reroute all clients that will be routed to
2359 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2360 PortHandleVector clientsToInvalidate;
2361 for (size_t i = 0; i < mOutputs.size(); i++) {
2362 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002363 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002364 continue;
2365 }
2366 for (const auto& c : mOutputs[i]->getClientIterable()) {
2367 clientsToInvalidate.push_back(c->portId());
2368 }
2369 }
2370 if (!clientsToInvalidate.empty()) {
2371 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2372 __func__);
2373 mpClientInterface->invalidateTracks(clientsToInvalidate);
2374 }
2375 }
jiabina84c3d32022-12-02 18:59:55 +00002376 }
2377 }
2378
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002379 if (client->hasPreferredDevice()) {
2380 // playback activity with preferred device impacts routing occurred, inform upper layers
2381 mpClientInterface->onRoutingUpdated();
2382 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002383 if (delayMs != 0) {
2384 usleep(delayMs * 1000);
2385 }
2386
jiabin220eea12024-05-17 17:55:20 +00002387 if (status == NO_ERROR &&
2388 outputDesc->mPreferredAttrInfo != nullptr &&
2389 outputDesc->isBitPerfect() &&
2390 com::android::media::audioserver::
2391 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2392 // A new client is started on bit-perfect output, update all clients internal mute.
2393 updateClientsInternalMute(outputDesc);
2394 }
2395
Eric Laurentc75307b2015-03-17 15:29:32 -07002396 return status;
2397}
2398
Eric Laurent96d1dda2022-03-14 17:14:19 +01002399bool AudioPolicyManager::isLeUnicastActive() const {
2400 if (isInCall()) {
2401 return true;
2402 }
2403 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2404}
2405
2406bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2407 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2408 return false;
2409 }
2410 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2411 ALOGV("%s active %d", __func__, active);
2412 return active;
2413}
2414
Eric Laurent97ac8712018-07-27 18:59:02 -07002415status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2416 const sp<TrackClientDescriptor>& client,
2417 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002418{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002419 // cannot start playback of STREAM_TTS if any other output is being used
2420 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002421
2422 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002423 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002424 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002425 auto clientStrategy = client->strategy();
2426 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002427 if (stream == AUDIO_STREAM_TTS) {
2428 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002429 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002430 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002431 return INVALID_OPERATION;
2432 } else {
2433 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2434 }
2435 } else {
2436 // some playback other than beacon starts
2437 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2438 }
2439
Eric Laurent77305a62016-07-25 16:39:22 -07002440 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002441 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002442 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002443
François Gaffie11d30102018-11-02 16:09:09 +01002444 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002445 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002446 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002447 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002448 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002449 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002450 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002451 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002452 } else {
2453 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002454 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002455 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2456 AUDIO_FORMAT_DEFAULT);
2457 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2458 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002459 }
2460
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002461 // requiresMuteCheck is false when we can bypass mute strategy.
2462 // It covers a common case when there is no materially active audio
2463 // and muting would result in unnecessary delay and dropped audio.
2464 const uint32_t outputLatencyMs = outputDesc->latency();
2465 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002466 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002467
Eric Laurente552edb2014-03-10 17:42:56 -07002468 // increment usage count for this stream on the requested output:
2469 // NOTE that the usage count is the same for duplicated output and hardware output which is
2470 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002471 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002472
2473 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002474 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002475 // Preferred device may be exclusive, use only if no other active clients on this output
2476 devices = DeviceVector(
2477 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2478 } else {
2479 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2480 }
François Gaffie11d30102018-11-02 16:09:09 +01002481 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002482 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002483 }
2484 }
Eric Laurente552edb2014-03-10 17:42:56 -07002485
François Gaffiec005e562018-11-06 15:04:49 +01002486 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002487 selectOutputForMusicEffects();
2488 }
2489
François Gaffie1c878552018-11-22 16:53:21 +01002490 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002491 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002492 if (devices.isEmpty()) {
2493 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002494 }
François Gaffiec005e562018-11-06 15:04:49 +01002495 bool shouldWait =
2496 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2497 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2498 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002499 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002500 const bool needToCloseBitPerfectOutput =
2501 (com::android::media::audioserver::
2502 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2503 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2504 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002505 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002506 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002507 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002508 // An output has a shared device if
2509 // - managed by the same hw module
2510 // - supports the currently selected device
2511 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002512 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002513
Eric Laurent77305a62016-07-25 16:39:22 -07002514 // force a device change if any other output is:
2515 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002516 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002517 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002518 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002519 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002520 // change the device currently selected by the other output.
2521 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002522 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002523 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002524 force = true;
2525 }
2526 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002527 // a notification so that audio focus effect can propagate, or that a mute/unmute
2528 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002529 const uint32_t latencyMs = desc->latency();
2530 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2531
2532 if (shouldWait && isActive && (waitMs < latencyMs)) {
2533 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002534 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002535
2536 // Require mute check if another output is on a shared device
2537 // and currently active to have proper drain and avoid pops.
2538 // Note restoring AudioTracks onto this output needs to invoke
2539 // a volume ramp if there is no mute.
2540 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002541
2542 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2543 outputsToReopen.push_back(desc);
2544 }
Eric Laurente552edb2014-03-10 17:42:56 -07002545 }
2546 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002547
jiabin220eea12024-05-17 17:55:20 +00002548 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002549 // If the output is open with preferred mixer attributes, but the routed device is
2550 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2551 // changed.
2552 return DEAD_OBJECT;
2553 }
jiabin220eea12024-05-17 17:55:20 +00002554 for (auto& outputToReopen : outputsToReopen) {
2555 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2556 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002557 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302558 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2559 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002560
Eric Laurente552edb2014-03-10 17:42:56 -07002561 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002562 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002563 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002564 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002565 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002566 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002567 outputDesc->useHwGain() /*force*/)) {
2568 // request AudioService to reinitialize the volume curves asynchronously
2569 ALOGE("checkAndSetVolume failed, requesting volume range init");
2570 mpClientInterface->onVolumeRangeInitRequest();
2571 };
Eric Laurente552edb2014-03-10 17:42:56 -07002572
2573 // update the outputs if starting an output with a stream that can affect notification
2574 // routing
2575 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002576
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002577 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002578 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002579 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002580 }
Eric Laurentdc462862016-07-19 12:29:53 -07002581
2582 if (waitMs > muteWaitMs) {
2583 *delayMs = waitMs - muteWaitMs;
2584 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002585
2586 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2587 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2588 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2589 // change occurs after the MixerThread starts and causes a stream volume
2590 // glitch.
2591 //
2592 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002593 }
Eric Laurentdc462862016-07-19 12:29:53 -07002594
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002595 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002596 mEngine->getForceUse(
2597 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002598 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002599 }
2600
Eric Laurent97ac8712018-07-27 18:59:02 -07002601 // Automatically enable the remote submix input when output is started on a re routing mix
2602 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002603 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2604 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002605 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2606 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2607 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002608 "remote-submix",
2609 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002610 }
2611
Eric Laurent96d1dda2022-03-14 17:14:19 +01002612 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2613
Eric Laurente552edb2014-03-10 17:42:56 -07002614 return NO_ERROR;
2615}
2616
Eric Laurent96d1dda2022-03-14 17:14:19 +01002617void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2618 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2619 bool isUnicastActive = isLeUnicastActive();
2620
2621 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002622 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002623 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2624 for (size_t i = 0; i < mOutputs.size(); i++) {
2625 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2626 if (desc != ignoredOutput && desc->isActive()
2627 && ((isUnicastActive &&
2628 !desc->devices().
2629 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2630 || (wasUnicastActive &&
2631 !desc->devices().getDevicesFromTypes(
2632 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2633 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2634 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002635 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002636 // If the device is using preferred mixer attributes, the output need to reopen
2637 // with default configuration when the new selected devices are different from
2638 // current routing devices.
2639 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2640 continue;
2641 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302642 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002643 // re-apply device specific volume if not done by setOutputDevice()
2644 if (!force) {
2645 applyStreamVolumes(desc, newDevices.types(), delayMs);
2646 }
2647 }
2648 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002649 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002650 }
2651}
2652
Eric Laurent8fc147b2018-07-22 19:13:55 -07002653status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002654{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002655 ALOGV("%s portId %d", __FUNCTION__, portId);
2656
2657 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2658 if (outputDesc == 0) {
2659 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002660 return BAD_VALUE;
2661 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002662 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002663
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002664 if (client->hasPreferredDevice(true)) {
2665 // playback activity with preferred device impacts routing occurred, inform upper layers
2666 mpClientInterface->onRoutingUpdated();
2667 }
2668
Eric Laurent97ac8712018-07-27 18:59:02 -07002669 ALOGV("stopOutput() output %d, stream %d, session %d",
2670 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002671
Eric Laurent97ac8712018-07-27 18:59:02 -07002672 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002673
Eric Laurent733ce942017-12-07 12:18:25 -08002674 if (status == NO_ERROR ) {
2675 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002676 } else {
2677 return status;
2678 }
2679
2680 if (outputDesc->devices().size() == 1) {
2681 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2682 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002683 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002684 if (info != nullptr && info->getUid() == client->uid()) {
2685 info->decreaseActiveClient();
2686 if (info->getActiveClientCount() == 0) {
2687 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002688 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002689 }
2690 }
jiabin220eea12024-05-17 17:55:20 +00002691 if (com::android::media::audioserver::
2692 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2693 !outputReopened && outputDesc->isBitPerfect()) {
2694 // Only need to update the clients' internal mute when the output is bit-perfect and it
2695 // is not reopened.
2696 updateClientsInternalMute(outputDesc);
2697 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002698 }
2699 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002700}
2701
Eric Laurent97ac8712018-07-27 18:59:02 -07002702status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2703 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002704{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002705 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002706 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002707 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002708 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002709
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002710 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2711
François Gaffie1c878552018-11-22 16:53:21 +01002712 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2713 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002714 // Automatically disable the remote submix input when output is stopped on a
2715 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002716 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002717 if (isSingleDeviceType(
2718 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002719 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002720 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002721 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2722 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002723 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002724 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002725 }
2726 }
2727 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002728 if (client->hasPreferredDevice(true) &&
2729 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002730 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002731 forceDeviceUpdate = true;
2732 }
2733
Eric Laurente552edb2014-03-10 17:42:56 -07002734 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002735 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002736
Eric Laurente552edb2014-03-10 17:42:56 -07002737 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002738 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002739 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002740 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002741
2742 // If the routing does not change, if an output is routed on a device using HwGain
2743 // (aka setAudioPortConfig) and there are still active clients following different
2744 // volume group(s), force reapply volume
2745 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2746 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2747
Eric Laurente552edb2014-03-10 17:42:56 -07002748 // delay the device switch by twice the latency because stopOutput() is executed when
2749 // the track stop() command is received and at that time the audio track buffer can
2750 // still contain data that needs to be drained. The latency only covers the audio HAL
2751 // and kernel buffers. Also the latency does not always include additional delay in the
2752 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302753 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002754 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002755
2756 // force restoring the device selection on other active outputs if it differs from the
2757 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002758 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002759 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002760 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002761 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002762 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002763 desc->isActive() &&
2764 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002765 (newDevices != desc->devices())) {
2766 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2767 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002768
jiabin220eea12024-05-17 17:55:20 +00002769 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002770 // If the device is using preferred mixer attributes, the output need to
2771 // reopen with default configuration when the new selected devices are
2772 // different from current routing devices.
2773 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2774 continue;
2775 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302776 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002777
Eric Laurent57de36c2016-09-28 16:59:11 -07002778 // re-apply device specific volume if not done by setOutputDevice()
2779 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002780 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002781 }
Eric Laurente552edb2014-03-10 17:42:56 -07002782 }
2783 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002784 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002785 // update the outputs if stopping one with a stream that can affect notification routing
2786 handleNotificationRoutingForStream(stream);
2787 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002788
2789 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2790 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002791 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002792 }
2793
François Gaffiec005e562018-11-06 15:04:49 +01002794 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002795 selectOutputForMusicEffects();
2796 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002797
2798 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2799
Eric Laurente552edb2014-03-10 17:42:56 -07002800 return NO_ERROR;
2801 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002802 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002803 return INVALID_OPERATION;
2804 }
2805}
2806
jiabinbce0c1d2020-10-05 11:20:18 -07002807bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002808{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002809 ALOGV("%s portId %d", __FUNCTION__, portId);
2810
2811 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2812 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002813 // If an output descriptor is closed due to a device routing change,
2814 // then there are race conditions with releaseOutput from tracks
2815 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2816 // destroyed shortly thereafter.
2817 //
2818 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002819 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002820 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002821 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002822
2823 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002824
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302825 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2826 if (outputDesc->isClientActive(client)) {
2827 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2828 stopOutput(portId);
2829 }
2830
Eric Laurent8fc147b2018-07-22 19:13:55 -07002831 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2832 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002833 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002834 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002835 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002836 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002837 if (--outputDesc->mDirectOpenCount == 0) {
2838 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002839 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002840 }
2841 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302842
Andy Hung39efb7a2018-09-26 15:39:28 -07002843 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002844 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2845 // The output is pending reopened to query dynamic profiles and
2846 // there is no active clients
2847 closeOutput(outputDesc->mIoHandle);
2848 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2849 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2850 if (newOutputDesc == nullptr) {
2851 ALOGE("%s failed to open output", __func__);
2852 }
2853 return true;
2854 }
2855 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002856}
2857
Eric Laurentcaf7f482014-11-25 17:50:47 -08002858status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2859 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002860 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002861 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002862 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002863 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002864 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002865 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002866 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002867 audio_port_handle_t *portId,
2868 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002869{
François Gaffiec005e562018-11-06 15:04:49 +01002870 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002871 "flags %#x attributes=%s requested device ID %d",
2872 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2873 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002874
Eric Laurentad2e7b92017-09-14 20:06:42 -07002875 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002876 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002877 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002878 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002879 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002880 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002881 sp<RecordClientDescriptor> clientDesc;
2882 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002883 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002884 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002885
2886 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2887 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2888 return INVALID_OPERATION;
2889 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002890
Francois Gaffie716e1432019-01-14 16:58:59 +01002891 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2892 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002893 }
2894
Paul McLean466dc8e2015-04-17 13:15:36 -06002895 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002896 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002897 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002898
Eric Laurentad2e7b92017-09-14 20:06:42 -07002899 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2900 // possible
2901 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2902 *input != AUDIO_IO_HANDLE_NONE) {
2903 ssize_t index = mInputs.indexOfKey(*input);
2904 if (index < 0) {
2905 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2906 status = BAD_VALUE;
2907 goto error;
2908 }
2909 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002910 RecordClientVector clients = inputDesc->getClientsForSession(session);
2911 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002912 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2913 status = BAD_VALUE;
2914 goto error;
2915 }
2916 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2917 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002918 // corresponds to a new client and is only permitted from the same UID.
2919 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002920 if (clients.size() > 1) {
2921 for (const auto& client : clients) {
2922 // The client map is ordered by key values (portId) and portIds are allocated
2923 // incrementaly. So the first client in this list is the one opened by audio flinger
2924 // when the mmap stream is created and should be ignored as it does not correspond
2925 // to an actual client
2926 if (client == *clients.cbegin()) {
2927 continue;
2928 }
2929 if (uid != client->uid() && !client->isSilenced()) {
2930 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2931 uid, client->portId(), client->uid());
2932 status = INVALID_OPERATION;
2933 goto error;
2934 }
Eric Laurent331679c2018-04-16 17:03:16 -07002935 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002936 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002937 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002938 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002939
Eric Laurentfecbceb2021-02-09 14:46:43 +01002940 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002941 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002942 }
2943
2944 *input = AUDIO_IO_HANDLE_NONE;
2945 *inputType = API_INPUT_INVALID;
2946
Francois Gaffie716e1432019-01-14 16:58:59 +01002947 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002948 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002949 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002950 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002951 ALOGW("%s could not find input mix for attr %s",
2952 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002953 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002954 }
jiabinc1de2df2019-05-07 14:26:40 -07002955 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2956 String8(attr->tags + strlen("addr=")),
2957 AUDIO_FORMAT_DEFAULT);
2958 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002959 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002960 __func__, attributes.source, attributes.tags);
2961 status = BAD_VALUE;
2962 goto error;
2963 }
2964
Kevin Rocard25f9b052019-02-27 15:08:54 -08002965 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2966 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2967 } else {
2968 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2969 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002970 if (virtualDeviceId) {
2971 *virtualDeviceId = policyMix->mVirtualDeviceId;
2972 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002973 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002974 if (explicitRoutingDevice != nullptr) {
2975 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002976 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002977 // Prevent from storing invalid requested device id in clients
2978 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002979 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002980 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2981 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002982 }
François Gaffie11d30102018-11-02 16:09:09 +01002983 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002984 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002985 status = BAD_VALUE;
2986 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002987 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002988 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2989 *inputType = API_INPUT_MIX_CAPTURE;
2990 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002991 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2992 // there is an external policy, but this input is attached to a mix of recorders,
2993 // meaning it receives audio injected into the framework, so the recorder doesn't
2994 // know about it and is therefore considered "legacy"
2995 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002996
2997 if (virtualDeviceId) {
2998 *virtualDeviceId = policyMix->mVirtualDeviceId;
2999 }
François Gaffie11d30102018-11-02 16:09:09 +01003000 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003001 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003002 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003003 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003004 } else {
3005 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003006 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003007
Eric Laurent599c7582015-12-07 18:05:55 -08003008 }
3009
François Gaffiec005e562018-11-06 15:04:49 +01003010 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003011 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003012 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003013 AudioProfileVector profiles;
3014 status_t ret = getProfilesForDevices(
3015 DeviceVector(device), profiles, flags, true /*isInput*/);
3016 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003017 const auto channels = profiles[0]->getChannels();
3018 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3019 config->channel_mask = *channels.begin();
3020 }
3021 const auto sampleRates = profiles[0]->getSampleRates();
3022 if (!sampleRates.empty() &&
3023 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3024 config->sample_rate = *sampleRates.begin();
3025 }
jiabinf1c73972022-04-14 16:28:52 -07003026 config->format = profiles[0]->getFormat();
3027 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003028 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003029 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003030
Marvin Ramine5a122d2023-12-07 13:57:59 +01003031
3032 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3033 *virtualDeviceId = policyMix->mVirtualDeviceId;
3034 }
3035
Eric Laurent8f42ea12018-08-08 09:08:25 -07003036exit:
3037
François Gaffiec005e562018-11-06 15:04:49 +01003038 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3039 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003040
Francois Gaffie716e1432019-01-14 16:58:59 +01003041 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003042 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003043 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003044
Mikhail Naganov2996f672019-04-18 12:29:59 -07003045 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003046 requestedDeviceId, attributes.source, flags,
3047 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003048 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003049 // Move (if found) effect for the client session to its input
3050 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003051 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003052
3053 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3054 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003055
Eric Laurent599c7582015-12-07 18:05:55 -08003056 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003057
3058error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003059 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003060}
3061
3062
François Gaffie11d30102018-11-02 16:09:09 +01003063audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003064 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003065 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003066 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003067 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003068 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003069{
3070 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003071 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003072 bool isSoundTrigger = false;
3073
François Gaffiec005e562018-11-06 15:04:49 +01003074 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003075 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3076 if (index >= 0) {
3077 input = mSoundTriggerSessions.valueFor(session);
3078 isSoundTrigger = true;
3079 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3080 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3081 } else {
3082 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003083 }
François Gaffiec005e562018-11-06 15:04:49 +01003084 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003085 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003086 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003087 }
3088
Carter Hsua3abb402021-10-26 11:11:20 +08003089 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3090 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3091 }
3092
Eric Laurentfe231122017-11-17 17:48:06 -08003093 // sampling rate and flags may be updated by getInputProfile
3094 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3095 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003096 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003097 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003098 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003099 // find a compatible input profile (not necessarily identical in parameters)
3100 sp<IOProfile> profile = getInputProfile(
3101 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3102 if (profile == nullptr) {
3103 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003104 }
jiabin2fd710d2022-05-02 23:20:22 +00003105
Glenn Kasten05ddca52016-02-11 08:17:12 -08003106 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003107 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003108 if (samplingRate == 0) {
3109 samplingRate = profileSamplingRate;
3110 }
Eric Laurente552edb2014-03-10 17:42:56 -07003111
Eric Laurent322b4d22015-04-03 15:57:54 -07003112 if (profile->getModuleHandle() == 0) {
3113 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003114 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003115 }
3116
Eric Laurentec376dc2021-04-08 20:41:22 +02003117 // Reuse an already opened input if a client with the same session ID already exists
3118 // on that input
3119 for (size_t i = 0; i < mInputs.size(); i++) {
3120 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3121 if (desc->mProfile != profile) {
3122 continue;
3123 }
3124 RecordClientVector clients = desc->clientsList();
3125 for (const auto &client : clients) {
3126 if (session == client->session()) {
3127 return desc->mIoHandle;
3128 }
3129 }
3130 }
3131
Eric Laurentc71b11b2024-06-03 12:54:53 +00003132 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003133 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003134 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3135 // First pick best candidate for preemption (there may not be any):
3136 // - Preempt and input if:
3137 // - It has only strictly lower priority use cases than the new client
3138 // - It has equal priority use cases than the new client, was not
3139 // opened thanks to preemption or has been active since opened.
3140 // - Order the preemption candidates by inactive first and priority second
3141 sp<AudioInputDescriptor> closeCandidate;
3142 int leastCloseRank = INT_MAX;
3143 static const int sCloseActive = 0x100;
3144
3145 for (size_t i = 0; i < mInputs.size(); i++) {
3146 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3147 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003148 continue;
3149 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003150 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3151 if (topPrioClient == nullptr) {
3152 continue;
3153 }
3154 int topPrio = source_priority(topPrioClient->source());
3155 if (topPrio < source_priority(attributes.source)
3156 || (topPrio == source_priority(attributes.source)
3157 && !desc->isPreemptor())) {
3158 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3159 if (closeRank < leastCloseRank) {
3160 leastCloseRank = closeRank;
3161 closeCandidate = desc;
3162 }
3163 }
3164 }
3165
3166 if (closeCandidate != nullptr) {
3167 closeInput(closeCandidate->mIoHandle);
3168 // Mark the new input as being issued from a preemption
3169 // so that is will not be preempted later
3170 isPreemptor = true;
3171 } else {
3172 // Then pick the best reusable input (There is always one)
3173 // The order of preference is:
3174 // 1) active inputs with same use case as the new client
3175 // 2) inactive inputs with same use case
3176 // 3) active inputs with different use cases
3177 // 4) inactive inputs with different use cases
3178 sp<AudioInputDescriptor> reuseCandidate;
3179 int leastReuseRank = INT_MAX;
3180 static const int sReuseDifferentUseCase = 0x100;
3181
3182 for (size_t i = 0; i < mInputs.size(); i++) {
3183 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3184 if (desc->mProfile != profile) {
3185 continue;
3186 }
3187 int reuseRank = sReuseDifferentUseCase;
3188 for (const auto& client: desc->getClientIterable()) {
3189 if (client->source() == attributes.source) {
3190 reuseRank = 0;
3191 break;
3192 }
3193 }
3194 reuseRank += desc->isActive() ? 0 : 1;
3195 if (reuseRank < leastReuseRank) {
3196 leastReuseRank = reuseRank;
3197 reuseCandidate = desc;
3198 }
3199 }
3200 return reuseCandidate->mIoHandle;
3201 }
3202 } else { // fix_input_sharing_logic()
3203 for (size_t i = 0; i < mInputs.size(); ) {
3204 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3205 if (desc->mProfile != profile) {
3206 i++;
3207 continue;
3208 }
3209 // if sound trigger, reuse input if used by other sound trigger on same session
3210 // else
3211 // reuse input if active client app is not in IDLE state
3212 //
3213 RecordClientVector clients = desc->clientsList();
3214 bool doClose = false;
3215 for (const auto& client : clients) {
3216 if (isSoundTrigger != client->isSoundTrigger()) {
3217 continue;
3218 }
3219 if (client->isSoundTrigger()) {
3220 if (session == client->session()) {
3221 return desc->mIoHandle;
3222 }
3223 continue;
3224 }
3225 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003226 return desc->mIoHandle;
3227 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003228 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003229 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003230 if (doClose) {
3231 closeInput(desc->mIoHandle);
3232 } else {
3233 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003234 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003235 }
3236 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003237 }
3238
Eric Laurentc71b11b2024-06-03 12:54:53 +00003239 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3240 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003241
Eric Laurentfe231122017-11-17 17:48:06 -08003242 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3243 lConfig.sample_rate = profileSamplingRate;
3244 lConfig.channel_mask = profileChannelMask;
3245 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003246
François Gaffie11d30102018-11-02 16:09:09 +01003247 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003248
3249 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003250 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003251 (profileSamplingRate != lConfig.sample_rate) ||
3252 !audio_formats_match(profileFormat, lConfig.format) ||
3253 (profileChannelMask != lConfig.channel_mask)) {
3254 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003255 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003256 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003257 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003258 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003259 }
Eric Laurent599c7582015-12-07 18:05:55 -08003260 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003261 }
3262
Eric Laurentc722f302014-12-10 11:21:49 -08003263 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003264
Eric Laurent599c7582015-12-07 18:05:55 -08003265 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003266 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003267
Eric Laurent599c7582015-12-07 18:05:55 -08003268 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003269}
3270
Eric Laurent4eb58f12018-12-07 16:41:02 -08003271status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003272{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003273 ALOGV("%s portId %d", __FUNCTION__, portId);
3274
3275 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3276 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003277 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003278 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003279 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003280 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003281 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003282 if (client->active()) {
3283 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3284 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003285 }
3286
Eric Laurent8f42ea12018-08-08 09:08:25 -07003287 audio_session_t session = client->session();
3288
Eric Laurent4eb58f12018-12-07 16:41:02 -08003289 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003290
Eric Laurent4eb58f12018-12-07 16:41:02 -08003291 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003292
Eric Laurent4eb58f12018-12-07 16:41:02 -08003293 status_t status = inputDesc->start();
3294 if (status != NO_ERROR) {
3295 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003296 }
Eric Laurente552edb2014-03-10 17:42:56 -07003297
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003298 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003299 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003300 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003301
Eric Laurent8f42ea12018-08-08 09:08:25 -07003302 // indicate active capture to sound trigger service if starting capture from a mic on
3303 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003304 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003305 if (device != nullptr) {
3306 status = setInputDevice(input, device, true /* force */);
3307 } else {
3308 ALOGW("%s no new input device can be found for descriptor %d",
3309 __FUNCTION__, inputDesc->getId());
3310 status = BAD_VALUE;
3311 }
Eric Laurente552edb2014-03-10 17:42:56 -07003312
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003313 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003314 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003315 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003316 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003317 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3318 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003319 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003320 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003321
François Gaffie11d30102018-11-02 16:09:09 +01003322 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3323 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003324 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003325 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003326 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003327
Eric Laurent8f42ea12018-08-08 09:08:25 -07003328 // automatically enable the remote submix output when input is started if not
3329 // used by a policy mix of type MIX_TYPE_RECORDERS
3330 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003331 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003332 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003333 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003334 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003335 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3336 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003337 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003338 if (address != "") {
3339 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3340 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003341 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003342 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003343 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003344 } else if (status != NO_ERROR) {
3345 // Restore client activity state.
3346 inputDesc->setClientActive(client, false);
3347 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003348 }
3349
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003350 ALOGV("%s input %d source = %d status = %d exit",
3351 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003352
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003353 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003354}
3355
Eric Laurent8fc147b2018-07-22 19:13:55 -07003356status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003357{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003358 ALOGV("%s portId %d", __FUNCTION__, portId);
3359
3360 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3361 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003362 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003363 return BAD_VALUE;
3364 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003365 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003366 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003367 if (!client->active()) {
3368 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003369 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003370 }
Carter Hsue6139d52021-07-08 10:30:20 +08003371 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003372 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003373
Eric Laurent8f42ea12018-08-08 09:08:25 -07003374 inputDesc->stop();
3375 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003376 auto current_source = inputDesc->source();
3377 setInputDevice(input, getNewInputDevice(inputDesc),
3378 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003379 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003380 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003381 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003382 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003383 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3384 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003385 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003386 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003387
3388 // automatically disable the remote submix output when input is stopped if not
3389 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003390 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003391 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003392 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003393 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003394 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3395 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003396 }
3397 if (address != "") {
3398 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3399 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003400 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003401 }
3402 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003403 resetInputDevice(input);
3404
3405 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3406 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003407 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3408 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003409 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003410 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003411 }
3412 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003413 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003414 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003415}
3416
Eric Laurent8fc147b2018-07-22 19:13:55 -07003417void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003418{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003419 ALOGV("%s portId %d", __FUNCTION__, portId);
3420
3421 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3422 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003423 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003424 return;
3425 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003426 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003427 audio_io_handle_t input = inputDesc->mIoHandle;
3428
Eric Laurent8f42ea12018-08-08 09:08:25 -07003429 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003430
Andy Hung39efb7a2018-09-26 15:39:28 -07003431 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003432
3433 // If no more clients are present in this session, park effects to an orphan chain
3434 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3435 if (clientsOnSession.size() == 0) {
3436 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3437 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003438 if (inputDesc->getClientCount() > 0) {
3439 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003440 return;
3441 }
3442
Eric Laurent05b90f82014-08-27 15:32:29 -07003443 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003444 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003445 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003446}
3447
Eric Laurent8f42ea12018-08-08 09:08:25 -07003448void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003449{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003450 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003451
3452 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003453 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003454 }
3455}
3456
Eric Laurent8f42ea12018-08-08 09:08:25 -07003457void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3458{
3459 stopInput(portId);
3460 releaseInput(portId);
3461}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003462
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003463bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3464 if (input->clientsList().size() == 0
3465 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3466 return true;
3467 }
3468 for (const auto& client : input->clientsList()) {
3469 sp<DeviceDescriptor> device =
3470 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3471 client->session());
3472 if (!input->supportedDevices().contains(device)) {
3473 return true;
3474 }
3475 }
3476 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3477 return false;
3478}
3479
Eric Laurent0dd51852019-04-19 18:18:58 -07003480void AudioPolicyManager::checkCloseInputs() {
3481 // After connecting or disconnecting an input device, close input if:
3482 // - it has no client (was just opened to check profile) OR
3483 // - none of its supported devices are connected anymore OR
3484 // - one of its clients cannot be routed to one of its supported
3485 // devices anymore. Otherwise update device selection
3486 std::vector<audio_io_handle_t> inputsToClose;
3487 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003488 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003489 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003490 }
3491 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003492 for (const audio_io_handle_t handle : inputsToClose) {
3493 ALOGV("%s closing input %d", __func__, handle);
3494 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003495 }
Eric Laurentd4692962014-05-05 18:13:44 -07003496}
3497
Vlad Popa87e0e582024-05-20 18:49:20 -07003498status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3499 const char *address __unused,
3500 bool enabled,
3501 audio_stream_type_t streamToDriveAbs)
3502{
3503 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3504 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3505 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3506 toString(streamToDriveAbs).c_str());
3507 return BAD_VALUE;
3508 }
3509
3510 if (enabled) {
3511 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3512 } else {
3513 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3514 }
3515
3516 return NO_ERROR;
3517}
3518
François Gaffie251c7f02018-11-07 10:41:08 +01003519void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003520{
3521 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003522 if (indexMin < 0 || indexMax < 0) {
3523 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3524 return;
3525 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003526 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003527
3528 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003529 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3530 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003531 continue;
3532 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003533 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003534 }
Eric Laurente552edb2014-03-10 17:42:56 -07003535}
3536
Eric Laurente0720872014-03-11 09:30:41 -07003537status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003538 int index,
3539 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003540{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003541 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003542 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3543 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3544 return NO_ERROR;
3545 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003546 ALOGV("%s: stream %s attributes=%s", __func__,
3547 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003548 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003549}
3550
Eric Laurente0720872014-03-11 09:30:41 -07003551status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003552 int *index,
3553 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003554{
François Gaffiec005e562018-11-06 15:04:49 +01003555 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3556 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003557 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003558 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003559 deviceTypes = mEngine->getOutputDevicesForStream(
3560 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003561 }
jiabin9a3361e2019-10-01 09:38:30 -07003562 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003563}
3564
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003565status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003566 int index,
3567 audio_devices_t device)
3568{
3569 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003570 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3571 if (group == VOLUME_GROUP_NONE) {
3572 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003573 return BAD_VALUE;
3574 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003575 ALOGV("%s: group %d matching with %s index %d",
3576 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003577 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003578 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003579 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003580 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3581 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3582 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3583 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003584 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3585
3586 status = setVolumeCurveIndex(index, device, curves);
3587 if (status != NO_ERROR) {
3588 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3589 return status;
3590 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003591
jiabin9a3361e2019-10-01 09:38:30 -07003592 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003593 auto curCurvAttrs = curves.getAttributes();
3594 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3595 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003596 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003597 } else if (!curves.getStreamTypes().empty()) {
3598 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003599 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003600 } else {
3601 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3602 return BAD_VALUE;
3603 }
jiabin9a3361e2019-10-01 09:38:30 -07003604 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3605 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003606
François Gaffiecfe17322018-11-07 13:41:29 +01003607 // update volume on all outputs and streams matching the following:
3608 // - The requested stream (or a stream matching for volume control) is active on the output
3609 // - The device (or devices) selected by the engine for this stream includes
3610 // the requested device
3611 // - For non default requested device, currently selected device on the output is either the
3612 // requested device or one of the devices selected by the engine for this stream
3613 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3614 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003615 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003616 for (size_t i = 0; i < mOutputs.size(); i++) {
3617 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003618 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003619
jiabin9a3361e2019-10-01 09:38:30 -07003620 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3621 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003622 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003623
3624 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003625 continue;
3626 }
3627 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3628 curDevices.find(device) == curDevices.end()) {
3629 continue;
3630 }
3631 bool applyVolume = false;
3632 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3633 curSrcDevices.insert(device);
3634 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003635 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3636 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003637 } else {
3638 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3639 }
3640 if (!applyVolume) {
3641 continue; // next output
3642 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003643 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3644 // If a higher priority strategy is active, and the output is routed to a device with a
3645 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003646 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003647 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003648 // If the volume source is active with higher priority source, ensure at least Sw Muted
3649 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003650 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3651 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3652 false /*preferredDevice*/);
3653 if (activeClients.empty()) {
3654 continue;
3655 }
3656 bool isPreempted = false;
3657 bool isHigherPriority = productStrategy < strategy;
3658 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003659 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003660 ALOGV("%s: Strategy=%d (\nrequester:\n"
3661 " group %d, volumeGroup=%d attributes=%s)\n"
3662 " higher priority source active:\n"
3663 " volumeGroup=%d attributes=%s) \n"
3664 " on output %zu, bailing out", __func__, productStrategy,
3665 group, group, toString(attributes).c_str(),
3666 client->volumeSource(), toString(client->attributes()).c_str(), i);
3667 applyVolume = false;
3668 isPreempted = true;
3669 break;
3670 }
3671 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003672 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003673 applyVolume = true;
3674 }
3675 }
3676 if (isPreempted || applyVolume) {
3677 break;
3678 }
3679 }
3680 if (!applyVolume) {
3681 continue; // next output
3682 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003683 }
François Gaffieed91f582020-01-31 10:35:37 +01003684 //FIXME: workaround for truncated touch sounds
3685 // delayed volume change for system stream to be removed when the problem is
3686 // handled by system UI
3687 status_t volStatus = checkAndSetVolume(
3688 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003689 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003690 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3691 if (volStatus != NO_ERROR) {
3692 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003693 }
3694 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003695
3696 // update voice volume if the an active call route exists
3697 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3698 && (curSrcDevices.find(
3699 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3700 != curSrcDevices.end())) {
3701 bool isVoiceVolSrc;
3702 bool isBtScoVolSrc;
3703 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3704 isVoiceVolSrc, isBtScoVolSrc, __func__)
3705 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003706 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3707 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3708 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003709 }
3710 }
3711
François Gaffiecfe17322018-11-07 13:41:29 +01003712 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3713 return status;
3714}
3715
François Gaffieaaac0fd2018-11-22 17:56:39 +01003716status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003717 audio_devices_t device,
3718 IVolumeCurves &volumeCurves)
3719{
3720 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3721 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003722 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3723 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003724 (index > volumeCurves.getVolumeIndexMax())) {
3725 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3726 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3727 return BAD_VALUE;
3728 }
3729 if (!audio_is_output_device(device)) {
3730 return BAD_VALUE;
3731 }
3732
3733 // Force max volume if stream cannot be muted
3734 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3735
François Gaffieaaac0fd2018-11-22 17:56:39 +01003736 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003737 volumeCurves.addCurrentVolumeIndex(device, index);
3738 return NO_ERROR;
3739}
3740
3741status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3742 int &index,
3743 audio_devices_t device)
3744{
3745 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3746 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003747 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003748 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003749 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003750 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003751 }
jiabin9a3361e2019-10-01 09:38:30 -07003752 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003753}
3754
3755status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3756 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003757 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003758{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003759 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003760 return BAD_VALUE;
3761 }
jiabin9a3361e2019-10-01 09:38:30 -07003762 index = curves.getVolumeIndex(deviceTypes);
3763 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003764 return NO_ERROR;
3765}
3766
3767status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3768 int &index)
3769{
3770 index = getVolumeCurves(attr).getVolumeIndexMin();
3771 return NO_ERROR;
3772}
3773
3774status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3775 int &index)
3776{
3777 index = getVolumeCurves(attr).getVolumeIndexMax();
3778 return NO_ERROR;
3779}
3780
Eric Laurent36829f92017-04-07 19:04:42 -07003781audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003782{
3783 // select one output among several suitable for global effects.
3784 // The priority is as follows:
3785 // 1: An offloaded output. If the effect ends up not being offloadable,
3786 // AudioFlinger will invalidate the track and the offloaded output
3787 // will be closed causing the effect to be moved to a PCM output.
3788 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003789 // 3: The primary output
3790 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003791
François Gaffiec005e562018-11-06 15:04:49 +01003792 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3793 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003794 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003795
Eric Laurent36829f92017-04-07 19:04:42 -07003796 if (outputs.size() == 0) {
3797 return AUDIO_IO_HANDLE_NONE;
3798 }
Eric Laurente552edb2014-03-10 17:42:56 -07003799
Eric Laurent36829f92017-04-07 19:04:42 -07003800 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3801 bool activeOnly = true;
3802
3803 while (output == AUDIO_IO_HANDLE_NONE) {
3804 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3805 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3806 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3807
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003808 for (audio_io_handle_t output : outputs) {
3809 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003810 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003811 continue;
3812 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003813 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3814 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003815 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003816 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003817 }
3818 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003819 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003820 }
3821 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003822 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003823 }
3824 }
3825 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3826 output = outputOffloaded;
3827 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3828 output = outputDeepBuffer;
3829 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3830 output = outputPrimary;
3831 } else {
3832 output = outputs[0];
3833 }
3834 activeOnly = false;
3835 }
3836
3837 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003838 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3839 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003840 mMusicEffectOutput = output;
3841 }
3842
3843 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003844 return output;
3845}
3846
Eric Laurent36829f92017-04-07 19:04:42 -07003847audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3848{
3849 return selectOutputForMusicEffects();
3850}
3851
Eric Laurente0720872014-03-11 09:30:41 -07003852status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003853 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003854 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003855 int session,
3856 int id)
3857{
Shunkai Yao29d10572024-03-19 04:31:47 +00003858 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003859 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003860 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003861 index = mInputs.indexOfKey(io);
3862 if (index < 0) {
3863 ALOGW("registerEffect() unknown io %d", io);
3864 return INVALID_OPERATION;
3865 }
Eric Laurente552edb2014-03-10 17:42:56 -07003866 }
3867 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003868 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3869 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3870 || strategy == PRODUCT_STRATEGY_NONE));
3871 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003872}
3873
Eric Laurentc241b0d2018-11-28 09:08:49 -08003874status_t AudioPolicyManager::unregisterEffect(int id)
3875{
3876 if (mEffects.getEffect(id) == nullptr) {
3877 return INVALID_OPERATION;
3878 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003879 if (mEffects.isEffectEnabled(id)) {
3880 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3881 setEffectEnabled(id, false);
3882 }
3883 return mEffects.unregisterEffect(id);
3884}
3885
3886status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3887{
3888 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3889 if (effect == nullptr) {
3890 return INVALID_OPERATION;
3891 }
3892
3893 status_t status = mEffects.setEffectEnabled(id, enabled);
3894 if (status == NO_ERROR) {
3895 mInputs.trackEffectEnabled(effect, enabled);
3896 }
3897 return status;
3898}
3899
Eric Laurent6c796322019-04-09 14:13:17 -07003900
3901status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3902{
3903 mEffects.moveEffects(ids, io);
3904 return NO_ERROR;
3905}
3906
Eric Laurentc75307b2015-03-17 15:29:32 -07003907bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3908{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003909 auto vs = toVolumeSource(stream, false);
3910 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003911}
3912
3913bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3914{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003915 auto vs = toVolumeSource(stream, false);
3916 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003917}
3918
Eric Laurente0720872014-03-11 09:30:41 -07003919bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003920{
3921 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003922 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003923 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003924 return true;
3925 }
3926 }
3927 return false;
3928}
3929
Eric Laurent275e8e92014-11-30 15:14:47 -08003930// Register a list of custom mixes with their attributes and format.
3931// When a mix is registered, corresponding input and output profiles are
3932// added to the remote submix hw module. The profile contains only the
3933// parameters (sampling rate, format...) specified by the mix.
3934// The corresponding input remote submix device is also connected.
3935//
3936// When a remote submix device is connected, the address is checked to select the
3937// appropriate profile and the corresponding input or output stream is opened.
3938//
3939// When capture starts, getInputForAttr() will:
3940// - 1 look for a mix matching the address passed in attribtutes tags if any
3941// - 2 if none found, getDeviceForInputSource() will:
3942// - 2.1 look for a mix matching the attributes source
3943// - 2.2 if none found, default to device selection by policy rules
3944// At this time, the corresponding output remote submix device is also connected
3945// and active playback use cases can be transferred to this mix if needed when reconnecting
3946// after AudioTracks are invalidated
3947//
3948// When playback starts, getOutputForAttr() will:
3949// - 1 look for a mix matching the address passed in attribtutes tags if any
3950// - 2 if none found, look for a mix matching the attributes usage
3951// - 3 if none found, default to device and output selection by policy rules.
3952
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003953status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003954{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003955 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3956 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003957 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003958 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003959 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003960 // examine each mix's route type
3961 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003962 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003963 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3964 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3965 ALOGE("Unsupported Policy Mix %zu of %zu: "
3966 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3967 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003968 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003969 break;
3970 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003971 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3972 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003973 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003974 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3975 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003976 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003977 rSubmixModule = mHwModules.getModuleFromName(
3978 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3979 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003980 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003981 i);
3982 res = INVALID_OPERATION;
3983 break;
3984 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003985 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003986
Eric Laurent97ac8712018-07-27 18:59:02 -07003987 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003988 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003989 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003990 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003991 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3992 } else {
3993 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3994 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003995 }
François Gaffie036e1e92015-03-19 10:16:24 +01003996
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003997 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003998 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003999 res = INVALID_OPERATION;
4000 break;
4001 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004002 audio_config_t outputConfig = mix.mFormat;
4003 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004004 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4005 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004006 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4007 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004008 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004009 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4010 audio_is_linear_pcm(outputConfig.format)
4011 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004012 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004013 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4014 audio_is_linear_pcm(inputConfig.format)
4015 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004016
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004017 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004018 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004019 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004020 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004021 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004022 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004023 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004024 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4025 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004026 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004027 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004028 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004029
4030 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4031 mix.mDeviceType, mix.mDeviceAddress,
4032 String8(), AUDIO_FORMAT_DEFAULT);
4033 if (device == nullptr) {
4034 res = INVALID_OPERATION;
4035 break;
4036 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004037
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004038 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004039 // First try to find an already opened output supporting the device
4040 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004041 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004042
Eric Laurentc529cf62020-04-17 18:19:10 -07004043 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004044 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004045 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004046 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004047 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004048 } else {
4049 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004050 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004051 }
4052 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004053 // If no output found, try to find a direct output profile supporting the device
4054 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4055 sp<HwModule> module = mHwModules[i];
4056 for (size_t j = 0;
4057 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4058 j++) {
4059 sp<IOProfile> profile = module->getOutputProfiles()[j];
4060 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4061 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4062 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004063 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004064 res = INVALID_OPERATION;
4065 } else {
4066 foundOutput = true;
4067 }
4068 }
4069 }
4070 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004071 if (res != NO_ERROR) {
4072 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004073 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004074 res = INVALID_OPERATION;
4075 break;
4076 } else if (!foundOutput) {
4077 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004078 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004079 res = INVALID_OPERATION;
4080 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004081 } else {
4082 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004083 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004084 }
Eric Laurentc722f302014-12-10 11:21:49 -08004085 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004086 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004087 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004088 if (audio_flags::audio_mix_ownership()) {
4089 // Only unregister mixes that were actually registered to not accidentally unregister
4090 // mixes that already existed previously.
4091 unregisterPolicyMixes(registeredMixes);
4092 registeredMixes.clear();
4093 } else {
4094 unregisterPolicyMixes(mixes);
4095 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004096 } else if (checkOutputs) {
4097 checkForDeviceAndOutputChanges();
4098 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004099 }
4100 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004101}
4102
4103status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4104{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004105 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004106 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004107 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004108 sp<HwModule> rSubmixModule;
4109 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004110 for (const auto& mix : mixes) {
4111 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004112
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004113 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004114 rSubmixModule = mHwModules.getModuleFromName(
4115 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4116 if (rSubmixModule == 0) {
4117 res = INVALID_OPERATION;
4118 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004119 }
4120 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004121
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004122 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004123
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004124 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004125 res = INVALID_OPERATION;
4126 continue;
4127 }
4128
Marvin Ramin0783e202024-03-05 12:45:50 +01004129 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004130 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004131 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4132 status_t currentRes =
4133 setDeviceConnectionStateInt(device,
4134 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4135 address.c_str(),
4136 "remote-submix",
4137 AUDIO_FORMAT_DEFAULT);
4138 if (!audio_flags::audio_mix_ownership()) {
4139 res = currentRes;
4140 }
4141 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004142 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004143 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004144 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004145 }
4146 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004147 }
jiabin5740f082019-08-19 15:08:30 -07004148 rSubmixModule->removeOutputProfile(address.c_str());
4149 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004150
Kevin Rocard153f92d2018-12-18 18:33:28 -08004151 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004152 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004153 res = INVALID_OPERATION;
4154 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004155 } else {
4156 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004157 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004158 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004159 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004160
4161 if (res == NO_ERROR && checkOutputs) {
4162 checkForDeviceAndOutputChanges();
4163 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004164 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004165 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004166}
4167
Marvin Raminbdefaf02023-11-01 09:10:32 +01004168status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4169 if (!audio_flags::audio_mix_test_api()) {
4170 return INVALID_OPERATION;
4171 }
4172
4173 _aidl_return.clear();
4174 _aidl_return.reserve(mPolicyMixes.size());
4175 for (const auto &policyMix: mPolicyMixes) {
4176 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4177 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4178 policyMix->mCbFlags);
4179 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004180 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004181 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004182 }
4183
Vlad Popaa5d73f32024-03-08 16:05:38 -08004184 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004185 return OK;
4186}
4187
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004188status_t AudioPolicyManager::updatePolicyMix(
4189 const AudioMix& mix,
4190 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4191 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4192 if (res == NO_ERROR) {
4193 checkForDeviceAndOutputChanges();
4194 updateCallAndOutputRouting();
4195 }
4196 return res;
4197}
4198
Mikhail Naganov100f0122018-11-29 11:22:16 -08004199void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4200{
4201 size_t i = 0;
4202 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4203 for (const auto& fmt : mManualSurroundFormats) {
4204 if (i++ != 0) dst->append(", ");
4205 std::string sfmt;
4206 FormatConverter::toString(fmt, sfmt);
4207 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4208 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4209 }
4210}
4211
Eric Laurentc529cf62020-04-17 18:19:10 -07004212// Returns true if all devices types match the predicate and are supported by one HW module
4213bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004214 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004215 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004216 const char *context,
4217 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004218 for (size_t i = 0; i < devices.size(); i++) {
4219 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004220 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004221 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004222 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004223 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004224 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004225 return false;
4226 }
4227 }
4228 return true;
4229}
4230
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004231void AudioPolicyManager::changeOutputDevicesMuteState(
4232 const AudioDeviceTypeAddrVector& devices) {
4233 ALOGVV("%s() num devices %zu", __func__, devices.size());
4234
4235 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4236 getSoftwareOutputsForDevices(devices);
4237
4238 for (size_t i = 0; i < outputs.size(); i++) {
4239 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4240 DeviceVector prevDevices = outputDesc->devices();
4241 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4242 }
4243}
4244
4245std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4246 const AudioDeviceTypeAddrVector& devices) const
4247{
4248 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4249 DeviceVector deviceDescriptors;
4250 for (size_t j = 0; j < devices.size(); j++) {
4251 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4252 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4253 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4254 ALOGE("%s: device type %#x address %s not supported or not an output device",
4255 __func__, devices[j].mType, devices[j].getAddress());
4256 continue;
4257 }
4258 deviceDescriptors.add(desc);
4259 }
4260 for (size_t i = 0; i < mOutputs.size(); i++) {
4261 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4262 continue;
4263 }
4264 outputs.push_back(mOutputs.valueAt(i));
4265 }
4266 return outputs;
4267}
4268
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004269status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004270 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004271 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004272 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4273 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004274 }
4275 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004276 if (res != NO_ERROR) {
4277 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4278 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004279 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004280
4281 checkForDeviceAndOutputChanges();
4282 updateCallAndOutputRouting();
4283
4284 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004285}
4286
4287status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4288 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004289 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4290 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004291 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004292 __FUNCTION__, uid);
4293 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004294 }
4295
Eric Laurentc529cf62020-04-17 18:19:10 -07004296 checkForDeviceAndOutputChanges();
4297 updateCallAndOutputRouting();
4298
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004299 return res;
4300}
4301
Eric Laurent2517af32020-11-25 15:31:27 +01004302
jiabin0a488932020-08-07 17:32:40 -07004303status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4304 device_role_t role,
4305 const AudioDeviceTypeAddrVector &devices) {
4306 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4307 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004308
Eric Laurentc529cf62020-04-17 18:19:10 -07004309 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004310 return BAD_VALUE;
4311 }
jiabin0a488932020-08-07 17:32:40 -07004312 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004313 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004314 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4315 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004316 return status;
4317 }
4318
4319 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004320
4321 bool forceVolumeReeval = false;
4322 // FIXME: workaround for truncated touch sounds
4323 // to be removed when the problem is handled by system UI
4324 uint32_t delayMs = 0;
4325 if (strategy == mCommunnicationStrategy) {
4326 forceVolumeReeval = true;
4327 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4328 updateInputRouting();
4329 }
4330 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004331
4332 return NO_ERROR;
4333}
4334
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004335void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4336 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004337{
4338 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004339 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004340 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004341 // Only apply special touch sound delay once
4342 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004343 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004344 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004345 for (size_t i = 0; i < mOutputs.size(); i++) {
4346 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4347 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004348 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4349 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004350 // As done in setDeviceConnectionState, we could also fix default device issue by
4351 // preventing the force re-routing in case of default dev that distinguishes on address.
4352 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004353 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004354 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004355 // If the device is using preferred mixer attributes, the output need to reopen
4356 // with default configuration when the new selected devices are different from
4357 // current routing devices.
4358 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4359 continue;
4360 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304361
4362 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4363 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004364 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004365 // Only apply special touch sound delay once
4366 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004367 }
4368 if (forceVolumeReeval && !newDevices.isEmpty()) {
4369 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4370 }
4371 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004372 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004373 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004374}
4375
Eric Laurent2517af32020-11-25 15:31:27 +01004376void AudioPolicyManager::updateInputRouting() {
4377 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304378 // Skip for hotword recording as the input device switch
4379 // is handled within sound trigger HAL
4380 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4381 continue;
4382 }
Eric Laurent2517af32020-11-25 15:31:27 +01004383 auto newDevice = getNewInputDevice(activeDesc);
4384 // Force new input selection if the new device can not be reached via current input
4385 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4386 setInputDevice(activeDesc->mIoHandle, newDevice);
4387 } else {
4388 closeInput(activeDesc->mIoHandle);
4389 }
4390 }
4391}
4392
Paul Wang5d7cdb52022-11-22 09:45:06 +00004393status_t
4394AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4395 device_role_t role,
4396 const AudioDeviceTypeAddrVector &devices) {
4397 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4398 dumpAudioDeviceTypeAddrVector(devices).c_str());
4399
Eric Laurent78fedbf2023-03-09 14:40:44 +01004400 if (!areAllDevicesSupported(
4401 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004402 return BAD_VALUE;
4403 }
4404 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4405 if (status != NO_ERROR) {
4406 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4407 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4408 return status;
4409 }
4410
4411 checkForDeviceAndOutputChanges();
4412
4413 bool forceVolumeReeval = false;
4414 // TODO(b/263479999): workaround for truncated touch sounds
4415 // to be removed when the problem is handled by system UI
4416 uint32_t delayMs = 0;
4417 if (strategy == mCommunnicationStrategy) {
4418 forceVolumeReeval = true;
4419 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4420 updateInputRouting();
4421 }
4422 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4423
4424 return NO_ERROR;
4425}
4426
4427status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4428 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004429{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004430 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004431
Paul Wang5d7cdb52022-11-22 09:45:06 +00004432 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004433 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004434 ALOGW_IF(status != NAME_NOT_FOUND,
4435 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004436 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004437 return status;
4438 }
4439
4440 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004441
4442 bool forceVolumeReeval = false;
4443 // FIXME: workaround for truncated touch sounds
4444 // to be removed when the problem is handled by system UI
4445 uint32_t delayMs = 0;
4446 if (strategy == mCommunnicationStrategy) {
4447 forceVolumeReeval = true;
4448 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4449 updateInputRouting();
4450 }
4451 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004452
4453 return NO_ERROR;
4454}
4455
jiabin0a488932020-08-07 17:32:40 -07004456status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4457 device_role_t role,
4458 AudioDeviceTypeAddrVector &devices) {
4459 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004460}
4461
Jiabin Huang3b98d322020-09-03 17:54:16 +00004462status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4463 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4464 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4465 dumpAudioDeviceTypeAddrVector(devices).c_str());
4466
Mikhail Naganov55773032020-10-01 15:08:13 -07004467 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004468 return BAD_VALUE;
4469 }
4470 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4471 ALOGW_IF(status != NO_ERROR,
4472 "Engine could not set preferred devices %s for audio source %d role %d",
4473 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4474
4475 return status;
4476}
4477
4478status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4479 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4480 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4481 dumpAudioDeviceTypeAddrVector(devices).c_str());
4482
Mikhail Naganov55773032020-10-01 15:08:13 -07004483 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004484 return BAD_VALUE;
4485 }
4486 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4487 ALOGW_IF(status != NO_ERROR,
4488 "Engine could not add preferred devices %s for audio source %d role %d",
4489 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4490
Eric Laurent2517af32020-11-25 15:31:27 +01004491 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004492 return status;
4493}
4494
4495status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4496 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4497{
4498 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4499 dumpAudioDeviceTypeAddrVector(devices).c_str());
4500
Eric Laurent78fedbf2023-03-09 14:40:44 +01004501 if (!areAllDevicesSupported(
4502 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004503 return BAD_VALUE;
4504 }
4505
4506 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4507 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004508 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004509 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004510 if (status == NO_ERROR) {
4511 updateInputRouting();
4512 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004513 return status;
4514}
4515
4516status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4517 device_role_t role) {
4518 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4519
4520 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004521 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004522 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004523 if (status == NO_ERROR) {
4524 updateInputRouting();
4525 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004526 return status;
4527}
4528
4529status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4530 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4531 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4532}
4533
Oscar Azucena90e77632019-11-27 17:12:28 -08004534status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004535 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004536 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004537 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4538 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004539 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004540 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4541 if (status != NO_ERROR) {
4542 ALOGE("%s() could not set device affinity for userId %d",
4543 __FUNCTION__, userId);
4544 return status;
4545 }
4546
4547 // reevaluate outputs for all devices
4548 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004549 changeOutputDevicesMuteState(devices);
4550 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4551 true /* skipDelays */);
4552 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004553
4554 return NO_ERROR;
4555}
4556
4557status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004558 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004559 AudioDeviceTypeAddrVector devices;
4560 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004561 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4562 if (status != NO_ERROR) {
4563 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4564 __FUNCTION__, userId);
4565 return status;
4566 }
4567
4568 // reevaluate outputs for all devices
4569 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004570 changeOutputDevicesMuteState(devices);
4571 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4572 true /* skipDelays */);
4573 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004574
4575 return NO_ERROR;
4576}
4577
Andy Hungc29d82b2018-10-05 12:23:17 -07004578void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004579{
Andy Hungc29d82b2018-10-05 12:23:17 -07004580 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004581 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004582 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004583 std::string stateLiteral;
4584 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004585 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004586 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4587 "communications", "media", "record", "dock", "system",
4588 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4589 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4590 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004591 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4592 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4593 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4594 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4595 dst->append(" (MANUAL: ");
4596 dumpManualSurroundFormats(dst);
4597 dst->append(")");
4598 }
4599 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004600 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004601 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4602 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004603 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004604 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004605
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004606 dst->append("\n");
4607 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4608 dst->append("\n");
4609 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004610 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004611 mOutputs.dump(dst);
4612 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004613 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004614 mAudioPatches.dump(dst);
4615 mPolicyMixes.dump(dst);
4616 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004617
Kevin Rocardb99cc752019-03-21 20:52:24 -07004618 dst->appendFormat(" AllowedCapturePolicies:\n");
4619 for (auto& policy : mAllowedCapturePolicies) {
4620 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4621 }
4622
jiabina84c3d32022-12-02 18:59:55 +00004623 dst->appendFormat(" Preferred mixer audio configuration:\n");
4624 for (const auto it : mPreferredMixerAttrInfos) {
4625 dst->appendFormat(" - device port id: %d\n", it.first);
4626 for (const auto preferredMixerInfoIt : it.second) {
4627 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4628 preferredMixerInfoIt.second->dump(dst);
4629 }
4630 }
4631
François Gaffiec005e562018-11-06 15:04:49 +01004632 dst->appendFormat("\nPolicy Engine dump:\n");
4633 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004634
4635 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4636 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4637 dst->appendFormat(" - device type: %s, driving stream %d\n",
4638 dumpDeviceTypes({it.first}).c_str(),
4639 mEngine->getVolumeGroupForAttributes(it.second));
4640 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004641}
4642
4643status_t AudioPolicyManager::dump(int fd)
4644{
4645 String8 result;
4646 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004647 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004648 return NO_ERROR;
4649}
4650
Kevin Rocardb99cc752019-03-21 20:52:24 -07004651status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4652{
4653 mAllowedCapturePolicies[uid] = capturePolicy;
4654 return NO_ERROR;
4655}
4656
Eric Laurente552edb2014-03-10 17:42:56 -07004657// This function checks for the parameters which can be offloaded.
4658// This can be enhanced depending on the capability of the DSP and policy
4659// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004660audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004661{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004662 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004663 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004664 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004665 offloadInfo.format,
4666 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4667 offloadInfo.has_video);
4668
jiabin2b9d5a12021-12-10 01:06:29 +00004669 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004670 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004671 }
4672
4673 // See if there is a profile to support this.
4674 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004675 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004676 offloadInfo.sample_rate,
4677 offloadInfo.format,
4678 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004679 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4680 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004681 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4682 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4683 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004684 if (profile == nullptr) {
4685 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4686 }
4687 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4688 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4689 }
4690 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004691}
4692
Michael Chana94fbb22018-04-24 14:31:19 +10004693bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4694 const audio_attributes_t& attributes) {
4695 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004696 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004697 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4698 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004699 config.sample_rate,
4700 config.format,
4701 config.channel_mask,
4702 output_flags,
4703 true /* directOnly */);
4704 ALOGV("%s() profile %sfound with name: %s, "
4705 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4706 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004707 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004708 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004709
4710 // also try the MSD module if compatible profile not found
4711 if (profile == nullptr) {
4712 profile = getMsdProfileForOutput(outputDevices,
4713 config.sample_rate,
4714 config.format,
4715 config.channel_mask,
4716 output_flags,
4717 true /* directOnly */);
4718 ALOGV("%s() MSD profile %sfound with name: %s, "
4719 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4720 __FUNCTION__, profile != 0 ? "" : "NOT ",
4721 (profile != 0 ? profile->getTagName().c_str() : "null"),
4722 config.sample_rate, config.format, config.channel_mask, output_flags);
4723 }
4724 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004725}
4726
jiabin2b9d5a12021-12-10 01:06:29 +00004727bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4728 bool durationIgnored) {
4729 if (mMasterMono) {
4730 return false; // no offloading if mono is set.
4731 }
4732
4733 // Check if offload has been disabled
4734 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4735 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4736 return false;
4737 }
4738
4739 // Check if stream type is music, then only allow offload as of now.
4740 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4741 {
4742 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4743 return false;
4744 }
4745
4746 //TODO: enable audio offloading with video when ready
4747 const bool allowOffloadWithVideo =
4748 property_get_bool("audio.offload.video", false /* default_value */);
4749 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4750 ALOGV("%s: has_video == true, returning false", __func__);
4751 return false;
4752 }
4753
4754 //If duration is less than minimum value defined in property, return false
4755 const int min_duration_secs = property_get_int32(
4756 "audio.offload.min.duration.secs", -1 /* default_value */);
4757 if (!durationIgnored) {
4758 if (min_duration_secs >= 0) {
4759 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4760 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4761 __func__, min_duration_secs);
4762 return false;
4763 }
4764 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4765 ALOGV("%s: Offload denied by duration < default min(=%u)",
4766 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4767 return false;
4768 }
4769 }
4770
4771 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4772 // creating an offloaded track and tearing it down immediately after start when audioflinger
4773 // detects there is an active non offloadable effect.
4774 // FIXME: We should check the audio session here but we do not have it in this context.
4775 // This may prevent offloading in rare situations where effects are left active by apps
4776 // in the background.
4777 if (mEffects.isNonOffloadableEffectEnabled()) {
4778 return false;
4779 }
4780
4781 return true;
4782}
4783
4784audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4785 const audio_config_t *config) {
4786 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4787 offloadInfo.format = config->format;
4788 offloadInfo.sample_rate = config->sample_rate;
4789 offloadInfo.channel_mask = config->channel_mask;
4790 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4791 offloadInfo.has_video = false;
4792 offloadInfo.is_streaming = false;
4793 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4794
4795 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4796 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4797 audio_flags_to_audio_output_flags(attr->flags, &flags);
4798 // only retain flags that will drive compressed offload or passthrough
4799 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4800 if (offloadPossible) {
4801 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4802 }
4803 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4804
Dorin Drimusfae3c642022-03-17 18:36:30 +01004805 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004806 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004807 DeviceVector outputDevices = engineOutputDevices;
4808 // the MSD module checks for different conditions and output devices
4809 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4810 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4811 continue;
4812 }
4813 outputDevices = getMsdAudioOutDevices();
4814 }
jiabin2b9d5a12021-12-10 01:06:29 +00004815 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004816 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004817 config->sample_rate, nullptr /*updatedSamplingRate*/,
4818 config->format, nullptr /*updatedFormat*/,
4819 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004820 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004821 continue;
4822 }
4823 // reject profiles not corresponding to a device currently available
4824 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4825 continue;
4826 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004827 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4828 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004829 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004830 != AUDIO_DIRECT_NOT_SUPPORTED) {
4831 // Already reports offload gapless supported. No need to report offload support.
4832 continue;
4833 }
4834 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4835 != AUDIO_OUTPUT_FLAG_NONE) {
4836 // If offload gapless is reported, no need to report offload support.
4837 directMode = (audio_direct_mode_t) ((directMode &
4838 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4839 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4840 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004841 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004842 }
4843 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004844 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004845 }
4846 }
4847 }
4848 return directMode;
4849}
4850
Dorin Drimusf2196d82022-01-03 12:11:18 +01004851status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4852 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004853 if (mEffects.isNonOffloadableEffectEnabled()) {
4854 return OK;
4855 }
jiabinf1c73972022-04-14 16:28:52 -07004856 DeviceVector devices;
4857 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004858 if (status != OK) {
4859 return status;
4860 }
4861 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4862 if (devices.empty()) {
4863 return OK; // no output devices for the attributes
4864 }
jiabinf1c73972022-04-14 16:28:52 -07004865 return getProfilesForDevices(devices, audioProfilesVector,
4866 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004867}
4868
jiabina84c3d32022-12-02 18:59:55 +00004869status_t AudioPolicyManager::getSupportedMixerAttributes(
4870 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4871 ALOGV("%s, portId=%d", __func__, portId);
4872 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4873 if (deviceDescriptor == nullptr) {
4874 ALOGE("%s the requested device is currently unavailable", __func__);
4875 return BAD_VALUE;
4876 }
jiabin96daffc2023-05-11 17:51:55 +00004877 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4878 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4879 deviceDescriptor->type());
4880 return BAD_VALUE;
4881 }
jiabina84c3d32022-12-02 18:59:55 +00004882 for (const auto& hwModule : mHwModules) {
4883 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4884 if (curProfile->supportsDevice(deviceDescriptor)) {
4885 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4886 }
4887 }
4888 }
4889 return NO_ERROR;
4890}
4891
4892status_t AudioPolicyManager::setPreferredMixerAttributes(
4893 const audio_attributes_t *attr,
4894 audio_port_handle_t portId,
4895 uid_t uid,
4896 const audio_mixer_attributes_t *mixerAttributes) {
4897 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4898 "mixerBehavior=%d}, uid=%d, portId=%u",
4899 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4900 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4901 mixerAttributes->mixer_behavior, uid, portId);
4902 if (attr->usage != AUDIO_USAGE_MEDIA) {
4903 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4904 return BAD_VALUE;
4905 }
4906 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4907 if (deviceDescriptor == nullptr) {
4908 ALOGE("%s the requested device is currently unavailable", __func__);
4909 return BAD_VALUE;
4910 }
4911 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4912 ALOGE("%s(%d), type=%d, is not a usb output device",
4913 __func__, portId, deviceDescriptor->type());
4914 return BAD_VALUE;
4915 }
4916
4917 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4918 audio_flags_to_audio_output_flags(attr->flags, &flags);
4919 flags = (audio_output_flags_t) (flags |
4920 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4921 sp<IOProfile> profile = nullptr;
4922 DeviceVector devices(deviceDescriptor);
4923 for (const auto& hwModule : mHwModules) {
4924 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4925 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004926 && curProfile->getCompatibilityScore(
4927 devices,
4928 mixerAttributes->config.sample_rate,
4929 nullptr /*updatedSamplingRate*/,
4930 mixerAttributes->config.format,
4931 nullptr /*updatedFormat*/,
4932 mixerAttributes->config.channel_mask,
4933 nullptr /*updatedChannelMask*/,
4934 flags,
4935 false /*exactMatchRequiredForInputFlags*/)
4936 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004937 profile = curProfile;
4938 break;
4939 }
4940 }
4941 }
4942 if (profile == nullptr) {
4943 ALOGE("%s, there is no compatible profile found", __func__);
4944 return BAD_VALUE;
4945 }
4946
4947 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4948 sp<PreferredMixerAttributesInfo>::make(
4949 uid, portId, profile, flags, *mixerAttributes);
4950 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4951 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4952
4953 // If 1) there is any client from the preferred mixer configuration owner that is currently
4954 // active and matches the strategy and 2) current output is on the preferred device and the
4955 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4956 // configuration.
4957 std::vector<audio_io_handle_t> outputsToReopen;
4958 for (size_t i = 0; i < mOutputs.size(); i++) {
4959 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004960 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4961 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004962 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004963 } else {
4964 for (const auto &client: output->getActiveClients()) {
4965 if (client->uid() == uid && client->strategy() == strategy) {
4966 client->setIsInvalid();
4967 outputsToReopen.push_back(output->mIoHandle);
4968 }
jiabina84c3d32022-12-02 18:59:55 +00004969 }
4970 }
4971 }
4972 }
4973 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4974 config.sample_rate = mixerAttributes->config.sample_rate;
4975 config.channel_mask = mixerAttributes->config.channel_mask;
4976 config.format = mixerAttributes->config.format;
4977 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004978 sp<SwAudioOutputDescriptor> desc =
4979 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4980 if (desc == nullptr) {
4981 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4982 continue;
4983 }
jiabin220eea12024-05-17 17:55:20 +00004984 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004985 }
4986
4987 return NO_ERROR;
4988}
4989
4990sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004991 audio_port_handle_t devicePortId,
4992 product_strategy_t strategy,
4993 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004994 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4995 if (it == mPreferredMixerAttrInfos.end()) {
4996 return nullptr;
4997 }
jiabind9a58d32023-06-01 17:57:30 +00004998 if (activeBitPerfectPreferred) {
4999 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005000 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005001 return info;
5002 }
5003 }
jiabina84c3d32022-12-02 18:59:55 +00005004 }
jiabind9a58d32023-06-01 17:57:30 +00005005 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5006 return strategyMatchedMixerAttrInfoIt == it->second.end()
5007 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005008}
5009
5010status_t AudioPolicyManager::getPreferredMixerAttributes(
5011 const audio_attributes_t *attr,
5012 audio_port_handle_t portId,
5013 audio_mixer_attributes_t* mixerAttributes) {
5014 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5015 portId, mEngine->getProductStrategyForAttributes(*attr));
5016 if (info == nullptr) {
5017 return NAME_NOT_FOUND;
5018 }
5019 *mixerAttributes = info->getMixerAttributes();
5020 return NO_ERROR;
5021}
5022
5023status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5024 audio_port_handle_t portId,
5025 uid_t uid) {
5026 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5027 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5028 if (preferredMixerAttrInfo == nullptr) {
5029 return NAME_NOT_FOUND;
5030 }
5031 if (preferredMixerAttrInfo->getUid() != uid) {
5032 ALOGE("%s, requested uid=%d, owned uid=%d",
5033 __func__, uid, preferredMixerAttrInfo->getUid());
5034 return PERMISSION_DENIED;
5035 }
5036 mPreferredMixerAttrInfos[portId].erase(strategy);
5037 if (mPreferredMixerAttrInfos[portId].empty()) {
5038 mPreferredMixerAttrInfos.erase(portId);
5039 }
5040
5041 // Reconfig existing output
5042 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5043 for (size_t i = 0; i < mOutputs.size(); i++) {
5044 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5045 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5046 }
5047 }
5048 for (const auto output : potentialOutputsToReopen) {
5049 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5050 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5051 preferredMixerAttrInfo->getFlags())) {
5052 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5053 }
5054 }
5055 return NO_ERROR;
5056}
5057
Eric Laurent6a94d692014-05-20 11:18:06 -07005058status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5059 audio_port_type_t type,
5060 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005061 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005062 unsigned int *generation)
5063{
jiabin19cdba52020-11-24 11:28:58 -08005064 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5065 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005066 return BAD_VALUE;
5067 }
5068 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005069 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005070 *num_ports = 0;
5071 }
5072
5073 size_t portsWritten = 0;
5074 size_t portsMax = *num_ports;
5075 *num_ports = 0;
5076 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005077 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5078 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005079 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005080 for (const auto& dev : mAvailableOutputDevices) {
5081 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005082 continue;
5083 }
5084 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005085 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005086 }
5087 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005088 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005089 }
5090 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005091 for (const auto& dev : mAvailableInputDevices) {
5092 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005093 continue;
5094 }
5095 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005096 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005097 }
5098 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005099 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005100 }
5101 }
5102 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5103 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5104 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5105 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5106 }
5107 *num_ports += mInputs.size();
5108 }
5109 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005110 size_t numOutputs = 0;
5111 for (size_t i = 0; i < mOutputs.size(); i++) {
5112 if (!mOutputs[i]->isDuplicated()) {
5113 numOutputs++;
5114 if (portsWritten < portsMax) {
5115 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5116 }
5117 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005118 }
Eric Laurent84c70242014-06-23 08:46:27 -07005119 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005120 }
5121 }
jiabina84c3d32022-12-02 18:59:55 +00005122
Eric Laurent6a94d692014-05-20 11:18:06 -07005123 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005124 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005125 return NO_ERROR;
5126}
5127
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005128status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5129 std::vector<media::AudioPortFw>* _aidl_return) {
5130 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5131 audio_port_v7 port;
5132 dev->toAudioPort(&port);
5133 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5134 _aidl_return->push_back(std::move(aidlPort));
5135 return OK;
5136 };
5137
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005138 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005139 for (const auto& dev : module->getDeclaredDevices()) {
5140 if (role == media::AudioPortRole::NONE ||
5141 ((role == media::AudioPortRole::SOURCE)
5142 == audio_is_input_device(dev->type()))) {
5143 RETURN_STATUS_IF_ERROR(pushPort(dev));
5144 }
5145 }
5146 }
5147 return OK;
5148}
5149
jiabin19cdba52020-11-24 11:28:58 -08005150status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005151{
Eric Laurent99fcae42018-05-17 16:59:18 -07005152 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5153 return BAD_VALUE;
5154 }
5155 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5156 if (dev != 0) {
5157 dev->toAudioPort(port);
5158 return NO_ERROR;
5159 }
5160 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5161 if (dev != 0) {
5162 dev->toAudioPort(port);
5163 return NO_ERROR;
5164 }
5165 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5166 if (out != 0) {
5167 out->toAudioPort(port);
5168 return NO_ERROR;
5169 }
5170 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5171 if (in != 0) {
5172 in->toAudioPort(port);
5173 return NO_ERROR;
5174 }
5175 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005176}
5177
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005178status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5179 audio_patch_handle_t *handle,
5180 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005181{
François Gaffieafd4cea2019-11-18 15:50:22 +01005182 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005183 if (handle == NULL || patch == NULL) {
5184 return BAD_VALUE;
5185 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005186 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005187 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005188 return BAD_VALUE;
5189 }
5190 // only one source per audio patch supported for now
5191 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005192 return INVALID_OPERATION;
5193 }
Eric Laurent874c42872014-08-08 15:13:39 -07005194 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005195 return INVALID_OPERATION;
5196 }
Eric Laurent874c42872014-08-08 15:13:39 -07005197 for (size_t i = 0; i < patch->num_sinks; i++) {
5198 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5199 return INVALID_OPERATION;
5200 }
5201 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005202
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005203 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5204 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5205 if (srcDevice == nullptr || sinkDevice == nullptr) {
5206 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5207 return BAD_VALUE;
5208 }
5209 ALOGV("%s between source %s and sink %s", __func__,
5210 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5211 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5212 // Default attributes, default volume priority, not to infer with non raw audio patches.
5213 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5214 const struct audio_port_config *source = &patch->sources[0];
5215 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005216 new SourceClientDescriptor(
5217 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5218 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005219 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005220 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005221
5222 status_t status =
5223 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5224
5225 if (status != NO_ERROR) {
5226 return INVALID_OPERATION;
5227 }
5228 mAudioSources.add(portId, sourceDesc);
5229 return NO_ERROR;
5230}
5231
5232status_t AudioPolicyManager::connectAudioSourceToSink(
5233 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5234 const struct audio_patch *patch,
5235 audio_patch_handle_t &handle,
5236 uid_t uid, uint32_t delayMs)
5237{
5238 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5239 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5240 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5241 return INVALID_OPERATION;
5242 }
5243 sourceDesc->connect(handle, sinkDevice);
5244 if (isMsdPatch(handle)) {
5245 return NO_ERROR;
5246 }
5247 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5248 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5249 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5250 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5251 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5252 goto FailurePatchAdded;
5253 }
5254 status = swOutput->start();
5255 if (status != NO_ERROR) {
5256 goto FailureSourceAdded;
5257 }
5258 swOutput->addClient(sourceDesc);
5259 status = startSource(swOutput, sourceDesc, &delayMs);
5260 if (status != NO_ERROR) {
5261 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5262 goto FailureSourceActive;
5263 }
5264 if (delayMs != 0) {
5265 usleep(delayMs * 1000);
5266 }
5267 return NO_ERROR;
5268
5269FailureSourceActive:
5270 swOutput->stop();
5271 releaseOutput(sourceDesc->portId());
5272FailureSourceAdded:
5273 sourceDesc->setSwOutput(nullptr);
5274FailurePatchAdded:
5275 releaseAudioPatchInternal(handle);
5276 return INVALID_OPERATION;
5277}
5278
5279status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5280 audio_patch_handle_t *handle,
5281 uid_t uid, uint32_t delayMs,
5282 const sp<SourceClientDescriptor>& sourceDesc)
5283{
5284 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005285 sp<AudioPatch> patchDesc;
5286 ssize_t index = mAudioPatches.indexOfKey(*handle);
5287
François Gaffieafd4cea2019-11-18 15:50:22 +01005288 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5289 patch->sources[0].role,
5290 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005291#if LOG_NDEBUG == 0
5292 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005293 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5294 patch->sinks[i].role,
5295 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005296 }
5297#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005298
5299 if (index >= 0) {
5300 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005301 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5302 __func__, mUidCached, patchDesc->getUid(), uid);
5303 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005304 return INVALID_OPERATION;
5305 }
5306 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005307 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005308 }
5309
5310 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005311 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005312 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005313 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005314 return BAD_VALUE;
5315 }
Eric Laurent84c70242014-06-23 08:46:27 -07005316 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5317 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005318 if (patchDesc != 0) {
5319 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005320 ALOGV("%s source id differs for patch current id %d new id %d",
5321 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005322 return BAD_VALUE;
5323 }
5324 }
Eric Laurent874c42872014-08-08 15:13:39 -07005325 DeviceVector devices;
5326 for (size_t i = 0; i < patch->num_sinks; i++) {
5327 // Only support mix to devices connection
5328 // TODO add support for mix to mix connection
5329 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005330 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005331 return INVALID_OPERATION;
5332 }
5333 sp<DeviceDescriptor> devDesc =
5334 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5335 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005336 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005337 return BAD_VALUE;
5338 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005339
jiabin66acc432024-02-06 00:57:36 +00005340 if (outputDesc->mProfile->getCompatibilityScore(
5341 DeviceVector(devDesc),
5342 patch->sources[0].sample_rate,
5343 nullptr, // updatedSamplingRate
5344 patch->sources[0].format,
5345 nullptr, // updatedFormat
5346 patch->sources[0].channel_mask,
5347 nullptr, // updatedChannelMask
5348 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005349 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005350 return INVALID_OPERATION;
5351 }
5352 devices.add(devDesc);
5353 }
5354 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005355 return INVALID_OPERATION;
5356 }
Eric Laurent874c42872014-08-08 15:13:39 -07005357
Eric Laurent6a94d692014-05-20 11:18:06 -07005358 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005359 ALOGV("%s setting device %s on output %d",
5360 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305361 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005362 index = mAudioPatches.indexOfKey(*handle);
5363 if (index >= 0) {
5364 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005365 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005366 }
5367 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005368 patchDesc->setUid(uid);
5369 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005370 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005371 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005372 return INVALID_OPERATION;
5373 }
5374 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5375 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5376 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005377 // only one sink supported when connecting an input device to a mix
5378 if (patch->num_sinks > 1) {
5379 return INVALID_OPERATION;
5380 }
François Gaffie53615e22015-03-19 09:24:12 +01005381 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005382 if (inputDesc == NULL) {
5383 return BAD_VALUE;
5384 }
5385 if (patchDesc != 0) {
5386 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5387 return BAD_VALUE;
5388 }
5389 }
François Gaffie11d30102018-11-02 16:09:09 +01005390 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005391 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005392 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005393 return BAD_VALUE;
5394 }
5395
jiabin66acc432024-02-06 00:57:36 +00005396 if (inputDesc->mProfile->getCompatibilityScore(
5397 DeviceVector(device),
5398 patch->sinks[0].sample_rate,
5399 nullptr, /*updatedSampleRate*/
5400 patch->sinks[0].format,
5401 nullptr, /*updatedFormat*/
5402 patch->sinks[0].channel_mask,
5403 nullptr, /*updatedChannelMask*/
5404 // FIXME for the parameter type,
5405 // and the NONE
5406 (audio_output_flags_t)
5407 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005408 return INVALID_OPERATION;
5409 }
5410 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005411 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005412 device->toString().c_str(), inputDesc->mIoHandle);
5413 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005414 index = mAudioPatches.indexOfKey(*handle);
5415 if (index >= 0) {
5416 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005417 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005418 }
5419 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005420 patchDesc->setUid(uid);
5421 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005422 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005423 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005424 return INVALID_OPERATION;
5425 }
5426 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5427 // device to device connection
5428 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005429 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005430 return BAD_VALUE;
5431 }
5432 }
François Gaffie11d30102018-11-02 16:09:09 +01005433 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005434 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005435 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005436 return BAD_VALUE;
5437 }
Eric Laurent874c42872014-08-08 15:13:39 -07005438
Eric Laurent6a94d692014-05-20 11:18:06 -07005439 //update source and sink with our own data as the data passed in the patch may
5440 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005441 PatchBuilder patchBuilder;
5442 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005443
5444 // if first sink is to MSD, establish single MSD patch
5445 if (getMsdAudioOutDevices().contains(
5446 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5447 ALOGV("%s patching to MSD", __FUNCTION__);
5448 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5449 goto installPatch;
5450 }
5451
François Gaffieafd4cea2019-11-18 15:50:22 +01005452 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5453 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005454
Eric Laurent874c42872014-08-08 15:13:39 -07005455 for (size_t i = 0; i < patch->num_sinks; i++) {
5456 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005457 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005458 return INVALID_OPERATION;
5459 }
François Gaffie11d30102018-11-02 16:09:09 +01005460 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005461 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005462 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005463 return BAD_VALUE;
5464 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005465 audio_port_config sinkPortConfig = {};
5466 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5467 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005468
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005469 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5470 // volume management purpose (tracking activity)
5471 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5472 // in config XML to reach the sink so that is can be declared as available.
5473 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005474 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005475 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005476 // take care of dynamic routing for SwOutput selection,
5477 audio_attributes_t attributes = sourceDesc->attributes();
5478 audio_stream_type_t stream = sourceDesc->stream();
5479 audio_attributes_t resultAttr;
5480 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5481 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005482 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5483 config.channel_mask =
5484 (audio_channel_mask_get_representation(sourceMask)
5485 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5486 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005487 config.format = sourceDesc->config().format;
5488 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5489 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5490 bool isRequestedDeviceForExclusiveUse = false;
5491 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005492 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005493 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005494 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5495 &stream, sourceDesc->uid(), &config, &flags,
5496 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005497 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005498 if (output == AUDIO_IO_HANDLE_NONE) {
5499 ALOGV("%s no output for device %s",
5500 __FUNCTION__, sinkDevice->toString().c_str());
5501 return INVALID_OPERATION;
5502 }
5503 outputDesc = mOutputs.valueFor(output);
5504 if (outputDesc->isDuplicated()) {
5505 ALOGE("%s output is duplicated", __func__);
5506 return INVALID_OPERATION;
5507 }
François Gaffie7e39df22022-04-26 12:48:49 +02005508 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5509 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005510 } else {
5511 // Same for "raw patches" aka created from createAudioPatch API
5512 SortedVector<audio_io_handle_t> outputs =
5513 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5514 // if the sink device is reachable via an opened output stream, request to
5515 // go via this output stream by adding a second source to the patch
5516 // description
5517 output = selectOutput(outputs);
5518 if (output == AUDIO_IO_HANDLE_NONE) {
5519 ALOGE("%s no output available for internal patch sink", __func__);
5520 return INVALID_OPERATION;
5521 }
5522 outputDesc = mOutputs.valueFor(output);
5523 if (outputDesc->isDuplicated()) {
5524 ALOGV("%s output for device %s is duplicated",
5525 __func__, sinkDevice->toString().c_str());
5526 return INVALID_OPERATION;
5527 }
François Gaffie7e39df22022-04-26 12:48:49 +02005528 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005529 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005530 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005531 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005532 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005533 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005534 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5535 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005536 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5537 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005538 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005539 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005540 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005541 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005542 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005543 return INVALID_OPERATION;
5544 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005545 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005546 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005547 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005548 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005549 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005550 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005551 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005552 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5553 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005554 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005555 }
Eric Laurent83b88082014-06-20 18:31:16 -07005556 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005557 }
5558 // TODO: check from routing capabilities in config file and other conflicting patches
5559
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005560installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005561 status_t status = installPatch(
5562 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005563 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005564 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005565 return INVALID_OPERATION;
5566 }
5567 } else {
5568 return BAD_VALUE;
5569 }
5570 } else {
5571 return BAD_VALUE;
5572 }
5573 return NO_ERROR;
5574}
5575
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005576status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005577{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005578 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005579 ssize_t index = mAudioPatches.indexOfKey(handle);
5580
5581 if (index < 0) {
5582 return BAD_VALUE;
5583 }
5584 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005585 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5586 __func__, mUidCached, patchDesc->getUid(), uid);
5587 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005588 return INVALID_OPERATION;
5589 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005590 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5591 for (size_t i = 0; i < mAudioSources.size(); i++) {
5592 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5593 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5594 portId = sourceDesc->portId();
5595 break;
5596 }
5597 }
5598 return portId != AUDIO_PORT_HANDLE_NONE ?
5599 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005600}
Eric Laurent6a94d692014-05-20 11:18:06 -07005601
François Gaffieafd4cea2019-11-18 15:50:22 +01005602status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005603 uint32_t delayMs,
5604 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005605{
5606 ALOGV("%s patch %d", __func__, handle);
5607 if (mAudioPatches.indexOfKey(handle) < 0) {
5608 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5609 return BAD_VALUE;
5610 }
5611 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005612 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005613 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005614 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005615 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005616 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005617 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005618 return BAD_VALUE;
5619 }
5620
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305621 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005622 getNewOutputDevices(outputDesc, true /*fromCache*/),
5623 true,
5624 0,
5625 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005626 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5627 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005628 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005629 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005630 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005631 return BAD_VALUE;
5632 }
5633 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005634 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005635 true,
5636 NULL);
5637 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005638 status_t status =
5639 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5640 ALOGV("%s patch panel returned %d patchHandle %d",
5641 __func__, status, patchDesc->getAfHandle());
5642 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005643 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005644 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005645 // SW or HW Bridge
5646 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5647 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005648 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005649 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5650 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5651 outputDesc = sourceDesc->swOutput().promote();
5652 }
5653 if (outputDesc == nullptr) {
5654 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5655 // releaseOutput has already called closeOutput in case of direct output
5656 return NO_ERROR;
5657 }
François Gaffie7e39df22022-04-26 12:48:49 +02005658 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005659 // While using a HwBridge, force reconsidering device only if not reusing an existing
5660 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005661 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005662 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5663 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5664 // Reconsider device only for cases:
5665 // 1 / Active Output
5666 // 2 / Inactive Output previously hosting HwBridge
5667 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5668 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5669 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305670 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005671 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5672 outputDesc->devices(),
5673 force,
5674 0,
5675 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005676 } else {
5677 return BAD_VALUE;
5678 }
5679 } else {
5680 return BAD_VALUE;
5681 }
5682 return NO_ERROR;
5683}
5684
5685status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5686 struct audio_patch *patches,
5687 unsigned int *generation)
5688{
François Gaffie53615e22015-03-19 09:24:12 +01005689 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005690 return BAD_VALUE;
5691 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005692 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005693 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005694}
5695
Eric Laurente1715a42014-05-20 11:30:42 -07005696status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005697{
Eric Laurente1715a42014-05-20 11:30:42 -07005698 ALOGV("setAudioPortConfig()");
5699
5700 if (config == NULL) {
5701 return BAD_VALUE;
5702 }
5703 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5704 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005705 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5706 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005707 }
5708
Eric Laurenta121f902014-06-03 13:32:54 -07005709 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005710 if (config->type == AUDIO_PORT_TYPE_MIX) {
5711 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005712 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005713 if (outputDesc == NULL) {
5714 return BAD_VALUE;
5715 }
Eric Laurent84c70242014-06-23 08:46:27 -07005716 ALOG_ASSERT(!outputDesc->isDuplicated(),
5717 "setAudioPortConfig() called on duplicated output %d",
5718 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005719 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005720 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005721 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005722 if (inputDesc == NULL) {
5723 return BAD_VALUE;
5724 }
Eric Laurenta121f902014-06-03 13:32:54 -07005725 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005726 } else {
5727 return BAD_VALUE;
5728 }
5729 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5730 sp<DeviceDescriptor> deviceDesc;
5731 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5732 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5733 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5734 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5735 } else {
5736 return BAD_VALUE;
5737 }
5738 if (deviceDesc == NULL) {
5739 return BAD_VALUE;
5740 }
Eric Laurenta121f902014-06-03 13:32:54 -07005741 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005742 } else {
5743 return BAD_VALUE;
5744 }
5745
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005746 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005747 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5748 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005749 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005750 audioPortConfig->toAudioPortConfig(&newConfig, config);
5751 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005752 }
Eric Laurenta121f902014-06-03 13:32:54 -07005753 if (status != NO_ERROR) {
5754 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005755 }
Eric Laurente1715a42014-05-20 11:30:42 -07005756
5757 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005758}
5759
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005760void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5761{
Eric Laurentd60560a2015-04-10 11:31:20 -07005762 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005763 clearAudioPatches(uid);
5764 clearSessionRoutes(uid);
5765}
5766
Eric Laurent6a94d692014-05-20 11:18:06 -07005767void AudioPolicyManager::clearAudioPatches(uid_t uid)
5768{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005769 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005770 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005771 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005772 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005773 }
5774 }
5775}
5776
François Gaffiec005e562018-11-06 15:04:49 +01005777void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005778{
François Gaffiec005e562018-11-06 15:04:49 +01005779 // Take the first attributes following the product strategy as it is used to retrieve the routed
5780 // device. All attributes wihin a strategy follows the same "routing strategy"
5781 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5782 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005783 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005784 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005785 for (size_t j = 0; j < mOutputs.size(); j++) {
5786 if (mOutputs.keyAt(j) == ouptutToSkip) {
5787 continue;
5788 }
5789 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005790 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005791 continue;
5792 }
5793 // If the default device for this strategy is on another output mix,
5794 // invalidate all tracks in this strategy to force re connection.
5795 // Otherwise select new device on the output mix.
5796 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005797 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005798 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005799 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005800 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005801 // If the device is using preferred mixer attributes, the output need to reopen
5802 // with default configuration when the new selected devices are different from
5803 // current routing devices.
5804 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5805 continue;
5806 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305807 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005808 }
5809 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005810 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005811}
5812
5813void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5814{
5815 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005816 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005817 for (size_t i = 0; i < mOutputs.size(); i++) {
5818 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005819 for (const auto& client : outputDesc->getClientIterable()) {
5820 if (client->hasPreferredDevice() && client->uid() == uid) {
5821 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005822 auto clientStrategy = client->strategy();
5823 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5824 end(affectedStrategies)) {
5825 continue;
5826 }
5827 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005828 }
5829 }
5830 }
5831 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005832 for (const auto& strategy : affectedStrategies) {
5833 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005834 }
5835
5836 // remove input routes associated with this uid
5837 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005838 for (size_t i = 0; i < mInputs.size(); i++) {
5839 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005840 for (const auto& client : inputDesc->getClientIterable()) {
5841 if (client->hasPreferredDevice() && client->uid() == uid) {
5842 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5843 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005844 }
5845 }
5846 }
5847 // reroute inputs if necessary
5848 SortedVector<audio_io_handle_t> inputsToClose;
5849 for (size_t i = 0; i < mInputs.size(); i++) {
5850 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005851 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005852 inputsToClose.add(inputDesc->mIoHandle);
5853 }
5854 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005855 for (const auto& input : inputsToClose) {
5856 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005857 }
5858}
5859
Eric Laurentd60560a2015-04-10 11:31:20 -07005860void AudioPolicyManager::clearAudioSources(uid_t uid)
5861{
5862 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005863 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5864 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005865 stopAudioSource(mAudioSources.keyAt(i));
5866 }
5867 }
5868}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005869
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005870status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5871 audio_io_handle_t *ioHandle,
5872 audio_devices_t *device)
5873{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005874 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5875 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005876 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005877 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5878 if (deviceDesc == nullptr) {
5879 return INVALID_OPERATION;
5880 }
5881 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005882
François Gaffiedf372692015-03-19 10:43:27 +01005883 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005884}
5885
Eric Laurentd60560a2015-04-10 11:31:20 -07005886status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005887 const audio_attributes_t *attributes,
5888 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005889 uid_t uid) {
5890 return startAudioSourceInternal(source, attributes, portId, uid,
5891 false /*internal*/, false /*isCallRx*/);
5892}
5893
5894status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5895 const audio_attributes_t *attributes,
5896 audio_port_handle_t *portId,
5897 uid_t uid, bool internal, bool isCallRx)
Eric Laurent554a2772015-04-10 11:29:24 -07005898{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005899 ALOGV("%s", __FUNCTION__);
5900 *portId = AUDIO_PORT_HANDLE_NONE;
5901
5902 if (source == NULL || attributes == NULL || portId == NULL) {
5903 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5904 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005905 return BAD_VALUE;
5906 }
5907
Eric Laurentd60560a2015-04-10 11:31:20 -07005908 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5909 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005910 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5911 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005912 return INVALID_OPERATION;
5913 }
5914
François Gaffie11d30102018-11-02 16:09:09 +01005915 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005916 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005917 String8(source->ext.device.address),
5918 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005919 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005920 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005921 return BAD_VALUE;
5922 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005923
jiabin4ef93452019-09-10 14:29:54 -07005924 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005925
François Gaffieaaac0fd2018-11-22 17:56:39 +01005926 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005927 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005928 mEngine->getStreamTypeForAttributes(*attributes),
5929 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005930 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005931
5932 status_t status = connectAudioSource(sourceDesc);
5933 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005934 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005935 }
5936 return status;
5937}
5938
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005939status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005940{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005941 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005942
5943 // make sure we only have one patch per source.
5944 disconnectAudioSource(sourceDesc);
5945
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005946 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005947 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5948 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5949 sourceDesc->srcDevice()->type(),
5950 String8(sourceDesc->srcDevice()->address().c_str()),
5951 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005952 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005953 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005954 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005955 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005956 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5957 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5958 return INVALID_OPERATION;
5959 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005960 PatchBuilder patchBuilder;
5961 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5962 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005963
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005964 return connectAudioSourceToSink(
5965 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005966}
5967
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005968status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005969{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005970 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5971 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005972 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005973 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005974 return BAD_VALUE;
5975 }
5976 status_t status = disconnectAudioSource(sourceDesc);
5977
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005978 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005979 return status;
5980}
5981
Andy Hung2ddee192015-12-18 17:34:44 -08005982status_t AudioPolicyManager::setMasterMono(bool mono)
5983{
5984 if (mMasterMono == mono) {
5985 return NO_ERROR;
5986 }
5987 mMasterMono = mono;
5988 // if enabling mono we close all offloaded devices, which will invalidate the
5989 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5990 // for recreating the new AudioTrack as non-offloaded PCM.
5991 //
5992 // If disabling mono, we leave all tracks as is: we don't know which clients
5993 // and tracks are able to be recreated as offloaded. The next "song" should
5994 // play back offloaded.
5995 if (mMasterMono) {
5996 Vector<audio_io_handle_t> offloaded;
5997 for (size_t i = 0; i < mOutputs.size(); ++i) {
5998 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5999 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6000 offloaded.push(desc->mIoHandle);
6001 }
6002 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006003 for (const auto& handle : offloaded) {
6004 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006005 }
6006 }
6007 // update master mono for all remaining outputs
6008 for (size_t i = 0; i < mOutputs.size(); ++i) {
6009 updateMono(mOutputs.keyAt(i));
6010 }
6011 return NO_ERROR;
6012}
6013
6014status_t AudioPolicyManager::getMasterMono(bool *mono)
6015{
6016 *mono = mMasterMono;
6017 return NO_ERROR;
6018}
6019
Eric Laurentac9cef52017-06-09 15:46:26 -07006020float AudioPolicyManager::getStreamVolumeDB(
6021 audio_stream_type_t stream, int index, audio_devices_t device)
6022{
Vlad Popa9d482762024-06-21 16:40:23 -07006023 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6024 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006025}
6026
jiabin81772902018-04-02 17:52:27 -07006027status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6028 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006029 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006030{
Kriti Dang6537def2021-03-02 13:46:59 +01006031 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6032 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006033 return BAD_VALUE;
6034 }
Kriti Dang6537def2021-03-02 13:46:59 +01006035 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6036 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006037
6038 size_t formatsWritten = 0;
6039 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006040
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006041 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006042 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6043 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006044 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006045 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006046 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006047 bool formatEnabled = true;
6048 switch (forceUse) {
6049 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006050 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006051 break;
6052 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6053 formatEnabled = false;
6054 break;
6055 default: // AUTO or ALWAYS => true
6056 break;
jiabin81772902018-04-02 17:52:27 -07006057 }
6058 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6059 }
jiabin81772902018-04-02 17:52:27 -07006060 }
6061 return NO_ERROR;
6062}
6063
Kriti Dang6537def2021-03-02 13:46:59 +01006064status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6065 audio_format_t *surroundFormats) {
6066 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6067 return BAD_VALUE;
6068 }
6069 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6070 __func__, *numSurroundFormats, surroundFormats);
6071
6072 size_t formatsWritten = 0;
6073 size_t formatsMax = *numSurroundFormats;
6074 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6075
6076 // Return formats from all device profiles that have already been resolved by
6077 // checkOutputsForDevice().
6078 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6079 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6080 audio_devices_t deviceType = device->type();
6081 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6082 // returns formats reported by HDMI devices.
6083 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
6084 continue;
6085 }
6086 // Formats reported by sink devices
6087 std::unordered_set<audio_format_t> formatset;
6088 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6089 formatset.insert(it->second.begin(), it->second.end());
6090 }
6091
6092 // Formats hard-coded in the in policy configuration file (if any).
6093 FormatVector encodedFormats = device->encodedFormats();
6094 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6095 // Filter the formats which are supported by the vendor hardware.
6096 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006097 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006098 formats.insert(*it);
6099 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006100 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006101 if (pair.second.count(*it) != 0) {
6102 formats.insert(pair.first);
6103 break;
6104 }
6105 }
6106 }
6107 }
6108 }
6109 *numSurroundFormats = formats.size();
6110 for (const auto& format: formats) {
6111 if (formatsWritten < formatsMax) {
6112 surroundFormats[formatsWritten++] = format;
6113 }
6114 }
6115 return NO_ERROR;
6116}
6117
jiabin81772902018-04-02 17:52:27 -07006118status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6119{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006120 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006121 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6122 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006123 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006124 return BAD_VALUE;
6125 }
6126
Mikhail Naganov100f0122018-11-29 11:22:16 -08006127 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6128 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006129 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006130 return INVALID_OPERATION;
6131 }
6132
Mikhail Naganov100f0122018-11-29 11:22:16 -08006133 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006134 return NO_ERROR;
6135 }
6136
Mikhail Naganov100f0122018-11-29 11:22:16 -08006137 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006138 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006139 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006140 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006141 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006142 }
6143 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006144 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006145 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006146 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006147 }
6148 }
6149
6150 sp<SwAudioOutputDescriptor> outputDesc;
6151 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006152 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6153 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006154 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6155 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006156 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006157 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006158 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6159 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6160 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006161 name.c_str(),
6162 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006163 if (status != NO_ERROR) {
6164 continue;
6165 }
6166 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6167 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6168 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006169 name.c_str(),
6170 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006171 profileUpdated |= (status == NO_ERROR);
6172 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006173 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006174 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006175 AUDIO_DEVICE_IN_HDMI);
6176 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6177 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006178 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006179 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006180 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6181 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6182 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006183 name.c_str(),
6184 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006185 if (status != NO_ERROR) {
6186 continue;
6187 }
6188 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6189 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6190 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006191 name.c_str(),
6192 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006193 profileUpdated |= (status == NO_ERROR);
6194 }
6195
jiabin81772902018-04-02 17:52:27 -07006196 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006197 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006198 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006199 }
6200
6201 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6202}
6203
Eric Laurent5ada82e2019-08-29 17:53:54 -07006204void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006205{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006206 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006207 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006208 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006209 }
6210}
6211
jiabin6012f912018-11-02 17:06:30 -07006212bool AudioPolicyManager::isHapticPlaybackSupported()
6213{
6214 for (const auto& hwModule : mHwModules) {
6215 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6216 for (const auto &outProfile : outputProfiles) {
6217 struct audio_port audioPort;
6218 outProfile->toAudioPort(&audioPort);
6219 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6220 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6221 return true;
6222 }
6223 }
6224 }
6225 }
6226 return false;
6227}
6228
Carter Hsu325a8eb2022-01-19 19:56:51 +08006229bool AudioPolicyManager::isUltrasoundSupported()
6230{
6231 bool hasUltrasoundOutput = false;
6232 bool hasUltrasoundInput = false;
6233 for (const auto& hwModule : mHwModules) {
6234 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6235 if (!hasUltrasoundOutput) {
6236 for (const auto &outProfile : outputProfiles) {
6237 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6238 hasUltrasoundOutput = true;
6239 break;
6240 }
6241 }
6242 }
6243
6244 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6245 if (!hasUltrasoundInput) {
6246 for (const auto &inputProfile : inputProfiles) {
6247 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6248 hasUltrasoundInput = true;
6249 break;
6250 }
6251 }
6252 }
6253
6254 if (hasUltrasoundOutput && hasUltrasoundInput)
6255 return true;
6256 }
6257 return false;
6258}
6259
Atneya Nair698f5ef2022-12-15 16:15:09 -08006260bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6261{
6262 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6263 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6264 for (const auto& hwModule : mHwModules) {
6265 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6266 for (const auto &inputProfile : inputProfiles) {
6267 if ((inputProfile->getFlags() & mask) == mask) {
6268 return true;
6269 }
6270 }
6271 }
6272 return false;
6273}
6274
Eric Laurent8340e672019-11-06 11:01:08 -08006275bool AudioPolicyManager::isCallScreenModeSupported()
6276{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006277 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006278}
6279
6280
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006281status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006282{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006283 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006284 if (!sourceDesc->isConnected()) {
6285 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6286 return NO_ERROR;
6287 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006288 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6289 if (swOutput != 0) {
6290 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006291 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006292 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006293 }
jiabinbce0c1d2020-10-05 11:20:18 -07006294 if (releaseOutput(sourceDesc->portId())) {
6295 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6296 // no need to release audio patch here but just return NO_ERROR.
6297 return NO_ERROR;
6298 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006299 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006300 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006301 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006302 // close Hwoutput and remove from mHwOutputs
6303 } else {
6304 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6305 }
6306 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006307 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006308 sourceDesc->disconnect();
6309 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006310}
6311
François Gaffiec005e562018-11-06 15:04:49 +01006312sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6313 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006314{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006315 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006316 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006317 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006318 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006319 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6320 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006321 source = sourceDesc;
6322 break;
6323 }
6324 }
6325 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006326}
6327
Eric Laurentb4f42a92022-01-17 17:37:31 +01006328bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006329 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006330 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006331{
6332 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6333 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006334 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006335 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006336 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6337 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6338 return false;
6339 }
6340 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6341 return false;
6342 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006343 }
6344
Eric Laurentd332bc82023-08-04 11:45:23 +02006345 // The caller can have the audio config criteria ignored by either passing a null ptr or
6346 // the AUDIO_CONFIG_INITIALIZER value.
6347 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006348 // some positional channel masks and PCM format and for stereo if low latency performance
6349 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006350
6351 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006352 static const bool stereo_spatialization_enabled =
6353 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006354 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006355 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006356 ? audio_channel_mask_contains_stereo(config->channel_mask)
6357 : audio_is_channel_mask_spatialized(config->channel_mask);
6358 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006359 return false;
6360 }
6361 if (!audio_is_linear_pcm(config->format)) {
6362 return false;
6363 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006364 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6365 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6366 return false;
6367 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006368 }
6369
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006370 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006371 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006372 if (profile == nullptr) {
6373 return false;
6374 }
6375
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006376 return true;
6377}
6378
Shunkai Yao4c3af932024-04-26 04:12:21 +00006379// The Spatializer output is compatible with Haptic use cases if:
6380// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6381// with client if client haptic channel bits were set, or
6382// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6383// including the haptic bits or creating the HapticGenerator effect for same session.
6384bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6385 const audio_config_t* config, audio_session_t sessionId) const {
6386 const auto clientHapticChannel =
6387 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6388 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6389 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6390
6391 if (threadOutputHapticChannel) {
6392 // check format and sampleRate match if client haptic channel mask exist
6393 if (clientHapticChannel) {
6394 return mSpatializerOutput->getFormat() == config->format &&
6395 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6396 }
6397 return true;
6398 } else {
6399 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6400 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6401 // HapticGenerator effect for this session) are not supported.
6402 return clientHapticChannel == 0 &&
6403 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6404 }
6405}
6406
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006407void AudioPolicyManager::checkVirtualizerClientRoutes() {
6408 std::set<audio_stream_type_t> streamsToInvalidate;
6409 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006410 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6411 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006412 audio_attributes_t attr = client->attributes();
6413 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6414 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6415 audio_config_base_t clientConfig = client->config();
6416 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006417 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006418 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006419 streamsToInvalidate.insert(client->stream());
6420 }
6421 }
6422 }
6423
jiabinc44b3462022-12-08 12:52:31 -08006424 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006425}
6426
Eric Laurente191d1b2022-04-15 11:59:25 +02006427
6428bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6429 const sp<SwAudioOutputDescriptor>& outputDesc) {
6430 if (outputDesc->isDuplicated()) {
6431 return false;
6432 }
6433 DeviceVector devices = outputDesc->supportedDevices();
6434 for (size_t i = 0; i < mOutputs.size(); i++) {
6435 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6436 if (desc == outputDesc || desc->isDuplicated()) {
6437 continue;
6438 }
6439 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6440 if (!sharedDevices.isEmpty()
6441 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6442 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6443 return false;
6444 }
6445 }
6446 return true;
6447}
6448
6449
Eric Laurentfa0f6742021-08-17 18:39:44 +02006450status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006451 const audio_attributes_t *attr,
6452 audio_io_handle_t *output) {
6453 *output = AUDIO_IO_HANDLE_NONE;
6454
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006455 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6456 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6457 audio_config_t *configPtr = nullptr;
6458 audio_config_t config;
6459 if (mixerConfig != nullptr) {
6460 config = audio_config_initializer(mixerConfig);
6461 configPtr = &config;
6462 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006463 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006464 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006465 return BAD_VALUE;
6466 }
6467
6468 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006469 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006470 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006471 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006472 return BAD_VALUE;
6473 }
6474
Eric Laurente191d1b2022-04-15 11:59:25 +02006475 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006476 for (size_t i = 0; i < mOutputs.size(); i++) {
6477 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006478 if (!desc->isDuplicated()
6479 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6480 spatializerOutputs.push_back(desc);
6481 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006482 }
6483 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006484 mSpatializerOutput.clear();
6485 bool outputsChanged = false;
6486 for (const auto& desc : spatializerOutputs) {
6487 if (desc->mProfile == profile
6488 && (configPtr == nullptr
6489 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6490 mSpatializerOutput = desc;
6491 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6492 } else {
6493 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6494 " and devices %s", __func__, desc->mIoHandle,
6495 configPtr != nullptr ? configPtr->channel_mask : 0,
6496 devices.toString().c_str());
6497 closeOutput(desc->mIoHandle);
6498 outputsChanged = true;
6499 }
Eric Laurent39095982021-08-24 18:29:27 +02006500 }
6501
Eric Laurente191d1b2022-04-15 11:59:25 +02006502 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006503 sp<SwAudioOutputDescriptor> desc =
6504 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006505 if (desc != nullptr) {
6506 mSpatializerOutput = desc;
6507 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006508 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006509 }
6510
6511 checkVirtualizerClientRoutes();
6512
Eric Laurente191d1b2022-04-15 11:59:25 +02006513 if (outputsChanged) {
6514 mPreviousOutputs = mOutputs;
6515 mpClientInterface->onAudioPortListUpdate();
6516 }
6517
6518 if (mSpatializerOutput == nullptr) {
6519 ALOGV("%s could not open spatializer output with requested config", __func__);
6520 return BAD_VALUE;
6521 }
Eric Laurent39095982021-08-24 18:29:27 +02006522 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006523 ALOGV("%s returning new spatializer output %d", __func__, *output);
6524 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006525}
6526
Eric Laurentfa0f6742021-08-17 18:39:44 +02006527status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6528 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006529 return INVALID_OPERATION;
6530 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006531 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006532 return BAD_VALUE;
6533 }
Eric Laurent39095982021-08-24 18:29:27 +02006534
Eric Laurente191d1b2022-04-15 11:59:25 +02006535 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6536 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6537 closeOutput(mSpatializerOutput->mIoHandle);
6538 //from now on mSpatializerOutput is null
6539 checkVirtualizerClientRoutes();
6540 }
Eric Laurent39095982021-08-24 18:29:27 +02006541
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006542 return NO_ERROR;
6543}
6544
Eric Laurente552edb2014-03-10 17:42:56 -07006545// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006546// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006547// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006548uint32_t AudioPolicyManager::nextAudioPortGeneration()
6549{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006550 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006551}
6552
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006553AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006554 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006555 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006556 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006557 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006558 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006559 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006560 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006561 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006562 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006563 mAudioPortGeneration(1),
6564 mBeaconMuteRefCount(0),
6565 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006566 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006567 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006568 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006569 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006570{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006571}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006572
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006573status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006574 if (mEngine == nullptr) {
6575 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006576 }
6577 mEngine->setObserver(this);
6578 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006579 if (status != NO_ERROR) {
6580 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6581 return status;
6582 }
François Gaffie2110e042015-03-24 08:41:51 +01006583
jiabin29230182023-04-04 21:02:36 +00006584 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6585 // at the end of this function.
6586 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006587 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6588 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6589
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006590 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006591 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006592 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006593
Eric Laurent3a4311c2014-03-17 12:00:47 -07006594 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006595 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6596 defaultOutputDevice == nullptr ||
6597 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6598 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6599 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006600 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006601 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006602 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006603
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006604 // Silence ALOGV statements
6605 property_set("log.tag." LOG_TAG, "D");
6606
Eric Laurente552edb2014-03-10 17:42:56 -07006607 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006608 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006609}
6610
Eric Laurente0720872014-03-11 09:30:41 -07006611AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006612{
Eric Laurente552edb2014-03-10 17:42:56 -07006613 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006614 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006615 }
6616 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006617 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006618 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006619 mAvailableOutputDevices.clear();
6620 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006621 mOutputs.clear();
6622 mInputs.clear();
6623 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006624 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006625 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006626}
6627
Eric Laurente0720872014-03-11 09:30:41 -07006628status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006629{
Eric Laurent87ffa392015-05-22 10:32:38 -07006630 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006631}
6632
Eric Laurente552edb2014-03-10 17:42:56 -07006633// ---
6634
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006635void AudioPolicyManager::onNewAudioModulesAvailable()
6636{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006637 DeviceVector newDevices;
6638 onNewAudioModulesAvailableInt(&newDevices);
6639 if (!newDevices.empty()) {
6640 nextAudioPortGeneration();
6641 mpClientInterface->onAudioPortListUpdate();
6642 }
6643}
6644
6645void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6646{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006647 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006648 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6649 continue;
6650 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006651 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006652 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6653 handle != AUDIO_MODULE_HANDLE_NONE) {
6654 hwModule->setHandle(handle);
6655 } else {
6656 ALOGW("could not load HW module %s", hwModule->getName());
6657 continue;
6658 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006659 }
6660 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006661 // open all output streams needed to access attached devices.
6662 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006663 // This also validates mAvailableOutputDevices list
6664 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6665 if (!outProfile->canOpenNewIo()) {
6666 ALOGE("Invalid Output profile max open count %u for profile %s",
6667 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6668 continue;
6669 }
6670 if (!outProfile->hasSupportedDevices()) {
6671 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6672 continue;
6673 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006674 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6675 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006676 mTtsOutputAvailable = true;
6677 }
6678
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006679 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006680 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006681 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006682 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6683 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006684 } else {
6685 // choose first device present in profile's SupportedDevices also part of
6686 // mAvailableOutputDevices.
6687 if (availProfileDevices.isEmpty()) {
6688 continue;
6689 }
6690 supportedDevice = availProfileDevices.itemAt(0);
6691 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006692 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006693 continue;
6694 }
6695 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6696 mpClientInterface);
6697 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006698 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006699 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6700 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006701 AUDIO_STREAM_DEFAULT,
Haofan Wangf6e304f2024-07-09 23:06:58 -07006702 AUDIO_OUTPUT_FLAG_NONE, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006703 if (status != NO_ERROR) {
6704 ALOGW("Cannot open output stream for devices %s on hw module %s",
6705 supportedDevice->toString().c_str(), hwModule->getName());
6706 continue;
6707 }
6708 for (const auto &device : availProfileDevices) {
6709 // give a valid ID to an attached device once confirmed it is reachable
6710 if (!device->isAttached()) {
6711 device->attach(hwModule);
6712 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006713 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006714 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006715 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6716 }
6717 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006718 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006719 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6720 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006721 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006722 }
Eric Laurent39095982021-08-24 18:29:27 +02006723 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006724 outputDesc->close();
6725 } else {
6726 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306727 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006728 DeviceVector(supportedDevice),
6729 true,
6730 0,
6731 NULL);
6732 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006733 }
6734 // open input streams needed to access attached devices to validate
6735 // mAvailableInputDevices list
6736 for (const auto& inProfile : hwModule->getInputProfiles()) {
6737 if (!inProfile->canOpenNewIo()) {
6738 ALOGE("Invalid Input profile max open count %u for profile %s",
6739 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6740 continue;
6741 }
6742 if (!inProfile->hasSupportedDevices()) {
6743 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6744 continue;
6745 }
6746 // chose first device present in profile's SupportedDevices also part of
6747 // available input devices
6748 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006749 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006750 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006751 ALOGV("%s: Input device list is empty! for profile %s",
6752 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006753 continue;
6754 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00006755 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6756 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006757
6758 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6759 status_t status = inputDesc->open(nullptr,
6760 availProfileDevices.itemAt(0),
6761 AUDIO_SOURCE_MIC,
6762 AUDIO_INPUT_FLAG_NONE,
6763 &input);
6764 if (status != NO_ERROR) {
6765 ALOGW("Cannot open input stream for device %s on hw module %s",
6766 availProfileDevices.toString().c_str(),
6767 hwModule->getName());
6768 continue;
6769 }
6770 for (const auto &device : availProfileDevices) {
6771 // give a valid ID to an attached device once confirmed it is reachable
6772 if (!device->isAttached()) {
6773 device->attach(hwModule);
6774 device->importAudioPortAndPickAudioProfile(inProfile, true);
6775 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006776 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006777 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6778 }
6779 }
6780 inputDesc->close();
6781 }
6782 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006783
6784 // Check if spatializer outputs can be closed until used.
6785 // mOutputs vector never contains duplicated outputs at this point.
6786 std::vector<audio_io_handle_t> outputsClosed;
6787 for (size_t i = 0; i < mOutputs.size(); i++) {
6788 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6789 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6790 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6791 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006792 nextAudioPortGeneration();
6793 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6794 if (index >= 0) {
6795 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6796 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6797 patchDesc->getAfHandle(), 0);
6798 mAudioPatches.removeItemsAt(index);
6799 mpClientInterface->onAudioPatchListUpdate();
6800 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006801 desc->close();
6802 }
6803 }
6804 for (auto output : outputsClosed) {
6805 removeOutput(output);
6806 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006807}
6808
Eric Laurent98e38192018-02-15 18:31:53 -08006809void AudioPolicyManager::addOutput(audio_io_handle_t output,
6810 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006811{
Eric Laurent1c333e22014-05-20 10:48:17 -07006812 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006813 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006814 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006815 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006816 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006817}
6818
François Gaffie53615e22015-03-19 09:24:12 +01006819void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6820{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006821 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6822 ALOGV("%s: removing primary output", __func__);
6823 mPrimaryOutput = nullptr;
6824 }
François Gaffie53615e22015-03-19 09:24:12 +01006825 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006826 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006827}
6828
Eric Laurent98e38192018-02-15 18:31:53 -08006829void AudioPolicyManager::addInput(audio_io_handle_t input,
6830 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006831{
Eric Laurent1c333e22014-05-20 10:48:17 -07006832 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006833 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006834}
Eric Laurente552edb2014-03-10 17:42:56 -07006835
François Gaffie11d30102018-11-02 16:09:09 +01006836status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006837 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006838 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006839{
François Gaffie11d30102018-11-02 16:09:09 +01006840 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006841 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006842 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006843
François Gaffie11d30102018-11-02 16:09:09 +01006844 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006845 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006846 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006847 }
Eric Laurente552edb2014-03-10 17:42:56 -07006848
Eric Laurent3b73df72014-03-11 09:06:29 -07006849 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006850 // first call getAudioPort to get the supported attributes from the HAL
6851 struct audio_port_v7 port = {};
6852 device->toAudioPort(&port);
6853 status_t status = mpClientInterface->getAudioPort(&port);
6854 if (status == NO_ERROR) {
6855 device->importAudioPort(port);
6856 }
6857
6858 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006859 for (size_t i = 0; i < mOutputs.size(); i++) {
6860 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006861 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006862 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006863 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6864 mOutputs.keyAt(i), device->toString().c_str());
6865 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006866 }
6867 }
6868 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006869 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006870 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006871 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6872 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006873 if (profile->supportsDevice(device)) {
6874 profiles.add(profile);
6875 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6876 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006877 }
6878 }
6879 }
6880
Eric Laurent7b279bb2015-12-14 10:18:23 -08006881 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006882
Eric Laurente552edb2014-03-10 17:42:56 -07006883 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006884 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006885 return BAD_VALUE;
6886 }
6887
6888 // open outputs for matching profiles if needed. Direct outputs are also opened to
6889 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6890 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006891 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006892
6893 // nothing to do if one output is already opened for this profile
6894 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006895 for (j = 0; j < outputs.size(); j++) {
6896 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006897 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006898 // matching profile: save the sample rates, format and channel masks supported
6899 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006900 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006901 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006902 }
Eric Laurente552edb2014-03-10 17:42:56 -07006903 break;
6904 }
6905 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006906 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006907 continue;
6908 }
6909
Eric Laurent3974e3b2017-12-07 17:58:43 -08006910 if (!profile->canOpenNewIo()) {
6911 ALOGW("Max Output number %u already opened for this profile %s",
6912 profile->maxOpenCount, profile->getTagName().c_str());
6913 continue;
6914 }
6915
Eric Laurent83efe1c2017-07-09 16:51:08 -07006916 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006917 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006918 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6919 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006920 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006921 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006922 profiles.removeAt(profile_index);
6923 profile_index--;
6924 } else {
6925 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006926 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006927 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006928 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6929 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006930 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006931 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006932
François Gaffie11d30102018-11-02 16:09:09 +01006933 if (device_distinguishes_on_address(deviceType)) {
6934 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6935 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306936 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6937 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006938 }
Eric Laurente552edb2014-03-10 17:42:56 -07006939 ALOGV("checkOutputsForDevice(): adding output %d", output);
6940 }
6941 }
6942
6943 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006944 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006945 return BAD_VALUE;
6946 }
Eric Laurentd4692962014-05-05 18:13:44 -07006947 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006948 // check if one opened output is not needed any more after disconnecting one device
6949 for (size_t i = 0; i < mOutputs.size(); i++) {
6950 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006951 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006952 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006953 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006954 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006955 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006956 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006957 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6958 mOutputs.keyAt(i));
6959 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006960 }
Eric Laurente552edb2014-03-10 17:42:56 -07006961 }
6962 }
Eric Laurentd4692962014-05-05 18:13:44 -07006963 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006964 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006965 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6966 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006967 if (!profile->supportsDevice(device)) {
6968 continue;
6969 }
6970 ALOGV("checkOutputsForDevice(): "
6971 "clearing direct output profile %zu on module %s",
6972 j, hwModule->getName());
6973 profile->clearAudioProfiles();
6974 if (!profile->hasDynamicAudioProfile()) {
6975 continue;
6976 }
6977 // When a device is disconnected, if there is an IOProfile that contains dynamic
6978 // profiles and supports the disconnected device, call getAudioPort to repopulate
6979 // the capabilities of the devices that is supported by the IOProfile.
6980 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6981 if (supportedDevice == device ||
6982 !mAvailableOutputDevices.contains(supportedDevice)) {
6983 continue;
6984 }
6985 struct audio_port_v7 port;
6986 supportedDevice->toAudioPort(&port);
6987 status_t status = mpClientInterface->getAudioPort(&port);
6988 if (status == NO_ERROR) {
6989 supportedDevice->importAudioPort(port);
6990 }
Eric Laurente552edb2014-03-10 17:42:56 -07006991 }
6992 }
6993 }
6994 }
6995 return NO_ERROR;
6996}
6997
François Gaffie11d30102018-11-02 16:09:09 +01006998status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006999 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007000{
François Gaffie11d30102018-11-02 16:09:09 +01007001 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007002 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007003 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007004 }
7005
Eric Laurentd4692962014-05-05 18:13:44 -07007006 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007007 sp<AudioInputDescriptor> desc;
7008
jiabinbf5f4262023-04-12 21:48:34 +00007009 // first call getAudioPort to get the supported attributes from the HAL
7010 struct audio_port_v7 port = {};
7011 device->toAudioPort(&port);
7012 status_t status = mpClientInterface->getAudioPort(&port);
7013 if (status == NO_ERROR) {
7014 device->importAudioPort(port);
7015 }
7016
Eric Laurent0dd51852019-04-19 18:18:58 -07007017 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007018 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007019 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007020 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007021 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007022 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007023 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007024
François Gaffie11d30102018-11-02 16:09:09 +01007025 if (profile->supportsDevice(device)) {
7026 profiles.add(profile);
7027 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
7028 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007029 }
7030 }
7031 }
7032
Eric Laurent0dd51852019-04-19 18:18:58 -07007033 if (profiles.isEmpty()) {
7034 ALOGW("%s: No input profile available for device %s",
7035 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007036 return BAD_VALUE;
7037 }
7038
7039 // open inputs for matching profiles if needed. Direct inputs are also opened to
7040 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7041 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7042
Eric Laurent1c333e22014-05-20 10:48:17 -07007043 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007044
Eric Laurentd4692962014-05-05 18:13:44 -07007045 // nothing to do if one input is already opened for this profile
7046 size_t input_index;
7047 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7048 desc = mInputs.valueAt(input_index);
7049 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007050 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007051 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007052 }
Eric Laurentd4692962014-05-05 18:13:44 -07007053 break;
7054 }
7055 }
7056 if (input_index != mInputs.size()) {
7057 continue;
7058 }
7059
Eric Laurent3974e3b2017-12-07 17:58:43 -08007060 if (!profile->canOpenNewIo()) {
7061 ALOGW("Max Input number %u already opened for this profile %s",
7062 profile->maxOpenCount, profile->getTagName().c_str());
7063 continue;
7064 }
7065
Eric Laurentc71b11b2024-06-03 12:54:53 +00007066 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007067 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00007068 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007069
Eric Laurentcf2c0212014-07-25 16:20:43 -07007070 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007071 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007072 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007073 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007074 mpClientInterface->setParameters(input, String8(param));
7075 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007076 }
jiabin12537fc2023-10-12 17:56:08 +00007077 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007078 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07007079 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08007080 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007081 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007082 }
7083
Eric Laurent0dd51852019-04-19 18:18:58 -07007084 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007085 addInput(input, desc);
7086 }
7087 } // endif input != 0
7088
Eric Laurentcf2c0212014-07-25 16:20:43 -07007089 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08007090 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01007091 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007092 profiles.removeAt(profile_index);
7093 profile_index--;
7094 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007095 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007096 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007097 }
Eric Laurentd4692962014-05-05 18:13:44 -07007098 ALOGV("checkInputsForDevice(): adding input %d", input);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007099
7100 if (checkCloseInput(desc)) {
7101 ALOGV("%s closing input %d", __func__, input);
7102 closeInput(input);
7103 }
Eric Laurentd4692962014-05-05 18:13:44 -07007104 }
7105 } // end scan profiles
7106
7107 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007108 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007109 return BAD_VALUE;
7110 }
7111 } else {
7112 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007113 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007114 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007115 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007116 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007117 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007118 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007119 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08007120 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
7121 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007122 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007123 }
7124 }
7125 }
7126 } // end disconnect
7127
7128 return NO_ERROR;
7129}
7130
7131
Eric Laurente0720872014-03-11 09:30:41 -07007132void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007133{
7134 ALOGV("closeOutput(%d)", output);
7135
François Gaffie1c878552018-11-22 16:53:21 +01007136 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7137 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007138 ALOGW("closeOutput() unknown output %d", output);
7139 return;
7140 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007141 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007142 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007143
Eric Laurente552edb2014-03-10 17:42:56 -07007144 // look for duplicated outputs connected to the output being removed.
7145 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007146 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7147 if (dupOutput->isDuplicated() &&
7148 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7149 sp<SwAudioOutputDescriptor> remainingOutput =
7150 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007151 // As all active tracks on duplicated output will be deleted,
7152 // and as they were also referenced on the other output, the reference
7153 // count for their stream type must be adjusted accordingly on
7154 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007155 const bool wasActive = remainingOutput->isActive();
7156 // Note: no-op on the closing output where all clients has already been set inactive
7157 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007158 // stop() will be a no op if the output is still active but is needed in case all
7159 // active streams refcounts where cleared above
7160 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007161 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007162 }
Eric Laurente552edb2014-03-10 17:42:56 -07007163 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7164 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7165
7166 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007167 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007168 }
7169 }
7170
Eric Laurent05b90f82014-08-27 15:32:29 -07007171 nextAudioPortGeneration();
7172
François Gaffie1c878552018-11-22 16:53:21 +01007173 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007174 if (index >= 0) {
7175 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007176 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7177 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007178 mAudioPatches.removeItemsAt(index);
7179 mpClientInterface->onAudioPatchListUpdate();
7180 }
7181
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007182 if (closingOutputWasActive) {
7183 closingOutput->stop();
7184 }
François Gaffie1c878552018-11-22 16:53:21 +01007185 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007186 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007187 for (const auto device : closingOutput->devices()) {
7188 device->setPreferredConfig(nullptr);
7189 }
7190 }
Eric Laurente552edb2014-03-10 17:42:56 -07007191
François Gaffie53615e22015-03-19 09:24:12 +01007192 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007193 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007194 if (closingOutput == mSpatializerOutput) {
7195 mSpatializerOutput.clear();
7196 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007197
7198 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7199 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007200 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007201 bool directOutputOpen = false;
7202 for (size_t i = 0; i < mOutputs.size(); i++) {
7203 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7204 directOutputOpen = true;
7205 break;
7206 }
7207 }
7208 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007209 ALOGV("no direct outputs open, reset MSD patches");
7210 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7211 // how output devices for patching are resolved. Avoid by caching and reusing the
7212 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7213 // devices to patch to. This may be complicated by the fact that devices may become
7214 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007215 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007216 }
7217 }
jiabin220eea12024-05-17 17:55:20 +00007218
7219 if (closingOutput->mPreferredAttrInfo != nullptr) {
7220 closingOutput->mPreferredAttrInfo->resetActiveClient();
7221 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007222}
7223
7224void AudioPolicyManager::closeInput(audio_io_handle_t input)
7225{
7226 ALOGV("closeInput(%d)", input);
7227
7228 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7229 if (inputDesc == NULL) {
7230 ALOGW("closeInput() unknown input %d", input);
7231 return;
7232 }
7233
Eric Laurent6a94d692014-05-20 11:18:06 -07007234 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007235
François Gaffie11d30102018-11-02 16:09:09 +01007236 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007237 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007238 if (index >= 0) {
7239 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007240 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7241 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007242 mAudioPatches.removeItemsAt(index);
7243 mpClientInterface->onAudioPatchListUpdate();
7244 }
7245
François Gaffie6ebbce02023-07-19 13:27:53 +02007246 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007247 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007248 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007249
François Gaffie11d30102018-11-02 16:09:09 +01007250 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7251 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007252 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007253 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007254 }
Eric Laurente552edb2014-03-10 17:42:56 -07007255}
7256
François Gaffie11d30102018-11-02 16:09:09 +01007257SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7258 const DeviceVector &devices,
7259 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007260{
7261 SortedVector<audio_io_handle_t> outputs;
7262
François Gaffie11d30102018-11-02 16:09:09 +01007263 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007264 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007265 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007266 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007267 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007268 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007269 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007270 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007271 outputs.add(openOutputs.keyAt(i));
7272 }
7273 }
7274 return outputs;
7275}
7276
Mikhail Naganov37977152018-07-11 15:54:44 -07007277void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7278{
7279 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7280 // output is suspended before any tracks are moved to it
7281 checkA2dpSuspend();
7282 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007283 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007284 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007285 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007286 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007287 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7288 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7289 // configuration changes will ultimately be rerouted correctly. We can still avoid
7290 // unnecessary rerouting by caching and reusing the arguments to
7291 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7292 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007293 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007294 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007295 // an event that changed routing likely occurred, inform upper layers
7296 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007297}
7298
François Gaffiec005e562018-11-06 15:04:49 +01007299bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7300 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007301{
François Gaffiec005e562018-11-06 15:04:49 +01007302 return mEngine->getProductStrategyForAttributes(lAttr) ==
7303 mEngine->getProductStrategyForAttributes(rAttr);
7304}
7305
Francois Gaffieff1eb522020-05-06 18:37:04 +02007306void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7307{
7308 for (size_t i = 0; i < mAudioSources.size(); i++) {
7309 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7310 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007311 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007312 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007313 connectAudioSource(sourceDesc);
7314 }
7315 }
7316}
7317
7318void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7319{
7320 for (size_t i = 0; i < mAudioSources.size(); i++) {
7321 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7322 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7323 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7324 disconnectAudioSource(sourceDesc);
7325 }
7326 }
7327}
7328
François Gaffiec005e562018-11-06 15:04:49 +01007329void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7330{
7331 auto psId = mEngine->getProductStrategyForAttributes(attr);
7332
7333 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7334 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007335
François Gaffie11d30102018-11-02 16:09:09 +01007336 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7337 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007338
Eric Laurentc209fe42020-06-05 18:11:23 -07007339 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007340 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007341 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007342 // take into account dynamic audio policies related changes: if a client is now associated
7343 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007344 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007345 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7346 if (desc->isDuplicated()) {
7347 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007348 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007349 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7350 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7351 continue;
7352 }
7353 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007354 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007355 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7356 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7357 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007358 if (status != OK) {
7359 continue;
7360 }
yucliuf4de36d2020-09-14 14:57:56 -07007361 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007362 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007363 maxLatency = desc->latency();
7364 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007365 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007366 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007367 }
7368 }
7369
Eric Laurent56ed8842022-11-15 16:04:41 +01007370 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007371 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7372 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007373 for (audio_io_handle_t srcOut : srcOutputs) {
7374 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007375 if (desc == nullptr) continue;
7376
7377 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007378 maxLatency = desc->latency();
7379 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007380
Eric Laurent56ed8842022-11-15 16:04:41 +01007381 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007382 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007383 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007384 // a client on a non direct outputs has necessarily a linear PCM format
7385 // so we can call selectOutput() safely
7386 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7387 client->flags(),
7388 client->config().format,
7389 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007390 client->config().sample_rate,
7391 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007392 if (newOutput != srcOut) {
7393 invalidate = true;
7394 break;
7395 }
7396 } else {
7397 sp<IOProfile> profile = getProfileForOutput(newDevices,
7398 client->config().sample_rate,
7399 client->config().format,
7400 client->config().channel_mask,
7401 client->flags(),
7402 true /* directOnly */);
7403 if (profile != desc->mProfile) {
7404 invalidate = true;
7405 break;
7406 }
7407 }
7408 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007409 // mute strategy while moving tracks from one output to another
7410 if (invalidate) {
7411 invalidatedOutputs.push_back(desc);
7412 if (desc->isStrategyActive(psId)) {
7413 setStrategyMute(psId, true, desc);
7414 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7415 newDevices.types());
7416 }
Eric Laurente552edb2014-03-10 17:42:56 -07007417 }
François Gaffiec005e562018-11-06 15:04:49 +01007418 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007419 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007420 connectAudioSource(source);
7421 }
Eric Laurente552edb2014-03-10 17:42:56 -07007422 }
7423
Eric Laurent56ed8842022-11-15 16:04:41 +01007424 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7425 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7426 std::to_string(srcOutputs[0]).c_str(),
7427 std::to_string(dstOutputs[0]).c_str());
7428
François Gaffiec005e562018-11-06 15:04:49 +01007429 // Move effects associated to this stream from previous output to new output
7430 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007431 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007432 }
François Gaffiec005e562018-11-06 15:04:49 +01007433 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007434 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007435 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007436 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007437 desc->setTracksInvalidatedStatusByStrategy(psId);
7438 }
Eric Laurente552edb2014-03-10 17:42:56 -07007439 }
7440 }
7441}
7442
Eric Laurente0720872014-03-11 09:30:41 -07007443void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007444{
François Gaffiec005e562018-11-06 15:04:49 +01007445 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7446 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7447 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007448 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007449 }
Eric Laurente552edb2014-03-10 17:42:56 -07007450}
7451
Kevin Rocard153f92d2018-12-18 18:33:28 -08007452void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007453 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007454 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007455 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007456 for (size_t i = 0; i < mOutputs.size(); i++) {
7457 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7458 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007459 sp<AudioPolicyMix> primaryMix;
7460 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007461 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007462 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7463 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7464 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007465 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7466 for (auto &secondaryMix : secondaryMixes) {
7467 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7468 if (outputDesc != nullptr &&
7469 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7470 secondaryDescs.push_back(outputDesc);
7471 }
7472 }
7473
jiabinc44b3462022-12-08 12:52:31 -08007474 if (status != OK &&
7475 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7476 // When it failed to query secondary output, only invalidate the client that is not
7477 // MMAP. The reason is that MMAP stream will not support secondary output.
7478 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007479 } else if (!std::equal(
7480 client->getSecondaryOutputs().begin(),
7481 client->getSecondaryOutputs().end(),
7482 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007483 if (!audio_is_linear_pcm(client->config().format)) {
7484 // If the format is not PCM, the tracks should be invalidated to get correct
7485 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007486 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007487 } else {
7488 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7489 std::vector<audio_io_handle_t> secondaryOutputIds;
7490 for (const auto &secondaryDesc: secondaryDescs) {
7491 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7492 weakSecondaryDescs.push_back(secondaryDesc);
7493 }
7494 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7495 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007496 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007497 }
7498 }
7499 }
jiabin10a03f12021-05-07 23:46:28 +00007500 if (!trackSecondaryOutputs.empty()) {
7501 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7502 }
jiabinc44b3462022-12-08 12:52:31 -08007503 if (!clientsToInvalidate.empty()) {
7504 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7505 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007506 }
7507}
7508
Eric Laurent2517af32020-11-25 15:31:27 +01007509bool AudioPolicyManager::isScoRequestedForComm() const {
7510 AudioDeviceTypeAddrVector devices;
7511 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7512 for (const auto &device : devices) {
7513 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7514 return true;
7515 }
7516 }
7517 return false;
7518}
7519
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007520bool AudioPolicyManager::isHearingAidUsedForComm() const {
7521 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7522 true /*fromCache*/);
7523 for (const auto &device : devices) {
7524 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7525 return true;
7526 }
7527 }
7528 return false;
7529}
7530
7531
Eric Laurente0720872014-03-11 09:30:41 -07007532void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007533{
François Gaffie53615e22015-03-19 09:24:12 +01007534 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007535 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007536 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007537 return;
7538 }
7539
Eric Laurent3a4311c2014-03-17 12:00:47 -07007540 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007541 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7542 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007543 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007544
7545 // if suspended, restore A2DP output if:
7546 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007547 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007548 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007549 //
Eric Laurentf732e072016-08-03 19:30:28 -07007550 // if not suspended, suspend A2DP output if:
7551 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007552 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007553 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007554 //
7555 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007556 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007557 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007558 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007559 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007560
7561 mpClientInterface->restoreOutput(a2dpOutput);
7562 mA2dpSuspended = false;
7563 }
7564 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007565 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007566 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007567 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007568 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007569
7570 mpClientInterface->suspendOutput(a2dpOutput);
7571 mA2dpSuspended = true;
7572 }
7573 }
7574}
7575
François Gaffie11d30102018-11-02 16:09:09 +01007576DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7577 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007578{
François Gaffiedb1755b2023-09-01 11:50:35 +02007579 if (outputDesc == nullptr) {
7580 return DeviceVector{};
7581 }
François Gaffie11d30102018-11-02 16:09:09 +01007582
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007583 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007584 if (index >= 0) {
7585 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007586 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007587 ALOGV("%s device %s forced by patch %d", __func__,
7588 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7589 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007590 }
7591 }
7592
Dean Wheatley514b4312020-06-17 21:45:00 +10007593 // Do not retrieve engine device for outputs through MSD
7594 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7595 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7596 return outputDesc->devices();
7597 }
7598
Eric Laurent97ac8712018-07-27 18:59:02 -07007599 // Honor explicit routing requests only if no client using default routing is active on this
7600 // input: a specific app can not force routing for other apps by setting a preferred device.
7601 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007602 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007603 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007604 if (device != nullptr) {
7605 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007606 }
7607
François Gaffiea807ef92018-11-05 10:44:33 +01007608 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7609 // of setForceUse / Default Bus device here
7610 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7611 if (device != nullptr) {
7612 return DeviceVector(device);
7613 }
7614
François Gaffiedb1755b2023-09-01 11:50:35 +02007615 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007616 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7617 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307618 auto hasStreamActive = [&](auto stream) {
7619 return hasStream(streams, stream) && isStreamActive(stream, 0);
7620 };
Eric Laurent484e9272018-06-07 17:29:23 -07007621
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307622 auto doGetOutputDevicesForVoice = [&]() {
7623 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007624 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307625 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007626 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7627 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307628 };
7629
7630 // With low-latency playing on speaker, music on WFD, when the first low-latency
7631 // output is stopped, getNewOutputDevices checks for a product strategy
7632 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007633 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307634 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7635 // stream is associated to the output descriptor.
7636 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7637 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7638 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7639 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007640 // Retrieval of devices for voice DL is done on primary output profile, cannot
7641 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007642 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007643 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7644 break;
7645 }
Eric Laurente552edb2014-03-10 17:42:56 -07007646 }
François Gaffiec005e562018-11-06 15:04:49 +01007647 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007648 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007649}
7650
François Gaffie11d30102018-11-02 16:09:09 +01007651sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7652 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007653{
François Gaffie11d30102018-11-02 16:09:09 +01007654 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007655
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007656 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007657 if (index >= 0) {
7658 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007659 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007660 ALOGV("getNewInputDevice() device %s forced by patch %d",
7661 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7662 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007663 }
7664 }
7665
Eric Laurent97ac8712018-07-27 18:59:02 -07007666 // Honor explicit routing requests only if no client using default routing is active on this
7667 // input: a specific app can not force routing for other apps by setting a preferred device.
7668 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007669 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7670 if (device != nullptr) {
7671 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007672 }
7673
Eric Laurentdc95a252018-04-12 12:46:56 -07007674 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007675 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007676 audio_attributes_t attributes;
7677 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007678 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007679 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7680 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007681 attributes = topClient->attributes();
7682 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007683 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007684 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007685 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7686 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007687 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007688 }
7689
Francois Gaffie716e1432019-01-14 16:58:59 +01007690 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7691 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007692 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007693 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007694 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007695 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007696
Eric Laurente552edb2014-03-10 17:42:56 -07007697 return device;
7698}
7699
Eric Laurent794fde22016-03-11 09:50:45 -08007700bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7701 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007702 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007703}
7704
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007705status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007706 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007707 if (devices == nullptr) {
7708 return BAD_VALUE;
7709 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007710
Andy Hung6d23c0f2022-02-16 09:37:15 -08007711 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007712 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7713 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007714 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007715 for (const auto& device : curDevices) {
7716 devices->push_back(device->getDeviceTypeAddr());
7717 }
7718 return NO_ERROR;
7719}
7720
Eric Laurente0720872014-03-11 09:30:41 -07007721void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007722 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007723 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007724 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007725 updateDevicesAndOutputs();
7726 break;
7727 default:
7728 break;
7729 }
7730}
7731
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007732uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007733
7734 // skip beacon mute management if a dedicated TTS output is available
7735 if (mTtsOutputAvailable) {
7736 return 0;
7737 }
7738
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007739 switch(event) {
7740 case STARTING_OUTPUT:
7741 mBeaconMuteRefCount++;
7742 break;
7743 case STOPPING_OUTPUT:
7744 if (mBeaconMuteRefCount > 0) {
7745 mBeaconMuteRefCount--;
7746 }
7747 break;
7748 case STARTING_BEACON:
7749 mBeaconPlayingRefCount++;
7750 break;
7751 case STOPPING_BEACON:
7752 if (mBeaconPlayingRefCount > 0) {
7753 mBeaconPlayingRefCount--;
7754 }
7755 break;
7756 }
7757
7758 if (mBeaconMuteRefCount > 0) {
7759 // any playback causes beacon to be muted
7760 return setBeaconMute(true);
7761 } else {
7762 // no other playback: unmute when beacon starts playing, mute when it stops
7763 return setBeaconMute(mBeaconPlayingRefCount == 0);
7764 }
7765}
7766
7767uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7768 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7769 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7770 // keep track of muted state to avoid repeating mute/unmute operations
7771 if (mBeaconMuted != mute) {
7772 // mute/unmute AUDIO_STREAM_TTS on all outputs
7773 ALOGV("\t muting %d", mute);
7774 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007775 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7776 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7777 ALOGV("\t no tts volume source available");
7778 return 0;
7779 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007780 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007781 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007782 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007783 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007784 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007785 maxLatency = latency;
7786 }
7787 }
7788 mBeaconMuted = mute;
7789 return maxLatency;
7790 }
7791 return 0;
7792}
7793
Eric Laurente0720872014-03-11 09:30:41 -07007794void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007795{
François Gaffiec005e562018-11-06 15:04:49 +01007796 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007797 mPreviousOutputs = mOutputs;
7798}
7799
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007800uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007801 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007802 uint32_t delayMs)
7803{
7804 // mute/unmute strategies using an incompatible device combination
7805 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7806 // if unmuting, unmute only after the specified delay
7807 if (outputDesc->isDuplicated()) {
7808 return 0;
7809 }
7810
7811 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007812 DeviceVector devices = outputDesc->devices();
7813 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007814
François Gaffiec005e562018-11-06 15:04:49 +01007815 auto productStrategies = mEngine->getOrderedProductStrategies();
7816 for (const auto &productStrategy : productStrategies) {
7817 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7818 DeviceVector curDevices =
7819 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7820 curDevices = curDevices.filter(outputDesc->supportedDevices());
7821 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007822 bool doMute = false;
7823
François Gaffiec005e562018-11-06 15:04:49 +01007824 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007825 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007826 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7827 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007828 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007829 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007830 }
Eric Laurent99401132014-05-07 19:48:15 -07007831 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007832 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007833 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007834 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007835 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007836 continue;
7837 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307838 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007839 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7840 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7841 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007842 if (mute) {
7843 // FIXME: should not need to double latency if volume could be applied
7844 // immediately by the audioflinger mixer. We must account for the delay
7845 // between now and the next time the audioflinger thread for this output
7846 // will process a buffer (which corresponds to one buffer size,
7847 // usually 1/2 or 1/4 of the latency).
7848 if (muteWaitMs < desc->latency() * 2) {
7849 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007850 }
7851 }
7852 }
7853 }
7854 }
7855 }
7856
Eric Laurent99401132014-05-07 19:48:15 -07007857 // temporary mute output if device selection changes to avoid volume bursts due to
7858 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007859 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007860 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007861
Eric Laurentdc462862016-07-19 12:29:53 -07007862 if (muteWaitMs < tempMuteWaitMs) {
7863 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007864 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007865
7866 // If recommended duration is defined, replace temporary mute duration to avoid
7867 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7868 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7869 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7870 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7871 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7872
François Gaffieaaac0fd2018-11-22 17:56:39 +01007873 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7874 // make sure that we do not start the temporary mute period too early in case of
7875 // delayed device change
7876 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7877 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007878 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007879 }
7880 }
7881
Eric Laurente552edb2014-03-10 17:42:56 -07007882 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7883 if (muteWaitMs > delayMs) {
7884 muteWaitMs -= delayMs;
7885 usleep(muteWaitMs * 1000);
7886 return muteWaitMs;
7887 }
7888 return 0;
7889}
7890
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307891uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7892 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007893 const DeviceVector &devices,
7894 bool force,
7895 int delayMs,
7896 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007897 bool requiresMuteCheck, bool requiresVolumeCheck,
7898 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007899{
jiabin3ff8d7d2022-12-13 06:27:44 +00007900 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307901 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7902 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7903 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007904 uint32_t muteWaitMs;
7905
7906 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307907 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007908 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307909 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007910 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007911 return muteWaitMs;
7912 }
Eric Laurente552edb2014-03-10 17:42:56 -07007913
7914 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007915 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007916 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007917 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007918
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307919 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7920 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007921
7922 if (!filteredDevices.isEmpty()) {
7923 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007924 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007925
7926 // if the outputs are not materially active, there is no need to mute.
7927 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007928 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007929 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307930 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7931 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007932 muteWaitMs = 0;
7933 }
Eric Laurente552edb2014-03-10 17:42:56 -07007934
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007935 bool outputRouted = outputDesc->isRouted();
7936
Eric Laurent79ea9582020-06-11 18:49:24 -07007937 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7938 // output profile or if new device is not supported AND previous device(s) is(are) still
7939 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007940 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307941 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7942 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007943 // restore previous device after evaluating strategy mute state
7944 outputDesc->setDevices(prevDevices);
7945 return muteWaitMs;
7946 }
7947
Eric Laurente552edb2014-03-10 17:42:56 -07007948 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007949 // the requested device is AUDIO_DEVICE_NONE
7950 // OR the requested device is the same as current device
7951 // AND force is not specified
7952 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007953 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007954 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307955 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7956 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7957 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007958 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307959 ALOGV("%s %s setting same device on routed output, force apply volumes",
7960 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007961 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7962 }
Eric Laurente552edb2014-03-10 17:42:56 -07007963 return muteWaitMs;
7964 }
7965
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307966 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7967 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007968
Eric Laurente552edb2014-03-10 17:42:56 -07007969 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007970 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007971 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007972 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007973 PatchBuilder patchBuilder;
7974 patchBuilder.addSource(outputDesc);
7975 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7976 for (const auto &filteredDevice : filteredDevices) {
7977 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007978 }
7979
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007980 // Add half reported latency to delayMs when muteWaitMs is null in order
7981 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007982 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7983 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7984 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007985 }
Eric Laurente552edb2014-03-10 17:42:56 -07007986
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007987 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7988 if (!skipMuteDelay) {
7989 // update stream volumes according to new device
7990 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7991 }
Eric Laurente552edb2014-03-10 17:42:56 -07007992
7993 return muteWaitMs;
7994}
7995
Eric Laurentc75307b2015-03-17 15:29:32 -07007996status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007997 int delayMs,
7998 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007999{
Eric Laurent6a94d692014-05-20 11:18:06 -07008000 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008001 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8002 return INVALID_OPERATION;
8003 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008004 if (patchHandle) {
8005 index = mAudioPatches.indexOfKey(*patchHandle);
8006 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008007 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008008 }
8009 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008010 return INVALID_OPERATION;
8011 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008012 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008013 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008014 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008015 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008016 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008017 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008018 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008019 return status;
8020}
8021
8022status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008023 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008024 bool force,
8025 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008026{
8027 status_t status = NO_ERROR;
8028
Eric Laurent1f2f2232014-06-02 12:01:23 -07008029 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008030 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8031 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008032
François Gaffie11d30102018-11-02 16:09:09 +01008033 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008034 PatchBuilder patchBuilder;
8035 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008036 // AUDIO_SOURCE_HOTWORD is for internal use only:
8037 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008038 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8039 auto result = usecase;
8040 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8041 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8042 }
8043 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07008044 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01008045 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008046 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008047 }
8048 }
8049 return status;
8050}
8051
Eric Laurent6a94d692014-05-20 11:18:06 -07008052status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8053 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008054{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008055 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008056 ssize_t index;
8057 if (patchHandle) {
8058 index = mAudioPatches.indexOfKey(*patchHandle);
8059 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008060 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008061 }
8062 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008063 return INVALID_OPERATION;
8064 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008065 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008066 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008067 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008068 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008069 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008070 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008071 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008072 return status;
8073}
8074
François Gaffie11d30102018-11-02 16:09:09 +01008075sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008076 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008077 audio_format_t& format,
8078 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008079 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008080{
8081 // Choose an input profile based on the requested capture parameters: select the first available
8082 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008083 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008084
Atneya Nair0f0a8032022-12-12 16:20:12 -08008085 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8086 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8087 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8088
8089 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008090
jiabin2fd710d2022-05-02 23:20:22 +00008091 for (;;) {
8092 sp<IOProfile> firstInexact = nullptr;
8093 uint32_t updatedSamplingRate = 0;
8094 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8095 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8096 for (const auto& hwModule : mHwModules) {
8097 for (const auto& profile : hwModule->getInputProfiles()) {
8098 // profile->log();
8099 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008100 if (profile->getCompatibilityScore(
8101 DeviceVector(device),
8102 samplingRate,
8103 &updatedSamplingRate,
8104 format,
8105 &updatedFormat,
8106 channelMask,
8107 &updatedChannelMask,
8108 // FIXME ugly cast
8109 (audio_output_flags_t) flags,
8110 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8111 samplingRate = updatedSamplingRate;
8112 format = updatedFormat;
8113 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008114 return profile;
8115 }
jiabin66acc432024-02-06 00:57:36 +00008116 if (firstInexact == nullptr
8117 && profile->getCompatibilityScore(
8118 DeviceVector(device),
8119 samplingRate,
8120 &updatedSamplingRate,
8121 format,
8122 &updatedFormat,
8123 channelMask,
8124 &updatedChannelMask,
8125 // FIXME ugly cast
8126 (audio_output_flags_t) flags,
8127 false /*exactMatchRequiredForInputFlags*/)
8128 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008129 firstInexact = profile;
8130 }
8131 }
8132 }
8133
8134 if (firstInexact != nullptr) {
8135 samplingRate = updatedSamplingRate;
8136 format = updatedFormat;
8137 channelMask = updatedChannelMask;
8138 return firstInexact;
8139 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8140 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8141 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8142 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8143 flags = AUDIO_INPUT_FLAG_NONE;
8144 } else { // fail
8145 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8146 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8147 samplingRate, format, channelMask, oriFlags);
8148 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008149 }
8150 }
jiabin2fd710d2022-05-02 23:20:22 +00008151
8152 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008153}
8154
Vlad Popa87e0e582024-05-20 18:49:20 -07008155float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8156 VolumeSource volumeSource,
8157 int index,
8158 const DeviceTypeSet &deviceTypes)
8159{
8160 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8161 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8162 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8163
8164 if (com_android_media_audio_abs_volume_index_fix()) {
8165 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8166 mAbsoluteVolumeDrivingStreams.end()) {
8167 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8168 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8169 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8170 ALOGD("%s: no group matching with %s", __FUNCTION__,
8171 toString(attributesToDriveAbs).c_str());
8172 return volumeDb;
8173 }
8174
8175 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8176 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8177 if (vsToDriveAbs == volumeSource) {
8178 // attenuation is applied by the abs volume controller
8179 return volumeDbMax;
8180 } else {
8181 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8182 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8183 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8184 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8185 curvesAbs.getVolumeIndexMax());
8186 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8187 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8188 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8189 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8190 return newVolumeDb;
8191 }
8192 }
8193 return volumeDb;
8194 } else {
8195 return volumeDb;
8196 }
8197}
8198
François Gaffieaaac0fd2018-11-22 17:56:39 +01008199float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8200 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008201 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008202 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008203 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008204 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008205{
Vlad Popa9d482762024-06-21 16:40:23 -07008206 float volumeDb;
8207 if (adjustAttenuation) {
8208 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8209 } else {
8210 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8211 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008212 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8213 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8214
8215 if (!computeInternalInteraction) {
8216 return volumeDb;
8217 }
8218
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008219 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8220 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8221 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8222 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008223 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8224 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8225 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8226 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8227 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008228 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008229 mOutputs.isActive(ringVolumeSrc, 0)) {
8230 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008231 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008232 adjustAttenuation,
8233 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008234 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008235 }
8236
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008237 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008238 if ((volumeSource != callVolumeSrc && (isInCall() ||
8239 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008240 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008241 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8242 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008243 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8244 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8245 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008246 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008247 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008248 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008249 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008250 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008251 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008252 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008253 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8254 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8255 // programmatically muted.
8256 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8257 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8258 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008259 bool exemptFromCapping =
8260 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8261 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008262 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8263 volumeSource, volumeDb);
8264 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008265 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8266 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8267 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008268 }
8269 }
Eric Laurente552edb2014-03-10 17:42:56 -07008270 // if a headset is connected, apply the following rules to ring tones and notifications
8271 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008272 // - always attenuate notifications volume by 6dB
8273 // - attenuate ring tones volume by 6dB unless music is not playing and
8274 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008275 // - if music is playing, always limit the volume to current music volume,
8276 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008277 if (!Intersection(deviceTypes,
8278 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8279 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008280 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8281 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008282 ((volumeSource == alarmVolumeSrc ||
8283 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008284 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8285 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8286 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008287 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8288 curves.canBeMuted()) {
8289
Eric Laurente552edb2014-03-10 17:42:56 -07008290 // when the phone is ringing we must consider that music could have been paused just before
8291 // by the music application and behave as if music was active if the last music track was
8292 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008293 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8294 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008295 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008296 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008297 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8298 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008299 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008300 float musicVolDb = computeVolume(musicCurves,
8301 musicVolumeSrc,
8302 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008303 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008304 adjustAttenuation,
8305 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008306 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8307 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8308 if (volumeDb > minVolDb) {
8309 volumeDb = minVolDb;
8310 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008311 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008312 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8313 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008314 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8315 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8316 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8317 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008318 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008319 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008320 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8321 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008322 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8323 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008324 }
8325 }
jiabin9a3361e2019-10-01 09:38:30 -07008326 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008327 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008328 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008329 }
8330 }
8331
François Gaffie43c73442018-11-08 08:21:55 +01008332 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008333}
8334
Eric Laurent3839bc02018-07-10 18:33:34 -07008335int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008336 VolumeSource fromVolumeSource,
8337 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008338{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008339 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008340 return srcIndex;
8341 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008342 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8343 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008344 float minSrc = (float)srcCurves.getVolumeIndexMin();
8345 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8346 float minDst = (float)dstCurves.getVolumeIndexMin();
8347 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008348
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008349 // preserve mute request or correct range
8350 if (srcIndex < minSrc) {
8351 if (srcIndex == 0) {
8352 return 0;
8353 }
8354 srcIndex = minSrc;
8355 } else if (srcIndex > maxSrc) {
8356 srcIndex = maxSrc;
8357 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008358 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8359}
8360
François Gaffieaaac0fd2018-11-22 17:56:39 +01008361status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8362 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008363 int index,
8364 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008365 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008366 int delayMs,
8367 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008368{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008369 // do not change actual attributes volume if the attributes is muted
8370 if (outputDesc->isMuted(volumeSource)) {
8371 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8372 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008373 return NO_ERROR;
8374 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008375
Eric Laurentae6e88c2024-01-10 14:42:57 +01008376 bool isVoiceVolSrc;
8377 bool isBtScoVolSrc;
8378 if (!isVolumeConsistentForCalls(
8379 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008380 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008381 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008382 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008383 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008384
jiabin9a3361e2019-10-01 09:38:30 -07008385 if (deviceTypes.empty()) {
8386 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008387 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008388 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008389 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008390 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008391
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008392 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8393 ALOGE("invalid volume index range");
8394 return BAD_VALUE;
8395 }
8396
jiabin9a3361e2019-10-01 09:38:30 -07008397 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8398 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008399 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008400 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008401 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8402 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008403 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008404 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008405 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008406 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8407 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008408
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008409 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008410 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8411 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8412 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008413 }
Eric Laurente552edb2014-03-10 17:42:56 -07008414 return NO_ERROR;
8415}
8416
Eric Laurentae6e88c2024-01-10 14:42:57 +01008417void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008418 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008419 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008420 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008421 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008422 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008423 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8424 } else {
8425 voiceVolume = index == 0 ? 0.0 : 1.0;
8426 }
8427 if (voiceVolume != mLastVoiceVolume) {
8428 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8429 mLastVoiceVolume = voiceVolume;
8430 }
8431}
8432
8433bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8434 const DeviceTypeSet& deviceTypes,
8435 bool& isVoiceVolSrc,
8436 bool& isBtScoVolSrc,
8437 const char* caller) {
8438 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8439 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8440 const bool isScoRequested = isScoRequestedForComm();
8441 const bool isHAUsed = isHearingAidUsedForComm();
8442
8443 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8444 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8445
8446 if ((callVolSrc != btScoVolSrc) &&
8447 ((isVoiceVolSrc && isScoRequested) ||
8448 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8449 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8450 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8451 volumeSource, isScoRequested ? " " : " not ");
8452 return false;
8453 }
8454 return true;
8455}
8456
Eric Laurentc75307b2015-03-17 15:29:32 -07008457void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008458 const DeviceTypeSet& deviceTypes,
8459 int delayMs,
8460 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008461{
jiabincd510522020-01-22 09:40:55 -08008462 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008463 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8464 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8465 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008466 curves.getVolumeIndex(deviceTypes),
8467 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008468 }
8469}
8470
François Gaffiec005e562018-11-06 15:04:49 +01008471void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8472 bool on,
8473 const sp<AudioOutputDescriptor>& outputDesc,
8474 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008475 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008476{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008477 std::vector<VolumeSource> sourcesToMute;
8478 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8479 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8480 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008481 VolumeSource source = toVolumeSource(attributes, false);
8482 if ((source != VOLUME_SOURCE_NONE) &&
8483 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8484 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008485 sourcesToMute.push_back(source);
8486 }
Eric Laurente552edb2014-03-10 17:42:56 -07008487 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008488 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008489 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008490 }
8491
Eric Laurente552edb2014-03-10 17:42:56 -07008492}
8493
François Gaffieaaac0fd2018-11-22 17:56:39 +01008494void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8495 bool on,
8496 const sp<AudioOutputDescriptor>& outputDesc,
8497 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008498 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008499{
jiabin9a3361e2019-10-01 09:38:30 -07008500 if (deviceTypes.empty()) {
8501 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008502 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008503 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008504 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008505 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008506 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008507 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008508 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8509 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008510 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008511 }
8512 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008513 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8514 // ignored
8515 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008516 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008517 if (!outputDesc->isMuted(volumeSource)) {
8518 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008519 return;
8520 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008521 if (outputDesc->decMuteCount(volumeSource) == 0) {
8522 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008523 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008524 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008525 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008526 delayMs);
8527 }
8528 }
8529}
8530
François Gaffie53615e22015-03-19 09:24:12 +01008531bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8532{
François Gaffiec005e562018-11-06 15:04:49 +01008533 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008534 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8535 return true;
8536 }
8537
8538 // has known usage?
8539 switch (paa->usage) {
8540 case AUDIO_USAGE_UNKNOWN:
8541 case AUDIO_USAGE_MEDIA:
8542 case AUDIO_USAGE_VOICE_COMMUNICATION:
8543 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8544 case AUDIO_USAGE_ALARM:
8545 case AUDIO_USAGE_NOTIFICATION:
8546 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8547 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8548 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8549 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8550 case AUDIO_USAGE_NOTIFICATION_EVENT:
8551 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8552 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8553 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8554 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008555 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008556 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008557 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008558 case AUDIO_USAGE_EMERGENCY:
8559 case AUDIO_USAGE_SAFETY:
8560 case AUDIO_USAGE_VEHICLE_STATUS:
8561 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008562 break;
8563 default:
8564 return false;
8565 }
8566 return true;
8567}
8568
François Gaffie2110e042015-03-24 08:41:51 +01008569audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8570{
8571 return mEngine->getForceUse(usage);
8572}
8573
Eric Laurent96d1dda2022-03-14 17:14:19 +01008574bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008575 return isStateInCall(mEngine->getPhoneState());
8576}
8577
Eric Laurent96d1dda2022-03-14 17:14:19 +01008578bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008579 return is_state_in_call(state);
8580}
8581
Eric Laurentf9cccec2022-11-16 19:12:00 +01008582bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008583 audio_mode_t mode = mEngine->getPhoneState();
8584 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008585 || (mode == AUDIO_MODE_CALL_SCREEN)
8586 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008587}
8588
Eric Laurentf9cccec2022-11-16 19:12:00 +01008589bool AudioPolicyManager::isInCallOrScreening() const {
8590 audio_mode_t mode = mEngine->getPhoneState();
8591 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8592}
8593
Eric Laurentd60560a2015-04-10 11:31:20 -07008594void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8595{
8596 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008597 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008598 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008599 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008600 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008601 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008602 }
8603 }
8604
8605 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8606 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8607 bool release = false;
8608 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8609 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8610 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8611 source->ext.device.type == deviceDesc->type()) {
8612 release = true;
8613 }
8614 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008615 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008616 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8617 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8618 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008619 sink->ext.device.type == deviceDesc->type() &&
8620 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8621 || strncmp(sink->ext.device.address, address,
8622 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008623 release = true;
8624 }
8625 }
8626 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008627 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8628 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008629 }
8630 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008631
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008632 mInputs.clearSessionRoutesForDevice(deviceDesc);
8633
Francois Gaffie716e1432019-01-14 16:58:59 +01008634 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008635}
8636
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008637void AudioPolicyManager::modifySurroundFormats(
8638 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008639 std::unordered_set<audio_format_t> enforcedSurround(
8640 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008641 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008642 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008643 allSurround.insert(pair.first);
8644 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8645 }
Phil Burk09bc4612016-02-24 15:58:15 -08008646
8647 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8648 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008649 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008650 // This is the resulting set of formats depending on the surround mode:
8651 // 'all surround' = allSurround
8652 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8653 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8654 // 'manual surround' = mManualSurroundFormats
8655 // AUTO: formats v 'enforced surround'
8656 // ALWAYS: formats v 'all surround' v 'enforced surround'
8657 // NEVER: formats ^ 'non-surround'
8658 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008659
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008660 std::unordered_set<audio_format_t> formatSet;
8661 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8662 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008663 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008664 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008665 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008666 formatSet.insert(*formatIter);
8667 }
8668 }
8669 } else {
8670 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8671 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008672 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008673
jiabin81772902018-04-02 17:52:27 -07008674 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008675 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008676 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8677 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8678 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008679 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008680 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8681 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8682 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008683 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008684 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008685 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008686 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008687 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008688 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008689}
8690
jiabin06e4bab2019-07-29 10:13:34 -07008691void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8692 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008693 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8694 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8695
8696 // If NEVER, then remove support for channelMasks > stereo.
8697 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008698 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8699 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008700 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008701 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008702 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008703 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008704 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008705 }
8706 }
jiabin81772902018-04-02 17:52:27 -07008707 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8708 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8709 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008710 bool supports5dot1 = false;
8711 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008712 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008713 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8714 supports5dot1 = true;
8715 break;
8716 }
8717 }
8718 // If not then add 5.1 support.
8719 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008720 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008721 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008722 }
Phil Burk09bc4612016-02-24 15:58:15 -08008723 }
8724}
8725
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008726void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008727 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008728 const sp<IOProfile>& profile) {
8729 if (!profile->hasDynamicAudioProfile()) {
8730 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008731 }
François Gaffie112b0af2015-11-19 16:13:25 +01008732
jiabin12537fc2023-10-12 17:56:08 +00008733 audio_port_v7 devicePort;
8734 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008735
jiabin12537fc2023-10-12 17:56:08 +00008736 audio_port_v7 mixPort;
8737 profile->toAudioPort(&mixPort);
8738 mixPort.ext.mix.handle = ioHandle;
8739
8740 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8741 if (status != NO_ERROR) {
8742 ALOGE("%s failed to query the attributes of the mix port", __func__);
8743 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008744 }
jiabin12537fc2023-10-12 17:56:08 +00008745
8746 std::set<audio_format_t> supportedFormats;
8747 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8748 supportedFormats.insert(mixPort.audio_profiles[i].format);
8749 }
8750 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8751 mReportedFormatsMap[devDesc] = formats;
8752
8753 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8754 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8755 modifySurroundFormats(devDesc, &formats);
8756 size_t modifiedNumProfiles = 0;
8757 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8758 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8759 formats.end()) {
8760 // Skip the format that is not present after modifying surround formats.
8761 continue;
8762 }
8763 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8764 sizeof(struct audio_profile));
8765 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8766 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8767 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8768 modifySurroundChannelMasks(&channels);
8769 std::copy(channels.begin(), channels.end(),
8770 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8771 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8772 }
8773 mixPort.num_audio_profiles = modifiedNumProfiles;
8774 }
8775 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008776}
Eric Laurentd60560a2015-04-10 11:31:20 -07008777
Mikhail Naganovdc769682018-05-04 15:34:08 -07008778status_t AudioPolicyManager::installPatch(const char *caller,
8779 audio_patch_handle_t *patchHandle,
8780 AudioIODescriptorInterface *ioDescriptor,
8781 const struct audio_patch *patch,
8782 int delayMs)
8783{
8784 ssize_t index = mAudioPatches.indexOfKey(
8785 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8786 *patchHandle : ioDescriptor->getPatchHandle());
8787 sp<AudioPatch> patchDesc;
8788 status_t status = installPatch(
8789 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8790 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008791 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008792 }
8793 return status;
8794}
8795
8796status_t AudioPolicyManager::installPatch(const char *caller,
8797 ssize_t index,
8798 audio_patch_handle_t *patchHandle,
8799 const struct audio_patch *patch,
8800 int delayMs,
8801 uid_t uid,
8802 sp<AudioPatch> *patchDescPtr)
8803{
8804 sp<AudioPatch> patchDesc;
8805 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8806 if (index >= 0) {
8807 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008808 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008809 }
8810
8811 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8812 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8813 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8814 if (status == NO_ERROR) {
8815 if (index < 0) {
8816 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008817 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008818 } else {
8819 patchDesc->mPatch = *patch;
8820 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008821 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008822 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008823 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008824 }
8825 nextAudioPortGeneration();
8826 mpClientInterface->onAudioPatchListUpdate();
8827 }
8828 if (patchDescPtr) *patchDescPtr = patchDesc;
8829 return status;
8830}
8831
jiabinbce0c1d2020-10-05 11:20:18 -07008832bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8833{
8834 const TrackClientVector activeClients = output->getActiveClients();
8835 if (activeClients.empty()) {
8836 return true;
8837 }
8838 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8839 if (index < 0) {
8840 ALOGE("%s, no audio patch found while there are active clients on output %d",
8841 __func__, output->getId());
8842 return false;
8843 }
8844 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8845 DeviceVector routedDevices;
8846 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8847 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8848 patchDesc->mPatch.sinks[i].id);
8849 if (device == nullptr) {
8850 ALOGE("%s, no audio device found with id(%d)",
8851 __func__, patchDesc->mPatch.sinks[i].id);
8852 return false;
8853 }
8854 routedDevices.add(device);
8855 }
8856 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008857 if (client->isInvalid()) {
8858 // No need to take care about invalidated clients.
8859 continue;
8860 }
jiabinbce0c1d2020-10-05 11:20:18 -07008861 sp<DeviceDescriptor> preferredDevice =
8862 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8863 if (mEngine->getOutputDevicesForAttributes(
8864 client->attributes(), preferredDevice, false) == routedDevices) {
8865 return false;
8866 }
8867 }
8868 return true;
8869}
8870
8871sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008872 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008873 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8874 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008875{
8876 for (const auto& device : devices) {
8877 // TODO: This should be checking if the profile supports the device combo.
8878 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008879 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8880 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008881 return nullptr;
8882 }
8883 }
8884 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8885 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07008886 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00008887 status_t status = desc->open(halConfig, mixerConfig, devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07008888 AUDIO_STREAM_DEFAULT, flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008889 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008890 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008891 return nullptr;
8892 }
jiabin14b50cc2023-12-13 19:01:52 +00008893 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8894 auto portConfig = desc->getConfig();
8895 for (const auto& device : devices) {
8896 device->setPreferredConfig(&portConfig);
8897 }
8898 }
jiabinbce0c1d2020-10-05 11:20:18 -07008899
8900 // Here is where the out_set_parameters() for card & device gets called
8901 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8902 const audio_devices_t deviceType = device->type();
8903 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008904 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008905 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8906 mpClientInterface->setParameters(output, String8(param));
8907 free(param);
8908 }
jiabin12537fc2023-10-12 17:56:08 +00008909 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008910 if (!profile->hasValidAudioProfile()) {
8911 ALOGW("%s() missing param", __func__);
8912 desc->close();
8913 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008914 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8915 // Reopen the output with the best audio profile picked by APM when the profile supports
8916 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008917 desc->close();
8918 output = AUDIO_IO_HANDLE_NONE;
8919 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8920 profile->pickAudioProfile(
8921 config.sample_rate, config.channel_mask, config.format);
8922 config.offload_info.sample_rate = config.sample_rate;
8923 config.offload_info.channel_mask = config.channel_mask;
8924 config.offload_info.format = config.format;
8925
Haofan Wangf6e304f2024-07-09 23:06:58 -07008926 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output,
8927 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008928 if (status != NO_ERROR) {
8929 return nullptr;
8930 }
8931 }
8932
8933 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008934 setOutputDevices(__func__, desc,
8935 devices,
8936 true,
8937 0,
8938 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008939 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8940 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8941
jiabinbce0c1d2020-10-05 11:20:18 -07008942 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8943 sp<AudioPolicyMix> policyMix;
8944 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8945 policyMix->setOutput(desc);
8946 desc->mPolicyMix = policyMix;
8947 } else {
8948 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008949 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008950 }
8951
baek.kim -61c20122022-07-27 10:05:32 +00008952 } else if (hasPrimaryOutput() && speaker != nullptr
8953 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008954 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8955 // no duplicated output for:
8956 // - direct outputs
8957 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008958 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008959 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8960
8961 //TODO: configure audio effect output stage here
8962
8963 // open a duplicating output thread for the new output and the primary output
8964 sp<SwAudioOutputDescriptor> dupOutputDesc =
8965 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8966 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8967 if (status == NO_ERROR) {
8968 // add duplicated output descriptor
8969 addOutput(duplicatedOutput, dupOutputDesc);
8970 } else {
8971 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8972 mPrimaryOutput->mIoHandle, output);
8973 desc->close();
8974 removeOutput(output);
8975 nextAudioPortGeneration();
8976 return nullptr;
8977 }
8978 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008979 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8980 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8981 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008982 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008983 }
jiabinbce0c1d2020-10-05 11:20:18 -07008984 return desc;
8985}
8986
jiabinf1c73972022-04-14 16:28:52 -07008987status_t AudioPolicyManager::getDevicesForAttributes(
8988 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8989 // Devices are determined in the following precedence:
8990 //
8991 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8992 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8993 //
8994 // If no such dynamic policy then
8995 // 2) Devices containing an active client using setPreferredDevice
8996 // with same strategy as the attributes.
8997 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8998 //
8999 // If no corresponding active client with setPreferredDevice then
9000 // 3) Devices associated with the strategy determined by the attributes
9001 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9002 //
9003 // See related getOutputForAttrInt().
9004
9005 // check dynamic policies but only for primary descriptors (secondary not used for audible
9006 // audio routing, only used for duplication for playback capture)
9007 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009008 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009009 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009010 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9011 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9012 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009013 if (status != OK) {
9014 return status;
9015 }
9016
9017 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9018 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9019 // as they are unaffected by device/stream volume
9020 // (per SwAudioOutputDescriptor::isFixedVolume()).
9021 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9022 ) {
9023 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9024 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9025 devices.add(deviceDesc);
9026 } else {
9027 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9028 // which selects setPreferredDevice if active. This means forVolume call
9029 // will take an active setPreferredDevice, if such exists.
9030
9031 devices = mEngine->getOutputDevicesForAttributes(
9032 attr, nullptr /* preferredDevice */, false /* fromCache */);
9033 }
9034
9035 if (forVolume) {
9036 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9037 // for single volume control in AudioService (such relationship should exist if
9038 // SPEAKER_SAFE is present).
9039 //
9040 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9041 DeviceVector speakerSafeDevices =
9042 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9043 if (!speakerSafeDevices.isEmpty()) {
9044 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9045 devices.remove(speakerSafeDevices);
9046 }
9047 }
9048
9049 return NO_ERROR;
9050}
9051
9052status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9053 AudioProfileVector& audioProfiles,
9054 uint32_t flags,
9055 bool isInput) {
9056 for (const auto& hwModule : mHwModules) {
9057 // the MSD module checks for different conditions
9058 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9059 continue;
9060 }
9061 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9062 : hwModule->getOutputProfiles();
9063 for (const auto& profile : ioProfiles) {
9064 if (!profile->areAllDevicesSupported(devices) ||
9065 !profile->isCompatibleProfileForFlags(
9066 flags, false /*exactMatchRequiredForInputFlags*/)) {
9067 continue;
9068 }
9069 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9070 }
9071 }
9072
9073 if (!isInput) {
9074 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9075 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9076 if (msdModule != nullptr) {
9077 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9078 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9079 for (const auto &profile: msdModule->getOutputProfiles()) {
9080 if (!profile->asAudioPort()->isDirectOutput()) {
9081 continue;
9082 }
9083 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9084 }
9085 } else {
9086 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9087 }
9088 }
9089 }
9090
9091 return NO_ERROR;
9092}
9093
jiabin3ff8d7d2022-12-13 06:27:44 +00009094sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9095 const audio_config_t *config,
9096 audio_output_flags_t flags,
9097 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009098 closeOutput(outputDesc->mIoHandle);
9099 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9100 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9101 if (preferredOutput == nullptr) {
9102 ALOGE("%s failed to reopen output device=%d, caller=%s",
9103 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009104 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009105 return preferredOutput;
9106}
9107
9108void AudioPolicyManager::reopenOutputsWithDevices(
9109 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9110 for (const auto& [output, devices] : outputsToReopen) {
9111 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9112 closeOutput(output);
9113 openOutputWithProfileAndDevice(desc->mProfile, devices);
9114 }
jiabina84c3d32022-12-02 18:59:55 +00009115}
9116
jiabinc44b3462022-12-08 12:52:31 -08009117PortHandleVector AudioPolicyManager::getClientsForStream(
9118 audio_stream_type_t streamType) const {
9119 PortHandleVector clients;
9120 for (size_t i = 0; i < mOutputs.size(); ++i) {
9121 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9122 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9123 }
9124 return clients;
9125}
9126
9127void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9128 PortHandleVector clients;
9129 for (auto stream : streams) {
9130 PortHandleVector clientsForStream = getClientsForStream(stream);
9131 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9132 }
9133 mpClientInterface->invalidateTracks(clients);
9134}
9135
jiabin220eea12024-05-17 17:55:20 +00009136void AudioPolicyManager::updateClientsInternalMute(
9137 const sp<android::SwAudioOutputDescriptor> &desc) {
9138 if (!desc->isBitPerfect() ||
9139 !com::android::media::audioserver::
9140 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9141 // This is only used for bit perfect output now.
9142 return;
9143 }
9144 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9145 bool bitPerfectClientInternalMute = false;
9146 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9147 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9148 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9149 bitPerfectClient = client;
9150 continue;
9151 }
9152 bool muted = false;
9153 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9154 // System sound is muted.
9155 muted = true;
9156 } else {
9157 bitPerfectClientInternalMute = true;
9158 }
9159 if (client->setInternalMute(muted)) {
9160 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9161 if (!result.ok()) {
9162 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9163 continue;
9164 }
9165 media::TrackInternalMuteInfo info;
9166 info.portId = result.value();
9167 info.muted = client->getInternalMute();
9168 clientsInternalMute.push_back(std::move(info));
9169 }
9170 }
9171 if (bitPerfectClient != nullptr &&
9172 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9173 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9174 if (result.ok()) {
9175 media::TrackInternalMuteInfo info;
9176 info.portId = result.value();
9177 info.muted = bitPerfectClient->getInternalMute();
9178 clientsInternalMute.push_back(std::move(info));
9179 } else {
9180 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9181 __func__, bitPerfectClient->portId());
9182 }
9183 }
9184 if (!clientsInternalMute.empty()) {
9185 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9186 status != NO_ERROR) {
9187 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9188 }
9189 }
9190}
9191
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009192} // namespace android