blob: e456e89dc4cfdde3238e4582e373558238b44608 [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();
Jaideep Sharma33173202024-06-18 17:46:45 +0530378 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700379 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700380 } // end if is output device
381
Eric Laurente552edb2014-03-10 17:42:56 -0700382 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700383 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100384 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700385 switch (state)
386 {
387 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700388 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700389 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100390 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700391 return INVALID_OPERATION;
392 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700393
Jaideep Sharma33173202024-06-18 17:46:45 +0530394 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
395
Eric Laurent0dd51852019-04-19 18:18:58 -0700396 if (mAvailableInputDevices.add(device) < 0) {
397 return NO_MEMORY;
398 }
399
François Gaffie44481e72016-04-20 07:49:57 +0200400 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
401 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000402 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700403 // Propagate device availability to Engine
404 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200405
Eric Laurent0dd51852019-04-19 18:18:58 -0700406 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700407 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
408
Eric Laurent0dd51852019-04-19 18:18:58 -0700409 mAvailableInputDevices.remove(device);
410
jiabinc0048632023-04-27 22:04:31 +0000411 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100412
413 mHwModules.cleanUpForDevice(device);
414
Eric Laurentd4692962014-05-05 18:13:44 -0700415 return INVALID_OPERATION;
416 }
417
Eric Laurentd4692962014-05-05 18:13:44 -0700418 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700419
420 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700421 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700422 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100423 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700424 return INVALID_OPERATION;
425 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700426
François Gaffie11d30102018-11-02 16:09:09 +0100427 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700428
jiabinc0048632023-04-27 22:04:31 +0000429 // Notify the HAL to prepare to disconnect device
430 broadcastDeviceConnectionState(
431 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700432
François Gaffie11d30102018-11-02 16:09:09 +0100433 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700434
435 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100436
jiabinc0048632023-04-27 22:04:31 +0000437 // Set Disconnect to HALs
438 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
439
Kriti Dangef6be8f2020-11-05 11:58:19 +0100440 // remove device from mReportedFormatsMap cache
441 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700442
443 // Propagate device availability to Engine
444 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700445 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700446
447 default:
François Gaffie11d30102018-11-02 16:09:09 +0100448 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700449 return BAD_VALUE;
450 }
451
Eric Laurent0dd51852019-04-19 18:18:58 -0700452 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700453 // As the input device list can impact the output device selection, update
454 // getDeviceForStrategy() cache
455 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700456
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100457 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200458 // Reconnect Audio Source
459 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
460 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
461 checkAudioSourceForAttributes(attributes);
462 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700463 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100464 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700465 }
466
Eric Laurentb52c1522014-05-20 11:27:36 -0700467 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530468 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700469 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700470 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700471
François Gaffie11d30102018-11-02 16:09:09 +0100472 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700473 return BAD_VALUE;
474}
475
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100476status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
477 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800478 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700479 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
480 devDescr->setName(device_name);
481 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100482}
483
Eric Laurent736a1022019-03-27 18:28:46 -0700484void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
485 audio_policy_dev_state_t state) {
486
487 // the Engine does not have to know about remote submix devices used by dynamic audio policies
488 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
489 return;
490 }
491 mEngine->setDeviceConnectionState(device, state);
492}
493
494
Eric Laurente0720872014-03-11 09:30:41 -0700495audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100496 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700497{
Eric Laurent634b7142016-04-20 13:48:02 -0700498 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800499 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
500 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700501 (strlen(device_address) != 0)/*matchAddress*/);
502
503 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100504 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700505 device, device_address);
506 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
507 }
François Gaffie53615e22015-03-19 09:24:12 +0100508
Eric Laurent3a4311c2014-03-17 12:00:47 -0700509 DeviceVector *deviceVector;
510
Eric Laurente552edb2014-03-10 17:42:56 -0700511 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700512 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700513 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700514 deviceVector = &mAvailableInputDevices;
515 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100516 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700517 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700518 }
Eric Laurent634b7142016-04-20 13:48:02 -0700519
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800520 return (deviceVector->getDevice(
521 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700522 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800523}
524
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
526 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800527 const char *device_name,
528 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800529{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800530 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
531 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800532
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800533 // connect/disconnect only 1 device at a time
534 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
535
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800536 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700537 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800538 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800539 // Nothing to do: device is not connected
540 return NO_ERROR;
541 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800542 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800543
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700544 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800545 // configure codecs.
546 // Handle two specific cases by sending a set parameter to
547 // configure A2DP codecs. No need to toggle device state.
548 // Case 1: A2DP active device switches from primary to primary
549 // module
550 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100551 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700552 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800553 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
554 if (availablePrimaryOutputDevices().contains(devDesc) &&
555 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100556 bool isA2dp = audio_is_a2dp_out_device(device);
557 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
558 : String8(AudioParameter::keyReconfigLeSupported);
559 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800560 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100561 int isReconfigSupported;
562 repliedParameters.getInt(supportKey, isReconfigSupported);
563 if (isReconfigSupported) {
564 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
565 : String8(AudioParameter::keyReconfigLe);
566 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800567 param.add(key, String8("true"));
568 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
569 devDesc->setEncodedFormat(encodedFormat);
570 return NO_ERROR;
571 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700572 }
573 }
cnx421bd2dcc42020-07-11 14:58:44 +0800574 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000575 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800576 for (size_t i = 0; i < mOutputs.size(); i++) {
577 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000578 // mute media strategies to avoid sending the music tail into
579 // the earpiece or headset.
580 if (desc->isStrategyActive(musicStrategy)) {
581 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
582 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
583 tempRecommendedMuteDuration : desc->latency() * 4;
584 if (muteWaitMs < tempMuteDurationMs) {
585 muteWaitMs = tempMuteDurationMs;
586 }
587 }
cnx421bd2dcc42020-07-11 14:58:44 +0800588 setStrategyMute(musicStrategy, true, desc);
589 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
590 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
591 nullptr, true /*fromCache*/).types());
592 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000593 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
594 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
595 // happens after the actual device switch.
596 if (muteWaitMs > 0) {
597 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
598 usleep(muteWaitMs * 1000);
599 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800600 // Toggle the device state: UNAVAILABLE -> AVAILABLE
601 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100602 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800603 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800604 device_address, device_name,
605 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800606 if (status != NO_ERROR) {
607 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
608 status);
609 return status;
610 }
611
612 status = setDeviceConnectionState(device,
613 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800614 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800615 if (status != NO_ERROR) {
616 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
617 status);
618 return status;
619 }
620
621 return NO_ERROR;
622}
623
Pattydd807582021-11-04 21:01:03 +0800624status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
625 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800626{
Pattydd807582021-11-04 21:01:03 +0800627 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800628 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800629 std::unordered_set<audio_format_t> formatSet;
630 sp<HwModule> primaryModule =
631 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700632 if (primaryModule == nullptr) {
633 ALOGE("%s() unable to get primary module", __func__);
634 return NO_INIT;
635 }
Pattydd807582021-11-04 21:01:03 +0800636
637 DeviceTypeSet audioDeviceSet;
638
639 switch(device) {
640 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
641 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
642 break;
643 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800644 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
645 break;
646 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
647 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800648 break;
649 default:
650 ALOGE("%s() device type 0x%08x not supported", __func__, device);
651 return BAD_VALUE;
652 }
653
jiabin9a3361e2019-10-01 09:38:30 -0700654 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800655 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800656 for (const auto& device : declaredDevices) {
657 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800658 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800659 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800660 return status;
661}
662
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100663DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
664{
665 DeviceVector rxSinkdevices{};
666 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
667 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
668 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
669 auto rxSinkDevice = rxSinkdevices.itemAt(0);
670 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
671 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
672 // retrieve Rx Source device descriptor
673 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
674 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
675
676 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
677 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
678 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
679 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
680 return DeviceVector(rxSinkDevice);
681 }
682 }
683 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
684 // the device returned is not necessarily reachable via this output
685 // (filter later by setOutputDevices())
686 return getNewOutputDevices(mPrimaryOutput, fromCache);
687}
688
689status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
690{
François Gaffiedb1755b2023-09-01 11:50:35 +0200691 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100692 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
693 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
694 }
695 return INVALID_OPERATION;
696}
697
698status_t AudioPolicyManager::updateCallRoutingInternal(
699 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700700{
701 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100702 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700703 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200704 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700705 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100706 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700707 }
François Gaffie11d30102018-11-02 16:09:09 +0100708
Francois Gaffie716e1432019-01-14 16:58:59 +0100709 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100710 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200711
Eric Laurentb2fb4102024-06-21 12:25:26 +0000712 if (!fix_call_audio_patch()) {
713 disconnectTelephonyAudioSource(mCallRxSourceClient);
714 disconnectTelephonyAudioSource(mCallTxSourceClient);
715 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200716
717 if (rxDevices.isEmpty()) {
718 ALOGW("%s() no selected output device", __func__);
719 return INVALID_OPERATION;
720 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000721 if (txSourceDevice == nullptr) {
722 ALOGE("%s() selected input device not available", __func__);
723 return INVALID_OPERATION;
724 }
François Gaffiec005e562018-11-06 15:04:49 +0100725
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100726 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100727 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700728
François Gaffie9eb18552018-11-05 10:33:26 +0100729 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700730 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100731 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700732 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100733 // retrieve Rx Source and Tx Sink device descriptors
734 sp<DeviceDescriptor> rxSourceDevice =
735 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
736 String8(),
737 AUDIO_FORMAT_DEFAULT);
738 sp<DeviceDescriptor> txSinkDevice =
739 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
740 String8(),
741 AUDIO_FORMAT_DEFAULT);
742
743 // RX and TX Telephony device are declared by Primary Audio HAL
744 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
745 (telephonyRxModule->getHalVersionMajor() >= 3)) {
746 if (rxSourceDevice == 0 || txSinkDevice == 0) {
747 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100748 ALOGE("%s() no telephony Tx and/or RX device", __func__);
749 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100750 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100751 // createAudioPatchInternal now supports both HW / SW bridging
752 createRxPatch = true;
753 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100754 } else {
755 // If the RX device is on the primary HW module, then use legacy routing method for
756 // voice calls via setOutputDevice() on primary output.
757 // Otherwise, create two audio patches for TX and RX path.
758 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
759 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700760 // If the TX device is also on the primary HW module, setOutputDevice() will take care
761 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100762 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
763 (txSinkDevice != 0);
764 }
765 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
766 // Otherwise, create two audio patches for TX and RX path.
767 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000768 if (fix_call_audio_patch()) {
769 disconnectTelephonyAudioSource(mCallRxSourceClient);
770 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200771 if (!hasPrimaryOutput()) {
772 ALOGW("%s() no primary output available", __func__);
773 return INVALID_OPERATION;
774 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530775 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700776 } else { // create RX path audio patch
David Lif85c5e32024-07-01 13:14:10 +0000777 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800778 // If the TX device is on the primary HW module but RX device is
779 // on other HW module, SinkMetaData of telephony input should handle it
780 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700781 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700782 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100783 // terminate active capture if on the same HW module as the call TX source device
784 // FIXME: would be better to refine to only inputs whose profile connects to the
785 // call TX device but this information is not in the audio patch and logic here must be
786 // symmetric to the one in startInput()
787 for (const auto& activeDesc : mInputs.getActiveInputs()) {
788 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
789 closeActiveClients(activeDesc);
790 }
791 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200792 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000793 } else if (fix_call_audio_patch()) {
794 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800795 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100796 if (waitMs != nullptr) {
797 *waitMs = muteWaitMs;
798 }
799 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800800}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700801
Mikhail Naganov100f0122018-11-29 11:22:16 -0800802bool AudioPolicyManager::isDeviceOfModule(
803 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
804 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
805 if (module != 0) {
806 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
807 .indexOf(devDesc) != NAME_NOT_FOUND
808 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
809 .indexOf(devDesc) != NAME_NOT_FOUND;
810 }
811 return false;
812}
813
David Lif85c5e32024-07-01 13:14:10 +0000814void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200815{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000816 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
817
818 if (fix_call_audio_patch()) {
819 if (mCallRxSourceClient != nullptr) {
820 DeviceVector rxDevices =
821 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
822 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
823 "connectTelephonyRxAudioSource(): no device found for call RX source");
824 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
825 if (mCallRxSourceClient->isConnected()
826 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
827 return;
828 }
829 disconnectTelephonyAudioSource(mCallRxSourceClient);
830 }
831 } else {
832 disconnectTelephonyAudioSource(mCallRxSourceClient);
833 }
834
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200835 const struct audio_port_config source = {
836 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
837 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
838 };
Eric Laurent541a2002024-01-15 18:11:42 +0100839 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000840
Eric Laurentccbd7872024-06-20 12:34:15 +0000841 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Lif85c5e32024-07-01 13:14:10 +0000842 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100843 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
844 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000845 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
846 mCallRxSourceClient->srcDevice()->toString().c_str(),
847 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200848 ALOGE_IF(mCallRxSourceClient == nullptr,
849 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200850}
851
Francois Gaffie601801d2021-06-22 13:27:39 +0200852void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200853{
Francois Gaffie601801d2021-06-22 13:27:39 +0200854 if (clientDesc == nullptr) {
855 return;
856 }
857 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
858 "%s error stopping audio source", __func__);
859 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200860}
861
862void AudioPolicyManager::connectTelephonyTxAudioSource(
863 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
864 uint32_t delayMs)
865{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200866 if (srcDevice == nullptr || sinkDevice == nullptr) {
867 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
868 return;
869 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000870
871 if (fix_call_audio_patch()) {
872 if (mCallTxSourceClient != nullptr) {
873 if (mCallTxSourceClient->isConnected()
874 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
875 return;
876 }
877 disconnectTelephonyAudioSource(mCallTxSourceClient);
878 }
879 } else {
880 disconnectTelephonyAudioSource(mCallTxSourceClient);
881 }
882
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200883 PatchBuilder patchBuilder;
884 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000885
Francois Gaffie601801d2021-06-22 13:27:39 +0200886 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200887 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
888
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200889 struct audio_port_config source = {};
890 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100891 mCallTxSourceClient = new SourceClientDescriptor(
892 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000893 mCommunnicationStrategy, toVolumeSource(aa), true,
894 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100895 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
896
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200897 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
898 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200899 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
900 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200901 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000902 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
903 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200904 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200905 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200906 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200907}
908
Eric Laurente0720872014-03-11 09:30:41 -0700909void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700910{
911 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100912 // store previous phone state for management of sonification strategy below
913 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100914 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100915
916 if (mEngine->setPhoneState(state) != NO_ERROR) {
917 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700918 return;
919 }
François Gaffie2110e042015-03-24 08:41:51 +0100920 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700921 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700922 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700923 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800924 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700925 }
926
François Gaffie2110e042015-03-24 08:41:51 +0100927 /**
928 * Switching to or from incall state or switching between telephony and VoIP lead to force
929 * routing command.
930 */
Eric Laurent74b71512019-11-06 17:21:57 -0800931 bool force = ((isStateInCall(oldState) != isStateInCall(state))
932 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700933
934 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700935 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700936
Eric Laurente552edb2014-03-10 17:42:56 -0700937 int delayMs = 0;
938 if (isStateInCall(state)) {
939 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100940 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
941 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700942 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700943 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700944 // mute media and sonification strategies and delay device switch by the largest
945 // latency of any output where either strategy is active.
946 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100947 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
948 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
949 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700950 (delayMs < (int)desc->latency()*2)) {
951 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700952 }
François Gaffiec005e562018-11-06 15:04:49 +0100953 setStrategyMute(musicStrategy, true, desc);
954 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
955 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
956 nullptr, true /*fromCache*/).types());
957 setStrategyMute(sonificationStrategy, true, desc);
958 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
959 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
960 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700961 }
962 }
963
François Gaffiedb1755b2023-09-01 11:50:35 +0200964 if (state == AUDIO_MODE_IN_CALL) {
965 (void)updateCallRouting(false /*fromCache*/, delayMs);
966 } else {
967 if (oldState == AUDIO_MODE_IN_CALL) {
968 disconnectTelephonyAudioSource(mCallRxSourceClient);
969 disconnectTelephonyAudioSource(mCallTxSourceClient);
970 }
971 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100972 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
973 // force routing command to audio hardware when ending call
974 // even if no device change is needed
975 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
976 rxDevices = mPrimaryOutput->devices();
977 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530978 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700979 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700980 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700981
jiabin3ff8d7d2022-12-13 06:27:44 +0000982 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700983 // reevaluate routing on all outputs in case tracks have been started during the call
984 for (size_t i = 0; i < mOutputs.size(); i++) {
985 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100986 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000987 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
988 && desc->mPreferredAttrInfo != nullptr) {
989 // If the output is using preferred mixer attributes and the audio mode is not normal,
990 // the output need to reopen with default configuration.
991 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
992 continue;
993 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200994 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
995 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530996 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200997 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700998 }
999 }
jiabin3ff8d7d2022-12-13 06:27:44 +00001000 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001001
Eric Laurent96d1dda2022-03-14 17:14:19 +01001002 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
1003
Eric Laurente552edb2014-03-10 17:42:56 -07001004 if (isStateInCall(state)) {
1005 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001006 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001007 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001008 }
1009
1010 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001011 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1012 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001013}
1014
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001015audio_mode_t AudioPolicyManager::getPhoneState() {
1016 return mEngine->getPhoneState();
1017}
1018
Eric Laurente0720872014-03-11 09:30:41 -07001019void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001020 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001021{
François Gaffie2110e042015-03-24 08:41:51 +01001022 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001023 if (config == mEngine->getForceUse(usage)) {
1024 return;
1025 }
Eric Laurente552edb2014-03-10 17:42:56 -07001026
François Gaffie2110e042015-03-24 08:41:51 +01001027 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1028 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1029 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001030 }
François Gaffie2110e042015-03-24 08:41:51 +01001031 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1032 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1033 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001034
1035 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001036 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001037
Eric Laurent22fcda22019-05-17 16:28:47 -07001038 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1039 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001040 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001041 }
1042
Eric Laurentdc462862016-07-19 12:29:53 -07001043 //FIXME: workaround for truncated touch sounds
1044 // to be removed when the problem is handled by system UI
1045 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001046 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1047 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1048 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001049
1050 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001051 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001052}
1053
Eric Laurente0720872014-03-11 09:30:41 -07001054void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001055{
1056 ALOGV("setSystemProperty() property %s, value %s", property, value);
1057}
1058
Dorin Drimusecc9f422022-03-09 17:57:40 +01001059// Find an MSD output profile compatible with the parameters passed.
1060// When "directOnly" is set, restrict search to profiles for direct outputs.
1061sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1062 const DeviceVector& devices,
1063 uint32_t samplingRate,
1064 audio_format_t format,
1065 audio_channel_mask_t channelMask,
1066 audio_output_flags_t flags,
1067 bool directOnly)
1068{
1069 flags = getRelevantFlags(flags, directOnly);
1070
1071 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1072 if (msdModule != nullptr) {
1073 // for the msd module check if there are patches to the output devices
1074 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1075 HwModuleCollection modules;
1076 modules.add(msdModule);
1077 return searchCompatibleProfileHwModules(
1078 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1079 flags, directOnly);
1080 }
1081 }
1082 return nullptr;
1083}
1084
Michael Chana94fbb22018-04-24 14:31:19 +10001085// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1086// search to profiles for direct outputs.
1087sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001088 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001089 uint32_t samplingRate,
1090 audio_format_t format,
1091 audio_channel_mask_t channelMask,
1092 audio_output_flags_t flags,
1093 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001094{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001095 flags = getRelevantFlags(flags, directOnly);
1096
1097 return searchCompatibleProfileHwModules(
1098 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1099}
1100
1101audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1102 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001103 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001104 // only retain flags that will drive the direct output profile selection
1105 // if explicitly requested
1106 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001107 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001108 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1109 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001110 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001111 return flags;
1112}
Eric Laurent861a6282015-05-18 15:40:16 -07001113
Dorin Drimusecc9f422022-03-09 17:57:40 +01001114sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1115 const HwModuleCollection& hwModules,
1116 const DeviceVector& devices,
1117 uint32_t samplingRate,
1118 audio_format_t format,
1119 audio_channel_mask_t channelMask,
1120 audio_output_flags_t flags,
1121 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001122 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001123 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001124 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001125 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001126 samplingRate, NULL /*updatedSamplingRate*/,
1127 format, NULL /*updatedFormat*/,
1128 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001129 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001130 continue;
1131 }
1132 // reject profiles not corresponding to a device currently available
1133 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1134 continue;
1135 }
1136 // reject profiles if connected device does not support codec
1137 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1138 continue;
1139 }
1140 if (!directOnly) {
1141 return curProfile;
1142 }
1143
1144 // when searching for direct outputs, if several profiles are compatible, give priority
1145 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001146 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001147 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001148 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001149 }
1150 profile = curProfile;
1151 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1152 break;
1153 }
Eric Laurente552edb2014-03-10 17:42:56 -07001154 }
1155 }
Eric Laurent861a6282015-05-18 15:40:16 -07001156 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001157}
1158
Eric Laurentfa0f6742021-08-17 18:39:44 +02001159sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001160 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001161{
1162 for (const auto& hwModule : mHwModules) {
1163 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001164 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001165 continue;
1166 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001167 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001168 // reject profiles not corresponding to a device currently available
1169 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1170 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1171 continue;
1172 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001173 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1174 != devices.size()) {
1175 continue;
1176 }
1177 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001178 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1179 return curProfile;
1180 }
1181 }
1182 return nullptr;
1183}
1184
Eric Laurentf4e63452017-11-06 19:31:46 +00001185audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001186{
François Gaffiec005e562018-11-06 15:04:49 +01001187 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001188
1189 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1190 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1191 // format, flags, etc. This may result in some discrepancy for functions that utilize
1192 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1193 // and AudioSystem::getOutputSamplingRate().
1194
François Gaffie11d30102018-11-02 16:09:09 +01001195 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001196 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1197 if (stream == AUDIO_STREAM_MUSIC &&
1198 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1199 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1200 }
1201 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001202
François Gaffie11d30102018-11-02 16:09:09 +01001203 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1204 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001205 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001206}
1207
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001208status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1209 const audio_attributes_t *srcAttr,
1210 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001211{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001212 if (srcAttr != NULL) {
1213 if (!isValidAttributes(srcAttr)) {
1214 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1215 __func__,
1216 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1217 srcAttr->tags);
1218 return BAD_VALUE;
1219 }
1220 *dstAttr = *srcAttr;
1221 } else {
1222 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1223 ALOGE("%s: invalid stream type", __func__);
1224 return BAD_VALUE;
1225 }
François Gaffiec005e562018-11-06 15:04:49 +01001226 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001227 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001228
1229 // Only honor audibility enforced when required. The client will be
1230 // forced to reconnect if the forced usage changes.
1231 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001232 dstAttr->flags = static_cast<audio_flags_mask_t>(
1233 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001234 }
1235
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001236 return NO_ERROR;
1237}
1238
Kevin Rocard153f92d2018-12-18 18:33:28 -08001239status_t AudioPolicyManager::getOutputForAttrInt(
1240 audio_attributes_t *resultAttr,
1241 audio_io_handle_t *output,
1242 audio_session_t session,
1243 const audio_attributes_t *attr,
1244 audio_stream_type_t *stream,
1245 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001246 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001247 audio_output_flags_t *flags,
1248 audio_port_handle_t *selectedDeviceId,
1249 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001250 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001251 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001252 bool *isSpatialized,
1253 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001254{
François Gaffiec005e562018-11-06 15:04:49 +01001255 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001256 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001257 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001258 const sp<DeviceDescriptor> requestedDevice =
1259 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1260
Eric Laurent8a1095a2019-11-08 14:44:16 -08001261 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001262 *isSpatialized = false;
1263
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001264 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1265 if (status != NO_ERROR) {
1266 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001267 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001268 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001269 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001270 }
François Gaffiec005e562018-11-06 15:04:49 +01001271 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001272
François Gaffiec005e562018-11-06 15:04:49 +01001273 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1274 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001275
Oscar Azucena873d10f2023-01-12 18:34:42 -08001276 bool usePrimaryOutputFromPolicyMixes = false;
1277
Kevin Rocard153f92d2018-12-18 18:33:28 -08001278 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1279 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1280 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001281 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001282 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1283 .channel_mask = config->channel_mask,
1284 .format = config->format,
1285 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001286 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001287 mAvailableOutputDevices, requestedDevice, primaryMix,
1288 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001289 if (status != OK) {
1290 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001291 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001292
Kevin Rocard153f92d2018-12-18 18:33:28 -08001293 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001294 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1295 && !audio_is_linear_pcm(config->format)) {
1296 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001297 return BAD_VALUE;
1298 }
1299 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001300 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001301 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1302 primaryMix->mDeviceAddress,
1303 AUDIO_FORMAT_DEFAULT);
1304 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001305 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001306 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1307 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001308 // if a direct output can be opened to deliver the track's multi-channel content to the
1309 // output rather than being downmixed by the primary output, then use this direct
1310 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1311 // mix.
1312 bool tryDirectForChannelMask = policyDesc != nullptr
1313 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1314 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001315 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001316 audio_io_handle_t newOutput;
1317 status = openDirectOutput(
1318 *stream, session, config,
1319 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001320 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001321 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001322 policyDesc = mOutputs.valueFor(newOutput);
1323 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001324 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001325 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001326 policyDesc = nullptr;
1327 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001328 }
1329 if (policyDesc != nullptr) {
1330 policyDesc->mPolicyMix = primaryMix;
1331 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001332 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1333 : AUDIO_PORT_HANDLE_NONE;
1334 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1335 // Remove direct flag as it is not on a direct output.
1336 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1337 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001338
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001339 ALOGV("getOutputForAttr() returns output %d", *output);
1340 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1341 *outputType = API_OUT_MIX_PLAYBACK;
1342 } else {
1343 *outputType = API_OUTPUT_LEGACY;
1344 }
1345 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001346 } else {
1347 if (policyMixDevice != nullptr) {
1348 ALOGE("%s, try to use primary mix but no output found", __func__);
1349 return INVALID_OPERATION;
1350 }
1351 // Fallback to default engine selection as the selected primary mix device is not
1352 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001353 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001354 }
François Gaffiec005e562018-11-06 15:04:49 +01001355 // Virtual sources must always be dynamicaly or explicitly routed
1356 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1357 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1358 return BAD_VALUE;
1359 }
1360 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1361 // in order to let the choice of the order to future vendor engine
1362 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001363
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001364 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001365 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001366 }
1367
Nadav Barb2f18162018-07-18 13:01:53 +03001368 // Set incall music only if device was explicitly set, and fallback to the device which is
1369 // chosen by the engine if not.
1370 // FIXME: provide a more generic approach which is not device specific and move this back
1371 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001372 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001373 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001374 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001375 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001376 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001377 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001378 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001379 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001380 }
1381 }
1382
François Gaffiec005e562018-11-06 15:04:49 +01001383 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1384 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1385 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001386
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001387 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001388 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001389 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001390 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001391 ALOGV("%s() Using MSD devices %s instead of devices %s",
1392 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001393 } else {
1394 *output = AUDIO_IO_HANDLE_NONE;
1395 }
1396 }
1397 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001398 sp<PreferredMixerAttributesInfo> info = nullptr;
1399 if (outputDevices.size() == 1) {
1400 info = getPreferredMixerAttributesInfo(
1401 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001402 mEngine->getProductStrategyForAttributes(*resultAttr),
1403 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001404 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1405 // and it is currently active.
1406 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001407 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001408 info = nullptr;
1409 }
jiabin220eea12024-05-17 17:55:20 +00001410 if (com::android::media::audioserver::
1411 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1412 if (info != nullptr && info->getUid() == uid &&
1413 info->configMatches(*config) &&
1414 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1415 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1416 [this, &outputDevices](audio_usage_t usage) {
1417 return mOutputs.isUsageActiveOnDevice(
1418 usage, outputDevices[0]); }))) {
1419 // Bit-perfect request is not allowed when the phone mode is not normal or
1420 // there is any higher priority user case active.
1421 return INVALID_OPERATION;
1422 }
1423 }
jiabina84c3d32022-12-02 18:59:55 +00001424 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001425 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001426 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001427 // The client will be active if the client is currently preferred mixer owner and the
1428 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001429 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001430 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001431 && info->getUid() == uid
1432 && *output != AUDIO_IO_HANDLE_NONE
1433 // When bit-perfect output is selected for the preferred mixer attributes owner,
1434 // only need to consider the config matches.
1435 && mOutputs.valueFor(*output)->isConfigurationMatched(
1436 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001437
1438 if (*isBitPerfect) {
1439 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1440 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001441 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001442 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001443 AudioProfileVector profiles;
1444 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1445 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001446 const auto channels = profiles[0]->getChannels();
1447 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1448 config->channel_mask = *channels.begin();
1449 }
1450 const auto sampleRates = profiles[0]->getSampleRates();
1451 if (!sampleRates.empty() &&
1452 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1453 config->sample_rate = *sampleRates.begin();
1454 }
jiabinf1c73972022-04-14 16:28:52 -07001455 config->format = profiles[0]->getFormat();
1456 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001457 return INVALID_OPERATION;
1458 }
Paul McLeanaa981192015-03-21 09:55:15 -07001459
François Gaffiec005e562018-11-06 15:04:49 +01001460 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001461 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001462 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001463 *selectedDeviceId = outputDevice->getId();
1464 break;
1465 }
1466 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001467
Eric Laurent8a1095a2019-11-08 14:44:16 -08001468 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1469 *outputType = API_OUTPUT_TELEPHONY_TX;
1470 } else {
1471 *outputType = API_OUTPUT_LEGACY;
1472 }
1473
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001474 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1475
1476 return NO_ERROR;
1477}
1478
1479status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1480 audio_io_handle_t *output,
1481 audio_session_t session,
1482 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001483 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001484 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001485 audio_output_flags_t *flags,
1486 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001487 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001488 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001489 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001490 bool *isSpatialized,
1491 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001492{
1493 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1494 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1495 return INVALID_OPERATION;
1496 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001497 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001498 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001499 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001500 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001501 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001502 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001503 const sp<DeviceDescriptor> requestedDevice =
1504 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1505
1506 // Prevent from storing invalid requested device id in clients
1507 const audio_port_handle_t sanitizedRequestedPortId =
1508 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1509 *selectedDeviceId = sanitizedRequestedPortId;
1510
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001511 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001512 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001513 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1514 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001515 if (status != NO_ERROR) {
1516 return status;
1517 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001518 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001519 if (secondaryOutputs != nullptr) {
1520 for (auto &secondaryMix : secondaryMixes) {
1521 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1522 if (outputDesc != nullptr &&
1523 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1524 secondaryOutputs->push_back(outputDesc->mIoHandle);
1525 weakSecondaryOutputDescs.push_back(outputDesc);
1526 }
1527 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001528 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001529
Eric Laurent8fc147b2018-07-22 19:13:55 -07001530 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001531 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001532 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001533 };
jiabin4ef93452019-09-10 14:29:54 -07001534 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001535
Eric Laurentc209fe42020-06-05 18:11:23 -07001536 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001537 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001538 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001539 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001540 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001541 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001542 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001543 std::move(weakSecondaryOutputDescs),
1544 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001545 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001546
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001547 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1548 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001549
Eric Laurente83b55d2014-11-14 10:06:21 -08001550 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001551}
1552
Eric Laurentc529cf62020-04-17 18:19:10 -07001553status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1554 audio_session_t session,
1555 const audio_config_t *config,
1556 audio_output_flags_t flags,
1557 const DeviceVector &devices,
1558 audio_io_handle_t *output) {
1559
1560 *output = AUDIO_IO_HANDLE_NONE;
1561
1562 // skip direct output selection if the request can obviously be attached to a mixed output
1563 // and not explicitly requested
1564 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1565 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1566 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1567 return NAME_NOT_FOUND;
1568 }
1569
1570 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1571 // This prevents creating an offloaded track and tearing it down immediately after start
1572 // when audioflinger detects there is an active non offloadable effect.
1573 // FIXME: We should check the audio session here but we do not have it in this context.
1574 // This may prevent offloading in rare situations where effects are left active by apps
1575 // in the background.
1576 sp<IOProfile> profile;
1577 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1578 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1579 profile = getProfileForOutput(
1580 devices, config->sample_rate, config->format, config->channel_mask,
1581 flags, true /* directOnly */);
1582 }
1583
1584 if (profile == nullptr) {
1585 return NAME_NOT_FOUND;
1586 }
1587
1588 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1589 for (size_t i = 0; i < mOutputs.size(); i++) {
1590 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1591 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1592 // reuse direct output if currently open by the same client
1593 // and configured with same parameters
1594 if ((config->sample_rate == desc->getSamplingRate()) &&
1595 (config->format == desc->getFormat()) &&
1596 (config->channel_mask == desc->getChannelMask()) &&
1597 (session == desc->mDirectClientSession)) {
1598 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301599 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001600 mOutputs.keyAt(i), session);
1601 *output = mOutputs.keyAt(i);
1602 return NO_ERROR;
1603 }
1604 }
1605 }
1606
1607 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001608 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301609 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1610 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001611 return NAME_NOT_FOUND;
1612 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1613 // MMAP gracefully handles lack of an exclusive track resource by mixing
1614 // above the audio framework. For AAudio to know that the limit is reached,
1615 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301616 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1617 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001618 return NAME_NOT_FOUND;
1619 } else {
1620 // Close outputs on this profile, if available, to free resources for this request
1621 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1622 const auto desc = mOutputs.valueAt(i);
1623 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301624 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1625 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001626 closeOutput(desc->mIoHandle);
1627 }
1628 }
1629 }
1630 }
1631
1632 // Unable to close streams to find free resources for this request
1633 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301634 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1635 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001636 return NAME_NOT_FOUND;
1637 }
1638
Atneya Nairb16666a2023-12-11 20:18:33 -08001639 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001640
Michael Chan6fb34492020-12-08 15:44:49 +11001641 // An MSD patch may be using the only output stream that can service this request. Release
1642 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001643 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001644
Eric Laurentf1f22e72021-07-13 14:04:14 +02001645 status_t status =
1646 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001647
1648 // only accept an output with the requested parameters
1649 if (status != NO_ERROR ||
1650 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1651 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1652 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1653 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1654 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1655 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1656 config->channel_mask, outputDesc->getChannelMask());
1657 if (*output != AUDIO_IO_HANDLE_NONE) {
1658 outputDesc->close();
1659 }
1660 // fall back to mixer output if possible when the direct output could not be open
1661 if (audio_is_linear_pcm(config->format) &&
1662 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1663 return NAME_NOT_FOUND;
1664 }
1665 *output = AUDIO_IO_HANDLE_NONE;
1666 return BAD_VALUE;
1667 }
1668 outputDesc->mDirectOpenCount = 1;
1669 outputDesc->mDirectClientSession = session;
1670
1671 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001672 setOutputDevices(__func__, outputDesc,
1673 devices,
1674 true,
1675 0,
1676 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001677 mPreviousOutputs = mOutputs;
1678 ALOGV("%s returns new direct output %d", __func__, *output);
1679 mpClientInterface->onAudioPortListUpdate();
1680 return NO_ERROR;
1681}
1682
François Gaffie11d30102018-11-02 16:09:09 +01001683audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1684 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001685 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001686 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001687 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001688 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001689 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001690 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001691 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001692{
Andy Hungc88b0642018-04-27 15:42:35 -07001693 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001694
jiabine375d412019-02-26 12:54:53 -08001695 // Discard haptic channel mask when forcing muting haptic channels.
1696 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001697 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1698 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001699
Eric Laurente552edb2014-03-10 17:42:56 -07001700 // open a direct output if required by specified parameters
1701 //force direct flag if offload flag is set: offloading implies a direct output stream
1702 // and all common behaviors are driven by checking only the direct flag
1703 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001704 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1705 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001706 }
Nadav Bar766fb022018-01-07 12:18:03 +02001707 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1708 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001709 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001710
1711 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1712
Eric Laurente83b55d2014-11-14 10:06:21 -08001713 // only allow deep buffering for music stream type
1714 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001715 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001716 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001717 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001718 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1719 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001720 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001721 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001722 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001723 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001724 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001725 audio_is_linear_pcm(config->format) &&
1726 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001727 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001728 AUDIO_OUTPUT_FLAG_DIRECT);
1729 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001730 }
Eric Laurente552edb2014-03-10 17:42:56 -07001731
Carter Hsua3abb402021-10-26 11:11:20 +08001732 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1733 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1734 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1735 }
1736
Eric Laurentf9230d52024-01-26 18:49:09 +01001737 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001738 // was specified and offload or direct playback is not explicitly requested, and there is no
1739 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001740 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001741 if (mSpatializerOutput != nullptr &&
1742 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1743 prefMixerConfigInfo == nullptr &&
1744 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1745 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001746 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001747 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001748 }
1749
Eric Laurentc529cf62020-04-17 18:19:10 -07001750 audio_config_t directConfig = *config;
1751 directConfig.channel_mask = channelMask;
1752 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1753 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001754 return output;
1755 }
1756
Eric Laurent14cbfca2016-03-17 09:42:16 -07001757 // A request for HW A/V sync cannot fallback to a mixed output because time
1758 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001759 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001760 return AUDIO_IO_HANDLE_NONE;
1761 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001762 // A request for Tuner cannot fallback to a mixed output
1763 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1764 return AUDIO_IO_HANDLE_NONE;
1765 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001766
Eric Laurente552edb2014-03-10 17:42:56 -07001767 // ignoring channel mask due to downmix capability in mixer
1768
1769 // open a non direct output
1770
1771 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001772 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001773 // get which output is suitable for the specified stream. The actual
1774 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001775 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001776 if (prefMixerConfigInfo != nullptr) {
1777 for (audio_io_handle_t outputHandle : outputs) {
1778 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1779 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1780 output = outputHandle;
1781 break;
1782 }
1783 }
1784 if (output == AUDIO_IO_HANDLE_NONE) {
1785 // No output open with the preferred profile. Open a new one.
1786 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1787 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1788 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1789 config.format = prefMixerConfigInfo->getConfigBase().format;
1790 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1791 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1792 &config, prefMixerConfigInfo->getFlags());
1793 if (preferredOutput == nullptr) {
1794 ALOGE("%s failed to open output with preferred mixer config", __func__);
1795 } else {
1796 output = preferredOutput->mIoHandle;
1797 }
1798 }
1799 } else {
1800 // at this stage we should ignore the DIRECT flag as no direct output could be
1801 // found earlier
1802 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001803 if (com::android::media::audioserver::
1804 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1805 // If the preferred mixer attributes is null, do not select the bit-perfect output
1806 // unless the bit-perfect output is the only output.
1807 // The bit-perfect output can exist while the passed in preferred mixer attributes
1808 // info is null when it is a high priority client. The high priority clients are
1809 // ringtone or alarm, which is not a bit-perfect use case.
1810 size_t i = 0;
1811 while (i < outputs.size() && outputs.size() > 1) {
1812 auto desc = mOutputs.valueFor(outputs[i]);
1813 // The output descriptor must not be null here.
1814 if (desc->isBitPerfect()) {
1815 outputs.removeItemsAt(i);
1816 } else {
1817 i += 1;
1818 }
1819 }
1820 }
jiabina84c3d32022-12-02 18:59:55 +00001821 output = selectOutput(
1822 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1823 }
Eric Laurente552edb2014-03-10 17:42:56 -07001824 }
François Gaffie11d30102018-11-02 16:09:09 +01001825 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001826 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001827 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001828
Eric Laurente552edb2014-03-10 17:42:56 -07001829 return output;
1830}
1831
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001832sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001833 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1834 mAvailableInputDevices);
1835 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1836}
1837
1838DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1839 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1840 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001841}
1842
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001843const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001844 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001845 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1846 if (msdModule != 0) {
1847 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1848 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1849 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1850 const struct audio_port_config *source = &patch->mPatch.sources[j];
1851 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1852 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001853 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001854 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001855 }
1856 }
1857 }
1858 return msdPatches;
1859}
1860
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001861bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1862 ssize_t index = mAudioPatches.indexOfKey(handle);
1863 if (index < 0) {
1864 return false;
1865 }
1866 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1867 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1868 if (msdModule == nullptr) {
1869 return false;
1870 }
1871 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1872 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1873 return true;
1874 }
1875 index = getMsdOutputPatches().indexOfKey(handle);
1876 if (index < 0) {
1877 return false;
1878 }
1879 return true;
1880}
1881
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001882status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1883 const InputProfileCollection &inputProfiles,
1884 const OutputProfileCollection &outputProfiles,
1885 const sp<DeviceDescriptor> &sourceDevice,
1886 const sp<DeviceDescriptor> &sinkDevice,
1887 AudioProfileVector& sourceProfiles,
1888 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001889 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001890 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001891 return NO_INIT;
1892 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001893 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001894 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001895 return NO_INIT;
1896 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001897 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001898 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1899 inProfile->supportsDevice(sourceDevice)) {
1900 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001901 }
1902 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001903 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001904 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001905 outProfile->supportsDevice(sinkDevice)) {
1906 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001907 }
1908 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001909 return NO_ERROR;
1910}
1911
1912status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1913 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1914 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1915{
Dean Wheatley16809da2022-12-09 14:55:46 +11001916 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1917 static const std::vector<audio_format_t> formatsOrder = {{
1918 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001919 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1920 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001921 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1922 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1923 // preferred).
1924 std::vector<audio_channel_mask_t> masks = {{
1925 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1926 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1927 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1928 // insert index masks (higher counts most preferred) as preferred over position masks
1929 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1930 masks.insert(
1931 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1932 }
1933 return masks;
1934 }();
1935
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001936 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001937 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1938 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001939 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001940 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1941 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001942 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001943 }
1944 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1945 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1946 sinkConfig->format = bestSinkConfig.format;
1947 // For encoded streams force direct flag to prevent downstream mixing.
1948 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1949 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001950 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1951 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001952 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001953 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1954 // raw and IEC61937 framed streams.
1955 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1956 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1957 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001958 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1959 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001960 sourceConfig->channel_mask =
1961 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1962 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1963 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001964 sourceConfig->format = bestSinkConfig.format;
1965 // Copy input stream directly without any processing (e.g. resampling).
1966 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1967 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1968 if (hwAvSync) {
1969 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1970 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1971 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1972 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1973 }
1974 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1975 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1976 sinkConfig->config_mask |= config_mask;
1977 sourceConfig->config_mask |= config_mask;
1978 return NO_ERROR;
1979}
1980
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001981PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1982 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001983{
1984 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001985 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1986 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1987 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1988 if (deviceModule == nullptr) {
1989 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1990 return patchBuilder;
1991 }
1992 const InputProfileCollection inputProfiles = msdIsSource ?
1993 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1994 const OutputProfileCollection outputProfiles = msdIsSource ?
1995 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1996
1997 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1998 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1999 device : getMsdAudioOutDevices().itemAt(0);
2000 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2001
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002002 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2003 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002004 AudioProfileVector sourceProfiles;
2005 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002006 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2007 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002008 for (auto hwAvSync : { true, false }) {
2009 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2010 sourceProfiles, sinkProfiles) != NO_ERROR) {
2011 continue;
2012 }
2013 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2014 &sinkConfig) == NO_ERROR) {
2015 // Found a matching config. Re-create PatchBuilder with this config.
2016 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2017 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002018 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002019 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002020 " supporting PCM format conversion.", __func__);
2021 return patchBuilder;
2022}
2023
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002024status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002025 DeviceVector devices;
2026 if (outputDevices != nullptr && outputDevices->size() > 0) {
2027 devices.add(*outputDevices);
2028 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002029 // Use media strategy for unspecified output device. This should only
2030 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2031 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002032 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002033 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002034 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002035 }
Michael Chan6fb34492020-12-08 15:44:49 +11002036 std::vector<PatchBuilder> patchesToCreate;
2037 for (auto i = 0u; i < devices.size(); ++i) {
2038 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002039 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002040 }
2041 // Retain only the MSD patches associated with outputDevices request.
2042 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002043 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002044 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2045 auto retainedPatch = false;
2046 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2047 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2048 patchesToRemove.removeItemsAt(i);
2049 retainedPatch = true;
2050 break;
2051 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002052 }
Michael Chan6fb34492020-12-08 15:44:49 +11002053 if (retainedPatch) {
2054 it = patchesToCreate.erase(it);
2055 continue;
2056 }
2057 ++it;
2058 }
2059 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2060 return NO_ERROR;
2061 }
2062 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2063 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002064 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002065 }
Michael Chan6fb34492020-12-08 15:44:49 +11002066 status_t status = NO_ERROR;
2067 for (const auto &p : patchesToCreate) {
2068 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2069 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2070 char message[256];
2071 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2072 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2073 currStatus == NO_ERROR ? "Success" : "Error",
2074 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2075 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2076 if (currStatus == NO_ERROR) {
2077 ALOGD("%s", message);
2078 } else {
2079 ALOGE("%s", message);
2080 if (status == NO_ERROR) {
2081 status = currStatus;
2082 }
2083 }
2084 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002085 return status;
2086}
2087
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002088void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2089 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002090 for (size_t i = 0; i < msdPatches.size(); i++) {
2091 const auto& patch = msdPatches[i];
2092 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2093 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2094 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2095 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2096 releaseAudioPatch(patch->getHandle(), mUidCached);
2097 break;
2098 }
2099 }
2100 }
2101}
2102
Dorin Drimus94d94412022-02-02 09:05:02 +01002103bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002104 DeviceVector devicesToCheck =
2105 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002106 AudioPatchCollection msdPatches = getMsdOutputPatches();
2107 for (size_t i = 0; i < msdPatches.size(); i++) {
2108 const auto& patch = msdPatches[i];
2109 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2110 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2111 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2112 const auto& foundDevice = devicesToCheck.getDevice(
2113 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2114 if (foundDevice != nullptr) {
2115 devicesToCheck.remove(foundDevice);
2116 if (devicesToCheck.isEmpty()) {
2117 return true;
2118 }
2119 }
2120 }
2121 }
2122 }
2123 return false;
2124}
2125
Eric Laurente0720872014-03-11 09:30:41 -07002126audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002127 audio_output_flags_t flags,
2128 audio_format_t format,
2129 audio_channel_mask_t channelMask,
2130 uint32_t samplingRate,
2131 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002132{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002133 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2134 "%s called with format %#x", __func__, format);
2135
jiabinebb6af42020-06-09 17:31:17 -07002136 // Return the output that haptic-generating attached to when 1) session id is specified,
2137 // 2) haptic-generating effect exists for given session id and 3) the output that
2138 // haptic-generating effect attached to is in given outputs.
2139 if (sessionId != AUDIO_SESSION_NONE) {
2140 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2141 sessionId, FX_IID_HAPTICGENERATOR);
2142 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2143 return hapticGeneratingOutput;
2144 }
2145 }
2146
Eric Laurent16c66dd2019-05-01 17:54:10 -07002147 // Flags disqualifying an output: the match must happen before calling selectOutput()
2148 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2149 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2150
2151 // Flags expressing a functional request: must be honored in priority over
2152 // other criteria
2153 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2154 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002155 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2156 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002157 // Flags expressing a performance request: have lower priority than serving
2158 // requested sampling rate or channel mask
2159 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2160 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2161 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2162
2163 const audio_output_flags_t functionalFlags =
2164 (audio_output_flags_t)(flags & kFunctionalFlags);
2165 const audio_output_flags_t performanceFlags =
2166 (audio_output_flags_t)(flags & kPerformanceFlags);
2167
2168 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2169
Eric Laurente552edb2014-03-10 17:42:56 -07002170 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002171 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002172 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002173 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002174 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002175 // with tiebreak preferring the minimum number of extra functional flags
2176 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002177 // 3: the output supporting the exact channel mask
2178 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002179 // 5: the output with the highest sampling rate if the requested sample rate is
2180 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002181 // 6: the output with the highest number of requested performance flags
2182 // 7: the output with the bit depth the closest to the requested one
2183 // 8: the primary output
2184 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002185
Eric Laurent16c66dd2019-05-01 17:54:10 -07002186 // matching criteria values in priority order for best matching output so far
2187 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002188
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002189 const bool hasOrphanHaptic =
2190 mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002191 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2192 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2193 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002194
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002195 for (audio_io_handle_t output : outputs) {
2196 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002197 // matching criteria values in priority order for current output
2198 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002199
Eric Laurent16c66dd2019-05-01 17:54:10 -07002200 if (outputDesc->isDuplicated()) {
2201 continue;
2202 }
2203 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2204 continue;
2205 }
Eric Laurent8838a382014-09-08 16:44:28 -07002206
Eric Laurent16c66dd2019-05-01 17:54:10 -07002207 // If haptic channel is specified, use the haptic output if present.
2208 // When using haptic output, same audio format and sample rate are required.
2209 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002210 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002211 // skip if haptic channel specified but output does not support it, or output support haptic
2212 // but there is no haptic channel requested AND no orphan haptic effect exist
2213 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2214 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002215 continue;
2216 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002217 // In the case of audio-coupled-haptic playback, there is no format conversion and
2218 // resampling in the framework, same format/channel/sampleRate for client and the output
2219 // thread is required. In the case of HapticGenerator effect, do not require format
2220 // matching.
2221 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2222 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002223 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002224 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002225 }
2226
2227 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002228 const int matchingFunctionalFlags =
2229 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2230 const int totalFunctionalFlags =
2231 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2232 // Prefer matching functional flags, but subtract unnecessary functional flags.
2233 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002234
2235 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002236 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2237 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002238 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2239 channelCount <= outputChannelCount) {
2240 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002241 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2242 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002243 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002244 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002245 currentMatchCriteria[3] = outputChannelCount;
2246 }
2247
2248 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002249 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002250 int diff; // avoid unsigned integer overflow.
2251 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2252
2253 // prefer the closest output sampling rate greater than or equal to target
2254 // if none exists, prefer the closest output sampling rate less than target.
2255 //
2256 // criteria is offset to make non-negative.
2257 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002258 }
2259
2260 // performance flags match
2261 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2262
2263 // format match
2264 if (format != AUDIO_FORMAT_INVALID) {
2265 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002266 PolicyAudioPort::kFormatDistanceMax -
2267 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002268 }
2269
2270 // primary output match
2271 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2272
2273 // compare match criteria by priority then value
2274 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2275 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2276 bestMatchCriteria = currentMatchCriteria;
2277 bestOutput = output;
2278
2279 std::stringstream result;
2280 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2281 std::ostream_iterator<int>(result, " "));
2282 ALOGV("%s new bestOutput %d criteria %s",
2283 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002284 }
2285 }
2286
Eric Laurent16c66dd2019-05-01 17:54:10 -07002287 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002288}
2289
Eric Laurent8fc147b2018-07-22 19:13:55 -07002290status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002291{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002292 ALOGV("%s portId %d", __FUNCTION__, portId);
2293
2294 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2295 if (outputDesc == 0) {
2296 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002297 return BAD_VALUE;
2298 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002299 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002300
Eric Laurent8fc147b2018-07-22 19:13:55 -07002301 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002302 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002303
jiabin220eea12024-05-17 17:55:20 +00002304 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2305 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2306 && outputDesc->isBitPerfect()) {
2307 // Usually, APM selects bit-perfect output for high priority use cases only when
2308 // bit-perfect output is the only output that can be routed to the selected device.
2309 // However, here is no need to play high priority use cases such as ringtone and alarm
2310 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2311 // can attach to new output.
2312 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2313 __func__, client->stream());
2314 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2315 return DEAD_OBJECT;
2316 }
2317
Eric Laurent733ce942017-12-07 12:18:25 -08002318 status_t status = outputDesc->start();
2319 if (status != NO_ERROR) {
2320 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002321 }
2322
Eric Laurent97ac8712018-07-27 18:59:02 -07002323 uint32_t delayMs;
2324 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002325
2326 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002327 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002328 if (status == DEAD_OBJECT) {
2329 sp<SwAudioOutputDescriptor> desc =
2330 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2331 if (desc == nullptr) {
2332 // This is not common, it may indicate something wrong with the HAL.
2333 ALOGE("%s unable to open output with default config", __func__);
2334 return status;
2335 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002336 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002337 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002338 }
jiabina84c3d32022-12-02 18:59:55 +00002339
2340 // If the client is the first one active on preferred mixer parameters, reopen the output
2341 // if the current mixer parameters doesn't match the preferred one.
2342 if (outputDesc->devices().size() == 1) {
2343 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2344 outputDesc->devices()[0]->getId(), client->strategy());
2345 if (info != nullptr && info->getUid() == client->uid()) {
2346 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2347 info->getConfigBase(), info->getFlags())) {
2348 stopSource(outputDesc, client);
2349 outputDesc->stop();
2350 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2351 config.channel_mask = info->getConfigBase().channel_mask;
2352 config.sample_rate = info->getConfigBase().sample_rate;
2353 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002354 sp<SwAudioOutputDescriptor> desc =
2355 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2356 if (desc == nullptr) {
2357 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002358 }
jiabin220eea12024-05-17 17:55:20 +00002359 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002360 // Intentionally return error to let the client side resending request for
2361 // creating and starting.
2362 return DEAD_OBJECT;
2363 }
2364 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002365 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002366 // If it is first bit-perfect client, reroute all clients that will be routed to
2367 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2368 PortHandleVector clientsToInvalidate;
2369 for (size_t i = 0; i < mOutputs.size(); i++) {
2370 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002371 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002372 continue;
2373 }
2374 for (const auto& c : mOutputs[i]->getClientIterable()) {
2375 clientsToInvalidate.push_back(c->portId());
2376 }
2377 }
2378 if (!clientsToInvalidate.empty()) {
2379 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2380 __func__);
2381 mpClientInterface->invalidateTracks(clientsToInvalidate);
2382 }
2383 }
jiabina84c3d32022-12-02 18:59:55 +00002384 }
2385 }
2386
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002387 if (client->hasPreferredDevice()) {
2388 // playback activity with preferred device impacts routing occurred, inform upper layers
2389 mpClientInterface->onRoutingUpdated();
2390 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002391 if (delayMs != 0) {
2392 usleep(delayMs * 1000);
2393 }
2394
jiabin220eea12024-05-17 17:55:20 +00002395 if (status == NO_ERROR &&
2396 outputDesc->mPreferredAttrInfo != nullptr &&
2397 outputDesc->isBitPerfect() &&
2398 com::android::media::audioserver::
2399 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2400 // A new client is started on bit-perfect output, update all clients internal mute.
2401 updateClientsInternalMute(outputDesc);
2402 }
2403
Eric Laurentc75307b2015-03-17 15:29:32 -07002404 return status;
2405}
2406
Eric Laurent96d1dda2022-03-14 17:14:19 +01002407bool AudioPolicyManager::isLeUnicastActive() const {
2408 if (isInCall()) {
2409 return true;
2410 }
2411 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2412}
2413
2414bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2415 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2416 return false;
2417 }
2418 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2419 ALOGV("%s active %d", __func__, active);
2420 return active;
2421}
2422
Eric Laurent97ac8712018-07-27 18:59:02 -07002423status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2424 const sp<TrackClientDescriptor>& client,
2425 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002426{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002427 // cannot start playback of STREAM_TTS if any other output is being used
2428 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002429
2430 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002431 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002432 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002433 auto clientStrategy = client->strategy();
2434 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002435 if (stream == AUDIO_STREAM_TTS) {
2436 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002437 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002438 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002439 return INVALID_OPERATION;
2440 } else {
2441 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2442 }
2443 } else {
2444 // some playback other than beacon starts
2445 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2446 }
2447
Eric Laurent77305a62016-07-25 16:39:22 -07002448 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002449 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002450 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002451
François Gaffie11d30102018-11-02 16:09:09 +01002452 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002453 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002454 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002455 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002456 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002457 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002458 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002459 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002460 } else {
2461 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002462 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002463 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2464 AUDIO_FORMAT_DEFAULT);
2465 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2466 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002467 }
2468
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002469 // requiresMuteCheck is false when we can bypass mute strategy.
2470 // It covers a common case when there is no materially active audio
2471 // and muting would result in unnecessary delay and dropped audio.
2472 const uint32_t outputLatencyMs = outputDesc->latency();
2473 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002474 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002475
Eric Laurente552edb2014-03-10 17:42:56 -07002476 // increment usage count for this stream on the requested output:
2477 // NOTE that the usage count is the same for duplicated output and hardware output which is
2478 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002479 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002480
2481 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002482 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002483 // Preferred device may be exclusive, use only if no other active clients on this output
2484 devices = DeviceVector(
2485 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2486 } else {
2487 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2488 }
François Gaffie11d30102018-11-02 16:09:09 +01002489 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002490 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002491 }
2492 }
Eric Laurente552edb2014-03-10 17:42:56 -07002493
François Gaffiec005e562018-11-06 15:04:49 +01002494 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002495 selectOutputForMusicEffects();
2496 }
2497
François Gaffie1c878552018-11-22 16:53:21 +01002498 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002499 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002500 if (devices.isEmpty()) {
2501 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002502 }
François Gaffiec005e562018-11-06 15:04:49 +01002503 bool shouldWait =
2504 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2505 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2506 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002507 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002508 const bool needToCloseBitPerfectOutput =
2509 (com::android::media::audioserver::
2510 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2511 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2512 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002513 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002514 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002515 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002516 // An output has a shared device if
2517 // - managed by the same hw module
2518 // - supports the currently selected device
2519 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002520 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002521
Eric Laurent77305a62016-07-25 16:39:22 -07002522 // force a device change if any other output is:
2523 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002524 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002525 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002526 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002527 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002528 // change the device currently selected by the other output.
2529 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002530 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002531 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002532 force = true;
2533 }
2534 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002535 // a notification so that audio focus effect can propagate, or that a mute/unmute
2536 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002537 const uint32_t latencyMs = desc->latency();
2538 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2539
2540 if (shouldWait && isActive && (waitMs < latencyMs)) {
2541 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002542 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002543
2544 // Require mute check if another output is on a shared device
2545 // and currently active to have proper drain and avoid pops.
2546 // Note restoring AudioTracks onto this output needs to invoke
2547 // a volume ramp if there is no mute.
2548 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002549
2550 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2551 outputsToReopen.push_back(desc);
2552 }
Eric Laurente552edb2014-03-10 17:42:56 -07002553 }
2554 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002555
jiabin220eea12024-05-17 17:55:20 +00002556 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002557 // If the output is open with preferred mixer attributes, but the routed device is
2558 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2559 // changed.
2560 return DEAD_OBJECT;
2561 }
jiabin220eea12024-05-17 17:55:20 +00002562 for (auto& outputToReopen : outputsToReopen) {
2563 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2564 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002565 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302566 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2567 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002568
Eric Laurente552edb2014-03-10 17:42:56 -07002569 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002570 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002571 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002572 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002573 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002574 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002575 outputDesc->useHwGain() /*force*/)) {
2576 // request AudioService to reinitialize the volume curves asynchronously
2577 ALOGE("checkAndSetVolume failed, requesting volume range init");
2578 mpClientInterface->onVolumeRangeInitRequest();
2579 };
Eric Laurente552edb2014-03-10 17:42:56 -07002580
2581 // update the outputs if starting an output with a stream that can affect notification
2582 // routing
2583 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002584
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002585 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002586 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002587 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002588 }
Eric Laurentdc462862016-07-19 12:29:53 -07002589
2590 if (waitMs > muteWaitMs) {
2591 *delayMs = waitMs - muteWaitMs;
2592 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002593
2594 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2595 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2596 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2597 // change occurs after the MixerThread starts and causes a stream volume
2598 // glitch.
2599 //
2600 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002601 }
Eric Laurentdc462862016-07-19 12:29:53 -07002602
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002603 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002604 mEngine->getForceUse(
2605 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002606 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002607 }
2608
Eric Laurent97ac8712018-07-27 18:59:02 -07002609 // Automatically enable the remote submix input when output is started on a re routing mix
2610 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002611 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2612 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002613 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2614 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2615 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002616 "remote-submix",
2617 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002618 }
2619
Eric Laurent96d1dda2022-03-14 17:14:19 +01002620 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2621
Eric Laurente552edb2014-03-10 17:42:56 -07002622 return NO_ERROR;
2623}
2624
Eric Laurent96d1dda2022-03-14 17:14:19 +01002625void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2626 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2627 bool isUnicastActive = isLeUnicastActive();
2628
2629 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002630 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002631 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2632 for (size_t i = 0; i < mOutputs.size(); i++) {
2633 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2634 if (desc != ignoredOutput && desc->isActive()
2635 && ((isUnicastActive &&
2636 !desc->devices().
2637 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2638 || (wasUnicastActive &&
2639 !desc->devices().getDevicesFromTypes(
2640 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2641 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2642 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002643 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002644 // If the device is using preferred mixer attributes, the output need to reopen
2645 // with default configuration when the new selected devices are different from
2646 // current routing devices.
2647 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2648 continue;
2649 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302650 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002651 // re-apply device specific volume if not done by setOutputDevice()
2652 if (!force) {
2653 applyStreamVolumes(desc, newDevices.types(), delayMs);
2654 }
2655 }
2656 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002657 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002658 }
2659}
2660
Eric Laurent8fc147b2018-07-22 19:13:55 -07002661status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002662{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002663 ALOGV("%s portId %d", __FUNCTION__, portId);
2664
2665 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2666 if (outputDesc == 0) {
2667 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002668 return BAD_VALUE;
2669 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002670 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002671
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002672 if (client->hasPreferredDevice(true)) {
2673 // playback activity with preferred device impacts routing occurred, inform upper layers
2674 mpClientInterface->onRoutingUpdated();
2675 }
2676
Eric Laurent97ac8712018-07-27 18:59:02 -07002677 ALOGV("stopOutput() output %d, stream %d, session %d",
2678 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002679
Eric Laurent97ac8712018-07-27 18:59:02 -07002680 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002681
Eric Laurent733ce942017-12-07 12:18:25 -08002682 if (status == NO_ERROR ) {
2683 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002684 } else {
2685 return status;
2686 }
2687
2688 if (outputDesc->devices().size() == 1) {
2689 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2690 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002691 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002692 if (info != nullptr && info->getUid() == client->uid()) {
2693 info->decreaseActiveClient();
2694 if (info->getActiveClientCount() == 0) {
2695 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002696 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002697 }
2698 }
jiabin220eea12024-05-17 17:55:20 +00002699 if (com::android::media::audioserver::
2700 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2701 !outputReopened && outputDesc->isBitPerfect()) {
2702 // Only need to update the clients' internal mute when the output is bit-perfect and it
2703 // is not reopened.
2704 updateClientsInternalMute(outputDesc);
2705 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002706 }
2707 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002708}
2709
Eric Laurent97ac8712018-07-27 18:59:02 -07002710status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2711 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002712{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002713 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002714 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002715 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002716 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002717
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002718 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2719
François Gaffie1c878552018-11-22 16:53:21 +01002720 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2721 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002722 // Automatically disable the remote submix input when output is stopped on a
2723 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002724 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002725 if (isSingleDeviceType(
2726 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002727 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002728 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002729 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2730 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002731 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002732 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002733 }
2734 }
2735 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002736 if (client->hasPreferredDevice(true) &&
2737 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002738 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002739 forceDeviceUpdate = true;
2740 }
2741
Eric Laurente552edb2014-03-10 17:42:56 -07002742 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002743 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002744
Eric Laurente552edb2014-03-10 17:42:56 -07002745 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002746 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002747 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002748 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002749
2750 // If the routing does not change, if an output is routed on a device using HwGain
2751 // (aka setAudioPortConfig) and there are still active clients following different
2752 // volume group(s), force reapply volume
2753 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2754 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2755
Eric Laurente552edb2014-03-10 17:42:56 -07002756 // delay the device switch by twice the latency because stopOutput() is executed when
2757 // the track stop() command is received and at that time the audio track buffer can
2758 // still contain data that needs to be drained. The latency only covers the audio HAL
2759 // and kernel buffers. Also the latency does not always include additional delay in the
2760 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302761 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002762 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002763
2764 // force restoring the device selection on other active outputs if it differs from the
2765 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002766 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002767 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002768 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002769 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002770 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002771 desc->isActive() &&
2772 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002773 (newDevices != desc->devices())) {
2774 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2775 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002776
jiabin220eea12024-05-17 17:55:20 +00002777 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002778 // If the device is using preferred mixer attributes, the output need to
2779 // reopen with default configuration when the new selected devices are
2780 // different from current routing devices.
2781 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2782 continue;
2783 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302784 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002785
Eric Laurent57de36c2016-09-28 16:59:11 -07002786 // re-apply device specific volume if not done by setOutputDevice()
2787 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002788 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002789 }
Eric Laurente552edb2014-03-10 17:42:56 -07002790 }
2791 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002792 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002793 // update the outputs if stopping one with a stream that can affect notification routing
2794 handleNotificationRoutingForStream(stream);
2795 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002796
2797 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2798 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002799 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002800 }
2801
François Gaffiec005e562018-11-06 15:04:49 +01002802 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002803 selectOutputForMusicEffects();
2804 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002805
2806 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2807
Eric Laurente552edb2014-03-10 17:42:56 -07002808 return NO_ERROR;
2809 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002810 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002811 return INVALID_OPERATION;
2812 }
2813}
2814
jiabinbce0c1d2020-10-05 11:20:18 -07002815bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002816{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002817 ALOGV("%s portId %d", __FUNCTION__, portId);
2818
2819 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2820 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002821 // If an output descriptor is closed due to a device routing change,
2822 // then there are race conditions with releaseOutput from tracks
2823 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2824 // destroyed shortly thereafter.
2825 //
2826 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002827 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002828 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002829 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002830
2831 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002832
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302833 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2834 if (outputDesc->isClientActive(client)) {
2835 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2836 stopOutput(portId);
2837 }
2838
Eric Laurent8fc147b2018-07-22 19:13:55 -07002839 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2840 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002841 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002842 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002843 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002844 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002845 if (--outputDesc->mDirectOpenCount == 0) {
2846 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002847 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002848 }
2849 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302850
Andy Hung39efb7a2018-09-26 15:39:28 -07002851 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002852 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2853 // The output is pending reopened to query dynamic profiles and
2854 // there is no active clients
2855 closeOutput(outputDesc->mIoHandle);
2856 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2857 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2858 if (newOutputDesc == nullptr) {
2859 ALOGE("%s failed to open output", __func__);
2860 }
2861 return true;
2862 }
2863 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002864}
2865
Eric Laurentcaf7f482014-11-25 17:50:47 -08002866status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2867 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002868 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002869 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002870 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002871 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002872 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002873 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002874 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002875 audio_port_handle_t *portId,
2876 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002877{
François Gaffiec005e562018-11-06 15:04:49 +01002878 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002879 "flags %#x attributes=%s requested device ID %d",
2880 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2881 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002882
Eric Laurentad2e7b92017-09-14 20:06:42 -07002883 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002884 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002885 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002886 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002887 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002888 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002889 sp<RecordClientDescriptor> clientDesc;
2890 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002891 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002892 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002893
2894 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2895 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2896 return INVALID_OPERATION;
2897 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002898
Francois Gaffie716e1432019-01-14 16:58:59 +01002899 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2900 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002901 }
2902
Paul McLean466dc8e2015-04-17 13:15:36 -06002903 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002904 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002905 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002906
Eric Laurentad2e7b92017-09-14 20:06:42 -07002907 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2908 // possible
2909 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2910 *input != AUDIO_IO_HANDLE_NONE) {
2911 ssize_t index = mInputs.indexOfKey(*input);
2912 if (index < 0) {
2913 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2914 status = BAD_VALUE;
2915 goto error;
2916 }
2917 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002918 RecordClientVector clients = inputDesc->getClientsForSession(session);
2919 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002920 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2921 status = BAD_VALUE;
2922 goto error;
2923 }
2924 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2925 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002926 // corresponds to a new client and is only permitted from the same UID.
2927 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002928 if (clients.size() > 1) {
2929 for (const auto& client : clients) {
2930 // The client map is ordered by key values (portId) and portIds are allocated
2931 // incrementaly. So the first client in this list is the one opened by audio flinger
2932 // when the mmap stream is created and should be ignored as it does not correspond
2933 // to an actual client
2934 if (client == *clients.cbegin()) {
2935 continue;
2936 }
2937 if (uid != client->uid() && !client->isSilenced()) {
2938 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2939 uid, client->portId(), client->uid());
2940 status = INVALID_OPERATION;
2941 goto error;
2942 }
Eric Laurent331679c2018-04-16 17:03:16 -07002943 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002944 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002945 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002946 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002947
Eric Laurentfecbceb2021-02-09 14:46:43 +01002948 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002949 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002950 }
2951
2952 *input = AUDIO_IO_HANDLE_NONE;
2953 *inputType = API_INPUT_INVALID;
2954
Francois Gaffie716e1432019-01-14 16:58:59 +01002955 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002956 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002957 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002958 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002959 ALOGW("%s could not find input mix for attr %s",
2960 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002961 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002962 }
jiabinc1de2df2019-05-07 14:26:40 -07002963 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2964 String8(attr->tags + strlen("addr=")),
2965 AUDIO_FORMAT_DEFAULT);
2966 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002967 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002968 __func__, attributes.source, attributes.tags);
2969 status = BAD_VALUE;
2970 goto error;
2971 }
2972
Kevin Rocard25f9b052019-02-27 15:08:54 -08002973 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2974 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2975 } else {
2976 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2977 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002978 if (virtualDeviceId) {
2979 *virtualDeviceId = policyMix->mVirtualDeviceId;
2980 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002981 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002982 if (explicitRoutingDevice != nullptr) {
2983 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002984 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002985 // Prevent from storing invalid requested device id in clients
2986 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002987 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002988 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2989 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002990 }
François Gaffie11d30102018-11-02 16:09:09 +01002991 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002992 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002993 status = BAD_VALUE;
2994 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002995 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002996 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2997 *inputType = API_INPUT_MIX_CAPTURE;
2998 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002999 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3000 // there is an external policy, but this input is attached to a mix of recorders,
3001 // meaning it receives audio injected into the framework, so the recorder doesn't
3002 // know about it and is therefore considered "legacy"
3003 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003004
3005 if (virtualDeviceId) {
3006 *virtualDeviceId = policyMix->mVirtualDeviceId;
3007 }
François Gaffie11d30102018-11-02 16:09:09 +01003008 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003009 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003010 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003011 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003012 } else {
3013 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003014 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003015
Eric Laurent599c7582015-12-07 18:05:55 -08003016 }
3017
François Gaffiec005e562018-11-06 15:04:49 +01003018 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003019 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003020 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003021 AudioProfileVector profiles;
3022 status_t ret = getProfilesForDevices(
3023 DeviceVector(device), profiles, flags, true /*isInput*/);
3024 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003025 const auto channels = profiles[0]->getChannels();
3026 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3027 config->channel_mask = *channels.begin();
3028 }
3029 const auto sampleRates = profiles[0]->getSampleRates();
3030 if (!sampleRates.empty() &&
3031 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3032 config->sample_rate = *sampleRates.begin();
3033 }
jiabinf1c73972022-04-14 16:28:52 -07003034 config->format = profiles[0]->getFormat();
3035 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003036 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003037 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003038
Marvin Ramine5a122d2023-12-07 13:57:59 +01003039
3040 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3041 *virtualDeviceId = policyMix->mVirtualDeviceId;
3042 }
3043
Eric Laurent8f42ea12018-08-08 09:08:25 -07003044exit:
3045
François Gaffiec005e562018-11-06 15:04:49 +01003046 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3047 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003048
Francois Gaffie716e1432019-01-14 16:58:59 +01003049 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003050 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003051 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003052
Mikhail Naganov2996f672019-04-18 12:29:59 -07003053 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003054 requestedDeviceId, attributes.source, flags,
3055 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003056 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003057 // Move (if found) effect for the client session to its input
3058 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003059 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003060
3061 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3062 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003063
Eric Laurent599c7582015-12-07 18:05:55 -08003064 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003065
3066error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003067 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003068}
3069
3070
François Gaffie11d30102018-11-02 16:09:09 +01003071audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003072 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003073 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003074 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003075 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003076 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003077{
3078 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003079 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003080 bool isSoundTrigger = false;
3081
François Gaffiec005e562018-11-06 15:04:49 +01003082 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003083 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3084 if (index >= 0) {
3085 input = mSoundTriggerSessions.valueFor(session);
3086 isSoundTrigger = true;
3087 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3088 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3089 } else {
3090 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003091 }
François Gaffiec005e562018-11-06 15:04:49 +01003092 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003093 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003094 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003095 }
3096
Carter Hsua3abb402021-10-26 11:11:20 +08003097 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3098 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3099 }
3100
Eric Laurentfe231122017-11-17 17:48:06 -08003101 // sampling rate and flags may be updated by getInputProfile
3102 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3103 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003104 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003105 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003106 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003107 // find a compatible input profile (not necessarily identical in parameters)
3108 sp<IOProfile> profile = getInputProfile(
3109 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3110 if (profile == nullptr) {
3111 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003112 }
jiabin2fd710d2022-05-02 23:20:22 +00003113
Glenn Kasten05ddca52016-02-11 08:17:12 -08003114 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003115 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003116 if (samplingRate == 0) {
3117 samplingRate = profileSamplingRate;
3118 }
Eric Laurente552edb2014-03-10 17:42:56 -07003119
Eric Laurent322b4d22015-04-03 15:57:54 -07003120 if (profile->getModuleHandle() == 0) {
3121 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003122 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003123 }
3124
Eric Laurentec376dc2021-04-08 20:41:22 +02003125 // Reuse an already opened input if a client with the same session ID already exists
3126 // on that input
3127 for (size_t i = 0; i < mInputs.size(); i++) {
3128 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3129 if (desc->mProfile != profile) {
3130 continue;
3131 }
3132 RecordClientVector clients = desc->clientsList();
3133 for (const auto &client : clients) {
3134 if (session == client->session()) {
3135 return desc->mIoHandle;
3136 }
3137 }
3138 }
3139
Eric Laurentc71b11b2024-06-03 12:54:53 +00003140 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003141 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003142 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3143 // First pick best candidate for preemption (there may not be any):
3144 // - Preempt and input if:
3145 // - It has only strictly lower priority use cases than the new client
3146 // - It has equal priority use cases than the new client, was not
3147 // opened thanks to preemption or has been active since opened.
3148 // - Order the preemption candidates by inactive first and priority second
3149 sp<AudioInputDescriptor> closeCandidate;
3150 int leastCloseRank = INT_MAX;
3151 static const int sCloseActive = 0x100;
3152
3153 for (size_t i = 0; i < mInputs.size(); i++) {
3154 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3155 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003156 continue;
3157 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003158 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3159 if (topPrioClient == nullptr) {
3160 continue;
3161 }
3162 int topPrio = source_priority(topPrioClient->source());
3163 if (topPrio < source_priority(attributes.source)
3164 || (topPrio == source_priority(attributes.source)
3165 && !desc->isPreemptor())) {
3166 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3167 if (closeRank < leastCloseRank) {
3168 leastCloseRank = closeRank;
3169 closeCandidate = desc;
3170 }
3171 }
3172 }
3173
3174 if (closeCandidate != nullptr) {
3175 closeInput(closeCandidate->mIoHandle);
3176 // Mark the new input as being issued from a preemption
3177 // so that is will not be preempted later
3178 isPreemptor = true;
3179 } else {
3180 // Then pick the best reusable input (There is always one)
3181 // The order of preference is:
3182 // 1) active inputs with same use case as the new client
3183 // 2) inactive inputs with same use case
3184 // 3) active inputs with different use cases
3185 // 4) inactive inputs with different use cases
3186 sp<AudioInputDescriptor> reuseCandidate;
3187 int leastReuseRank = INT_MAX;
3188 static const int sReuseDifferentUseCase = 0x100;
3189
3190 for (size_t i = 0; i < mInputs.size(); i++) {
3191 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3192 if (desc->mProfile != profile) {
3193 continue;
3194 }
3195 int reuseRank = sReuseDifferentUseCase;
3196 for (const auto& client: desc->getClientIterable()) {
3197 if (client->source() == attributes.source) {
3198 reuseRank = 0;
3199 break;
3200 }
3201 }
3202 reuseRank += desc->isActive() ? 0 : 1;
3203 if (reuseRank < leastReuseRank) {
3204 leastReuseRank = reuseRank;
3205 reuseCandidate = desc;
3206 }
3207 }
3208 return reuseCandidate->mIoHandle;
3209 }
3210 } else { // fix_input_sharing_logic()
3211 for (size_t i = 0; i < mInputs.size(); ) {
3212 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3213 if (desc->mProfile != profile) {
3214 i++;
3215 continue;
3216 }
3217 // if sound trigger, reuse input if used by other sound trigger on same session
3218 // else
3219 // reuse input if active client app is not in IDLE state
3220 //
3221 RecordClientVector clients = desc->clientsList();
3222 bool doClose = false;
3223 for (const auto& client : clients) {
3224 if (isSoundTrigger != client->isSoundTrigger()) {
3225 continue;
3226 }
3227 if (client->isSoundTrigger()) {
3228 if (session == client->session()) {
3229 return desc->mIoHandle;
3230 }
3231 continue;
3232 }
3233 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003234 return desc->mIoHandle;
3235 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003236 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003237 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003238 if (doClose) {
3239 closeInput(desc->mIoHandle);
3240 } else {
3241 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003242 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003243 }
3244 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003245 }
3246
Eric Laurentc71b11b2024-06-03 12:54:53 +00003247 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3248 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003249
Eric Laurentfe231122017-11-17 17:48:06 -08003250 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3251 lConfig.sample_rate = profileSamplingRate;
3252 lConfig.channel_mask = profileChannelMask;
3253 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003254
François Gaffie11d30102018-11-02 16:09:09 +01003255 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003256
3257 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003258 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003259 (profileSamplingRate != lConfig.sample_rate) ||
3260 !audio_formats_match(profileFormat, lConfig.format) ||
3261 (profileChannelMask != lConfig.channel_mask)) {
3262 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003263 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003264 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003265 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003266 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003267 }
Eric Laurent599c7582015-12-07 18:05:55 -08003268 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003269 }
3270
Eric Laurentc722f302014-12-10 11:21:49 -08003271 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003272
Eric Laurent599c7582015-12-07 18:05:55 -08003273 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003274 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003275
Eric Laurent599c7582015-12-07 18:05:55 -08003276 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003277}
3278
Eric Laurent4eb58f12018-12-07 16:41:02 -08003279status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003280{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003281 ALOGV("%s portId %d", __FUNCTION__, portId);
3282
3283 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3284 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003285 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003286 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003287 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003288 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003289 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003290 if (client->active()) {
3291 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3292 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003293 }
3294
Eric Laurent8f42ea12018-08-08 09:08:25 -07003295 audio_session_t session = client->session();
3296
Eric Laurent4eb58f12018-12-07 16:41:02 -08003297 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003298
Eric Laurent4eb58f12018-12-07 16:41:02 -08003299 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003300
Eric Laurent4eb58f12018-12-07 16:41:02 -08003301 status_t status = inputDesc->start();
3302 if (status != NO_ERROR) {
3303 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003304 }
Eric Laurente552edb2014-03-10 17:42:56 -07003305
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003306 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003307 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003308 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003309
Eric Laurent8f42ea12018-08-08 09:08:25 -07003310 // indicate active capture to sound trigger service if starting capture from a mic on
3311 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003312 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003313 if (device != nullptr) {
3314 status = setInputDevice(input, device, true /* force */);
3315 } else {
3316 ALOGW("%s no new input device can be found for descriptor %d",
3317 __FUNCTION__, inputDesc->getId());
3318 status = BAD_VALUE;
3319 }
Eric Laurente552edb2014-03-10 17:42:56 -07003320
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003321 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003322 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003323 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003324 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003325 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3326 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003327 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003328 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003329
François Gaffie11d30102018-11-02 16:09:09 +01003330 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3331 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003332 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003333 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003334 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003335
Eric Laurent8f42ea12018-08-08 09:08:25 -07003336 // automatically enable the remote submix output when input is started if not
3337 // used by a policy mix of type MIX_TYPE_RECORDERS
3338 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003339 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003340 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003341 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003342 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003343 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3344 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003345 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003346 if (address != "") {
3347 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3348 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003349 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003350 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003351 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003352 } else if (status != NO_ERROR) {
3353 // Restore client activity state.
3354 inputDesc->setClientActive(client, false);
3355 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003356 }
3357
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003358 ALOGV("%s input %d source = %d status = %d exit",
3359 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003360
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003361 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003362}
3363
Eric Laurent8fc147b2018-07-22 19:13:55 -07003364status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003365{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003366 ALOGV("%s portId %d", __FUNCTION__, portId);
3367
3368 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3369 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003370 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003371 return BAD_VALUE;
3372 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003373 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003374 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003375 if (!client->active()) {
3376 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003377 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003378 }
Carter Hsue6139d52021-07-08 10:30:20 +08003379 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003380 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003381
Eric Laurent8f42ea12018-08-08 09:08:25 -07003382 inputDesc->stop();
3383 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003384 auto current_source = inputDesc->source();
3385 setInputDevice(input, getNewInputDevice(inputDesc),
3386 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003387 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003388 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003389 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003390 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003391 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3392 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003393 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003394 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003395
3396 // automatically disable the remote submix output when input is stopped if not
3397 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003398 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003399 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003400 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003401 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003402 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3403 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003404 }
3405 if (address != "") {
3406 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3407 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003408 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003409 }
3410 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003411 resetInputDevice(input);
3412
3413 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3414 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003415 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3416 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003417 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003418 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003419 }
3420 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003421 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003422 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003423}
3424
Eric Laurent8fc147b2018-07-22 19:13:55 -07003425void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003426{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003427 ALOGV("%s portId %d", __FUNCTION__, portId);
3428
3429 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3430 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003431 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003432 return;
3433 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003434 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003435 audio_io_handle_t input = inputDesc->mIoHandle;
3436
Eric Laurent8f42ea12018-08-08 09:08:25 -07003437 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003438
Andy Hung39efb7a2018-09-26 15:39:28 -07003439 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003440
3441 // If no more clients are present in this session, park effects to an orphan chain
3442 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3443 if (clientsOnSession.size() == 0) {
3444 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3445 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003446 if (inputDesc->getClientCount() > 0) {
3447 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003448 return;
3449 }
3450
Eric Laurent05b90f82014-08-27 15:32:29 -07003451 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003452 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003453 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003454}
3455
Eric Laurent8f42ea12018-08-08 09:08:25 -07003456void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003457{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003458 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003459
3460 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003461 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003462 }
3463}
3464
Eric Laurent8f42ea12018-08-08 09:08:25 -07003465void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3466{
3467 stopInput(portId);
3468 releaseInput(portId);
3469}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003470
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003471bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3472 if (input->clientsList().size() == 0
3473 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3474 return true;
3475 }
3476 for (const auto& client : input->clientsList()) {
3477 sp<DeviceDescriptor> device =
3478 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3479 client->session());
3480 if (!input->supportedDevices().contains(device)) {
3481 return true;
3482 }
3483 }
3484 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3485 return false;
3486}
3487
Eric Laurent0dd51852019-04-19 18:18:58 -07003488void AudioPolicyManager::checkCloseInputs() {
3489 // After connecting or disconnecting an input device, close input if:
3490 // - it has no client (was just opened to check profile) OR
3491 // - none of its supported devices are connected anymore OR
3492 // - one of its clients cannot be routed to one of its supported
3493 // devices anymore. Otherwise update device selection
3494 std::vector<audio_io_handle_t> inputsToClose;
3495 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003496 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003497 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003498 }
3499 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003500 for (const audio_io_handle_t handle : inputsToClose) {
3501 ALOGV("%s closing input %d", __func__, handle);
3502 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003503 }
Eric Laurentd4692962014-05-05 18:13:44 -07003504}
3505
Vlad Popa87e0e582024-05-20 18:49:20 -07003506status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3507 const char *address __unused,
3508 bool enabled,
3509 audio_stream_type_t streamToDriveAbs)
3510{
Vlad Popaa536eb32024-07-18 16:00:35 -07003511 if (!enabled) {
3512 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3513 return NO_ERROR;
3514 }
3515
Vlad Popa87e0e582024-05-20 18:49:20 -07003516 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3517 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3518 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3519 toString(streamToDriveAbs).c_str());
3520 return BAD_VALUE;
3521 }
3522
Vlad Popaa536eb32024-07-18 16:00:35 -07003523 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
Vlad Popa87e0e582024-05-20 18:49:20 -07003524 return NO_ERROR;
3525}
3526
François Gaffie251c7f02018-11-07 10:41:08 +01003527void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003528{
3529 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003530 if (indexMin < 0 || indexMax < 0) {
3531 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3532 return;
3533 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003534 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003535
3536 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003537 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3538 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003539 continue;
3540 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003541 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003542 }
Eric Laurente552edb2014-03-10 17:42:56 -07003543}
3544
Eric Laurente0720872014-03-11 09:30:41 -07003545status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003546 int index,
3547 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003548{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003549 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003550 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3551 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3552 return NO_ERROR;
3553 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303554 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3555 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003556 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003557}
3558
Eric Laurente0720872014-03-11 09:30:41 -07003559status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003560 int *index,
3561 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003562{
François Gaffiec005e562018-11-06 15:04:49 +01003563 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3564 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003565 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003566 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003567 deviceTypes = mEngine->getOutputDevicesForStream(
3568 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003569 }
jiabin9a3361e2019-10-01 09:38:30 -07003570 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003571}
3572
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003573status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003574 int index,
3575 audio_devices_t device)
3576{
3577 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003578 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3579 if (group == VOLUME_GROUP_NONE) {
3580 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003581 return BAD_VALUE;
3582 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003583 ALOGV("%s: group %d matching with %s index %d",
3584 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003585 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003586 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003587 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003588 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3589 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3590 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3591 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003592 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3593
3594 status = setVolumeCurveIndex(index, device, curves);
3595 if (status != NO_ERROR) {
3596 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3597 return status;
3598 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003599
jiabin9a3361e2019-10-01 09:38:30 -07003600 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003601 auto curCurvAttrs = curves.getAttributes();
3602 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3603 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003604 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003605 } else if (!curves.getStreamTypes().empty()) {
3606 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003607 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003608 } else {
3609 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3610 return BAD_VALUE;
3611 }
jiabin9a3361e2019-10-01 09:38:30 -07003612 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3613 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003614
François Gaffiecfe17322018-11-07 13:41:29 +01003615 // update volume on all outputs and streams matching the following:
3616 // - The requested stream (or a stream matching for volume control) is active on the output
3617 // - The device (or devices) selected by the engine for this stream includes
3618 // the requested device
3619 // - For non default requested device, currently selected device on the output is either the
3620 // requested device or one of the devices selected by the engine for this stream
3621 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3622 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003623 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003624 for (size_t i = 0; i < mOutputs.size(); i++) {
3625 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003626 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003627
jiabin9a3361e2019-10-01 09:38:30 -07003628 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3629 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003630 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003631
3632 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003633 continue;
3634 }
3635 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3636 curDevices.find(device) == curDevices.end()) {
3637 continue;
3638 }
3639 bool applyVolume = false;
3640 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3641 curSrcDevices.insert(device);
3642 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003643 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3644 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003645 } else {
3646 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3647 }
3648 if (!applyVolume) {
3649 continue; // next output
3650 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003651 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3652 // If a higher priority strategy is active, and the output is routed to a device with a
3653 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003654 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003655 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003656 // If the volume source is active with higher priority source, ensure at least Sw Muted
3657 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003658 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3659 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3660 false /*preferredDevice*/);
3661 if (activeClients.empty()) {
3662 continue;
3663 }
3664 bool isPreempted = false;
3665 bool isHigherPriority = productStrategy < strategy;
3666 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003667 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003668 ALOGV("%s: Strategy=%d (\nrequester:\n"
3669 " group %d, volumeGroup=%d attributes=%s)\n"
3670 " higher priority source active:\n"
3671 " volumeGroup=%d attributes=%s) \n"
3672 " on output %zu, bailing out", __func__, productStrategy,
3673 group, group, toString(attributes).c_str(),
3674 client->volumeSource(), toString(client->attributes()).c_str(), i);
3675 applyVolume = false;
3676 isPreempted = true;
3677 break;
3678 }
3679 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003680 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003681 applyVolume = true;
3682 }
3683 }
3684 if (isPreempted || applyVolume) {
3685 break;
3686 }
3687 }
3688 if (!applyVolume) {
3689 continue; // next output
3690 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003691 }
François Gaffieed91f582020-01-31 10:35:37 +01003692 //FIXME: workaround for truncated touch sounds
3693 // delayed volume change for system stream to be removed when the problem is
3694 // handled by system UI
3695 status_t volStatus = checkAndSetVolume(
3696 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003697 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003698 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3699 if (volStatus != NO_ERROR) {
3700 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003701 }
3702 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003703
3704 // update voice volume if the an active call route exists
3705 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3706 && (curSrcDevices.find(
3707 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3708 != curSrcDevices.end())) {
3709 bool isVoiceVolSrc;
3710 bool isBtScoVolSrc;
3711 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3712 isVoiceVolSrc, isBtScoVolSrc, __func__)
3713 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003714 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3715 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3716 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003717 }
3718 }
3719
François Gaffiecfe17322018-11-07 13:41:29 +01003720 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3721 return status;
3722}
3723
François Gaffieaaac0fd2018-11-22 17:56:39 +01003724status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003725 audio_devices_t device,
3726 IVolumeCurves &volumeCurves)
3727{
3728 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3729 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003730 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3731 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003732 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303733 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3734 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003735 return BAD_VALUE;
3736 }
3737 if (!audio_is_output_device(device)) {
3738 return BAD_VALUE;
3739 }
3740
3741 // Force max volume if stream cannot be muted
3742 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3743
François Gaffieaaac0fd2018-11-22 17:56:39 +01003744 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003745 volumeCurves.addCurrentVolumeIndex(device, index);
3746 return NO_ERROR;
3747}
3748
3749status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3750 int &index,
3751 audio_devices_t device)
3752{
3753 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3754 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003755 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003756 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003757 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003758 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003759 }
jiabin9a3361e2019-10-01 09:38:30 -07003760 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003761}
3762
3763status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3764 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003765 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003766{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003767 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003768 return BAD_VALUE;
3769 }
jiabin9a3361e2019-10-01 09:38:30 -07003770 index = curves.getVolumeIndex(deviceTypes);
3771 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003772 return NO_ERROR;
3773}
3774
3775status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3776 int &index)
3777{
3778 index = getVolumeCurves(attr).getVolumeIndexMin();
3779 return NO_ERROR;
3780}
3781
3782status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3783 int &index)
3784{
3785 index = getVolumeCurves(attr).getVolumeIndexMax();
3786 return NO_ERROR;
3787}
3788
Eric Laurent36829f92017-04-07 19:04:42 -07003789audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003790{
3791 // select one output among several suitable for global effects.
3792 // The priority is as follows:
3793 // 1: An offloaded output. If the effect ends up not being offloadable,
3794 // AudioFlinger will invalidate the track and the offloaded output
3795 // will be closed causing the effect to be moved to a PCM output.
3796 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003797 // 3: The primary output
3798 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003799
François Gaffiec005e562018-11-06 15:04:49 +01003800 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3801 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003802 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003803
Eric Laurent36829f92017-04-07 19:04:42 -07003804 if (outputs.size() == 0) {
3805 return AUDIO_IO_HANDLE_NONE;
3806 }
Eric Laurente552edb2014-03-10 17:42:56 -07003807
Eric Laurent36829f92017-04-07 19:04:42 -07003808 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3809 bool activeOnly = true;
3810
3811 while (output == AUDIO_IO_HANDLE_NONE) {
3812 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3813 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3814 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3815
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003816 for (audio_io_handle_t output : outputs) {
3817 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003818 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003819 continue;
3820 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003821 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3822 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003823 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003824 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003825 }
3826 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003827 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003828 }
3829 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003830 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003831 }
3832 }
3833 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3834 output = outputOffloaded;
3835 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3836 output = outputDeepBuffer;
3837 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3838 output = outputPrimary;
3839 } else {
3840 output = outputs[0];
3841 }
3842 activeOnly = false;
3843 }
3844
3845 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003846 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3847 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003848 mMusicEffectOutput = output;
3849 }
3850
3851 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003852 return output;
3853}
3854
Eric Laurent36829f92017-04-07 19:04:42 -07003855audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3856{
3857 return selectOutputForMusicEffects();
3858}
3859
Eric Laurente0720872014-03-11 09:30:41 -07003860status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003861 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003862 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003863 int session,
3864 int id)
3865{
Shunkai Yao29d10572024-03-19 04:31:47 +00003866 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003867 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003868 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003869 index = mInputs.indexOfKey(io);
3870 if (index < 0) {
3871 ALOGW("registerEffect() unknown io %d", io);
3872 return INVALID_OPERATION;
3873 }
Eric Laurente552edb2014-03-10 17:42:56 -07003874 }
3875 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003876 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3877 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3878 || strategy == PRODUCT_STRATEGY_NONE));
3879 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003880}
3881
Eric Laurentc241b0d2018-11-28 09:08:49 -08003882status_t AudioPolicyManager::unregisterEffect(int id)
3883{
3884 if (mEffects.getEffect(id) == nullptr) {
3885 return INVALID_OPERATION;
3886 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003887 if (mEffects.isEffectEnabled(id)) {
3888 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3889 setEffectEnabled(id, false);
3890 }
3891 return mEffects.unregisterEffect(id);
3892}
3893
3894status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3895{
3896 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3897 if (effect == nullptr) {
3898 return INVALID_OPERATION;
3899 }
3900
3901 status_t status = mEffects.setEffectEnabled(id, enabled);
3902 if (status == NO_ERROR) {
3903 mInputs.trackEffectEnabled(effect, enabled);
3904 }
3905 return status;
3906}
3907
Eric Laurent6c796322019-04-09 14:13:17 -07003908
3909status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3910{
3911 mEffects.moveEffects(ids, io);
3912 return NO_ERROR;
3913}
3914
Eric Laurentc75307b2015-03-17 15:29:32 -07003915bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3916{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003917 auto vs = toVolumeSource(stream, false);
3918 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003919}
3920
3921bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3922{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003923 auto vs = toVolumeSource(stream, false);
3924 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003925}
3926
Eric Laurente0720872014-03-11 09:30:41 -07003927bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003928{
3929 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003930 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003931 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003932 return true;
3933 }
3934 }
3935 return false;
3936}
3937
Eric Laurent275e8e92014-11-30 15:14:47 -08003938// Register a list of custom mixes with their attributes and format.
3939// When a mix is registered, corresponding input and output profiles are
3940// added to the remote submix hw module. The profile contains only the
3941// parameters (sampling rate, format...) specified by the mix.
3942// The corresponding input remote submix device is also connected.
3943//
3944// When a remote submix device is connected, the address is checked to select the
3945// appropriate profile and the corresponding input or output stream is opened.
3946//
3947// When capture starts, getInputForAttr() will:
3948// - 1 look for a mix matching the address passed in attribtutes tags if any
3949// - 2 if none found, getDeviceForInputSource() will:
3950// - 2.1 look for a mix matching the attributes source
3951// - 2.2 if none found, default to device selection by policy rules
3952// At this time, the corresponding output remote submix device is also connected
3953// and active playback use cases can be transferred to this mix if needed when reconnecting
3954// after AudioTracks are invalidated
3955//
3956// When playback starts, getOutputForAttr() will:
3957// - 1 look for a mix matching the address passed in attribtutes tags if any
3958// - 2 if none found, look for a mix matching the attributes usage
3959// - 3 if none found, default to device and output selection by policy rules.
3960
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003961status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003962{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003963 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3964 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003965 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003966 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003967 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003968 // examine each mix's route type
3969 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003970 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003971 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3972 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3973 ALOGE("Unsupported Policy Mix %zu of %zu: "
3974 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3975 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003976 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003977 break;
3978 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003979 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3980 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003981 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003982 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3983 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003984 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003985 rSubmixModule = mHwModules.getModuleFromName(
3986 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3987 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003988 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003989 i);
3990 res = INVALID_OPERATION;
3991 break;
3992 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003993 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003994
Eric Laurent97ac8712018-07-27 18:59:02 -07003995 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003996 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003997 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003998 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003999 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4000 } else {
4001 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4002 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004003 }
François Gaffie036e1e92015-03-19 10:16:24 +01004004
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004005 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004006 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004007 res = INVALID_OPERATION;
4008 break;
4009 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004010 audio_config_t outputConfig = mix.mFormat;
4011 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004012 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4013 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004014 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4015 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004016 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004017 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4018 audio_is_linear_pcm(outputConfig.format)
4019 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004020 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004021 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4022 audio_is_linear_pcm(inputConfig.format)
4023 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004024
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004025 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004026 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004027 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004028 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004029 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004030 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004031 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004032 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4033 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004034 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004035 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004036 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004037
4038 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4039 mix.mDeviceType, mix.mDeviceAddress,
4040 String8(), AUDIO_FORMAT_DEFAULT);
4041 if (device == nullptr) {
4042 res = INVALID_OPERATION;
4043 break;
4044 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004045
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004046 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004047 // First try to find an already opened output supporting the device
4048 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004049 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004050
Eric Laurentc529cf62020-04-17 18:19:10 -07004051 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004052 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004053 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004054 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004055 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004056 } else {
4057 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004058 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004059 }
4060 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004061 // If no output found, try to find a direct output profile supporting the device
4062 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4063 sp<HwModule> module = mHwModules[i];
4064 for (size_t j = 0;
4065 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4066 j++) {
4067 sp<IOProfile> profile = module->getOutputProfiles()[j];
4068 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4069 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4070 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004071 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004072 res = INVALID_OPERATION;
4073 } else {
4074 foundOutput = true;
4075 }
4076 }
4077 }
4078 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004079 if (res != NO_ERROR) {
4080 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004081 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004082 res = INVALID_OPERATION;
4083 break;
4084 } else if (!foundOutput) {
4085 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004086 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004087 res = INVALID_OPERATION;
4088 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004089 } else {
4090 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004091 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004092 }
Eric Laurentc722f302014-12-10 11:21:49 -08004093 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004094 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004095 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004096 if (audio_flags::audio_mix_ownership()) {
4097 // Only unregister mixes that were actually registered to not accidentally unregister
4098 // mixes that already existed previously.
4099 unregisterPolicyMixes(registeredMixes);
4100 registeredMixes.clear();
4101 } else {
4102 unregisterPolicyMixes(mixes);
4103 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004104 } else if (checkOutputs) {
4105 checkForDeviceAndOutputChanges();
4106 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004107 }
4108 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004109}
4110
4111status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4112{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004113 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004114 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004115 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004116 sp<HwModule> rSubmixModule;
4117 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004118 for (const auto& mix : mixes) {
4119 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004120
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004121 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004122 rSubmixModule = mHwModules.getModuleFromName(
4123 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4124 if (rSubmixModule == 0) {
4125 res = INVALID_OPERATION;
4126 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004127 }
4128 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004129
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004130 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004131
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004132 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004133 res = INVALID_OPERATION;
4134 continue;
4135 }
4136
Marvin Ramin0783e202024-03-05 12:45:50 +01004137 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004138 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004139 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4140 status_t currentRes =
4141 setDeviceConnectionStateInt(device,
4142 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4143 address.c_str(),
4144 "remote-submix",
4145 AUDIO_FORMAT_DEFAULT);
4146 if (!audio_flags::audio_mix_ownership()) {
4147 res = currentRes;
4148 }
4149 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004150 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004151 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004152 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004153 }
4154 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004155 }
jiabin5740f082019-08-19 15:08:30 -07004156 rSubmixModule->removeOutputProfile(address.c_str());
4157 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004158
Kevin Rocard153f92d2018-12-18 18:33:28 -08004159 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004160 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004161 res = INVALID_OPERATION;
4162 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004163 } else {
4164 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004165 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004166 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004167 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004168
4169 if (res == NO_ERROR && checkOutputs) {
4170 checkForDeviceAndOutputChanges();
4171 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004172 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004173 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004174}
4175
Marvin Raminbdefaf02023-11-01 09:10:32 +01004176status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4177 if (!audio_flags::audio_mix_test_api()) {
4178 return INVALID_OPERATION;
4179 }
4180
4181 _aidl_return.clear();
4182 _aidl_return.reserve(mPolicyMixes.size());
4183 for (const auto &policyMix: mPolicyMixes) {
4184 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4185 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4186 policyMix->mCbFlags);
4187 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004188 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004189 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004190 }
4191
Vlad Popaa5d73f32024-03-08 16:05:38 -08004192 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004193 return OK;
4194}
4195
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004196status_t AudioPolicyManager::updatePolicyMix(
4197 const AudioMix& mix,
4198 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4199 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4200 if (res == NO_ERROR) {
4201 checkForDeviceAndOutputChanges();
4202 updateCallAndOutputRouting();
4203 }
4204 return res;
4205}
4206
Mikhail Naganov100f0122018-11-29 11:22:16 -08004207void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4208{
4209 size_t i = 0;
4210 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4211 for (const auto& fmt : mManualSurroundFormats) {
4212 if (i++ != 0) dst->append(", ");
4213 std::string sfmt;
4214 FormatConverter::toString(fmt, sfmt);
4215 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4216 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4217 }
4218}
4219
Eric Laurentc529cf62020-04-17 18:19:10 -07004220// Returns true if all devices types match the predicate and are supported by one HW module
4221bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004222 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004223 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004224 const char *context,
4225 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004226 for (size_t i = 0; i < devices.size(); i++) {
4227 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004228 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004229 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004230 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004231 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004232 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004233 return false;
4234 }
4235 }
4236 return true;
4237}
4238
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004239void AudioPolicyManager::changeOutputDevicesMuteState(
4240 const AudioDeviceTypeAddrVector& devices) {
4241 ALOGVV("%s() num devices %zu", __func__, devices.size());
4242
4243 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4244 getSoftwareOutputsForDevices(devices);
4245
4246 for (size_t i = 0; i < outputs.size(); i++) {
4247 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4248 DeviceVector prevDevices = outputDesc->devices();
4249 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4250 }
4251}
4252
4253std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4254 const AudioDeviceTypeAddrVector& devices) const
4255{
4256 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4257 DeviceVector deviceDescriptors;
4258 for (size_t j = 0; j < devices.size(); j++) {
4259 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4260 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4261 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4262 ALOGE("%s: device type %#x address %s not supported or not an output device",
4263 __func__, devices[j].mType, devices[j].getAddress());
4264 continue;
4265 }
4266 deviceDescriptors.add(desc);
4267 }
4268 for (size_t i = 0; i < mOutputs.size(); i++) {
4269 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4270 continue;
4271 }
4272 outputs.push_back(mOutputs.valueAt(i));
4273 }
4274 return outputs;
4275}
4276
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004277status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004278 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004279 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004280 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4281 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004282 }
4283 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004284 if (res != NO_ERROR) {
4285 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4286 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004287 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004288
4289 checkForDeviceAndOutputChanges();
4290 updateCallAndOutputRouting();
4291
4292 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004293}
4294
4295status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4296 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004297 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4298 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004299 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004300 __FUNCTION__, uid);
4301 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004302 }
4303
Eric Laurentc529cf62020-04-17 18:19:10 -07004304 checkForDeviceAndOutputChanges();
4305 updateCallAndOutputRouting();
4306
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004307 return res;
4308}
4309
Eric Laurent2517af32020-11-25 15:31:27 +01004310
jiabin0a488932020-08-07 17:32:40 -07004311status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4312 device_role_t role,
4313 const AudioDeviceTypeAddrVector &devices) {
4314 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4315 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004316
Eric Laurentc529cf62020-04-17 18:19:10 -07004317 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004318 return BAD_VALUE;
4319 }
jiabin0a488932020-08-07 17:32:40 -07004320 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004321 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004322 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4323 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004324 return status;
4325 }
4326
4327 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004328
4329 bool forceVolumeReeval = false;
4330 // FIXME: workaround for truncated touch sounds
4331 // to be removed when the problem is handled by system UI
4332 uint32_t delayMs = 0;
4333 if (strategy == mCommunnicationStrategy) {
4334 forceVolumeReeval = true;
4335 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4336 updateInputRouting();
4337 }
4338 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004339
4340 return NO_ERROR;
4341}
4342
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004343void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4344 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004345{
4346 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004347 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004348 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004349 // Only apply special touch sound delay once
4350 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004351 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004352 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004353 for (size_t i = 0; i < mOutputs.size(); i++) {
4354 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4355 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004356 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4357 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004358 // As done in setDeviceConnectionState, we could also fix default device issue by
4359 // preventing the force re-routing in case of default dev that distinguishes on address.
4360 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004361 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004362 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004363 // If the device is using preferred mixer attributes, the output need to reopen
4364 // with default configuration when the new selected devices are different from
4365 // current routing devices.
4366 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4367 continue;
4368 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304369
4370 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4371 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004372 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004373 // Only apply special touch sound delay once
4374 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004375 }
4376 if (forceVolumeReeval && !newDevices.isEmpty()) {
4377 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4378 }
4379 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004380 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004381 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004382}
4383
Eric Laurent2517af32020-11-25 15:31:27 +01004384void AudioPolicyManager::updateInputRouting() {
4385 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304386 // Skip for hotword recording as the input device switch
4387 // is handled within sound trigger HAL
4388 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4389 continue;
4390 }
Eric Laurent2517af32020-11-25 15:31:27 +01004391 auto newDevice = getNewInputDevice(activeDesc);
4392 // Force new input selection if the new device can not be reached via current input
4393 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4394 setInputDevice(activeDesc->mIoHandle, newDevice);
4395 } else {
4396 closeInput(activeDesc->mIoHandle);
4397 }
4398 }
4399}
4400
Paul Wang5d7cdb52022-11-22 09:45:06 +00004401status_t
4402AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4403 device_role_t role,
4404 const AudioDeviceTypeAddrVector &devices) {
4405 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4406 dumpAudioDeviceTypeAddrVector(devices).c_str());
4407
Eric Laurent78fedbf2023-03-09 14:40:44 +01004408 if (!areAllDevicesSupported(
4409 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004410 return BAD_VALUE;
4411 }
4412 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4413 if (status != NO_ERROR) {
4414 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4415 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4416 return status;
4417 }
4418
4419 checkForDeviceAndOutputChanges();
4420
4421 bool forceVolumeReeval = false;
4422 // TODO(b/263479999): workaround for truncated touch sounds
4423 // to be removed when the problem is handled by system UI
4424 uint32_t delayMs = 0;
4425 if (strategy == mCommunnicationStrategy) {
4426 forceVolumeReeval = true;
4427 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4428 updateInputRouting();
4429 }
4430 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4431
4432 return NO_ERROR;
4433}
4434
4435status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4436 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004437{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004438 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004439
Paul Wang5d7cdb52022-11-22 09:45:06 +00004440 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004441 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004442 ALOGW_IF(status != NAME_NOT_FOUND,
4443 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004444 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004445 return status;
4446 }
4447
4448 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004449
4450 bool forceVolumeReeval = false;
4451 // FIXME: workaround for truncated touch sounds
4452 // to be removed when the problem is handled by system UI
4453 uint32_t delayMs = 0;
4454 if (strategy == mCommunnicationStrategy) {
4455 forceVolumeReeval = true;
4456 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4457 updateInputRouting();
4458 }
4459 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004460
4461 return NO_ERROR;
4462}
4463
jiabin0a488932020-08-07 17:32:40 -07004464status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4465 device_role_t role,
4466 AudioDeviceTypeAddrVector &devices) {
4467 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004468}
4469
Jiabin Huang3b98d322020-09-03 17:54:16 +00004470status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4471 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4472 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4473 dumpAudioDeviceTypeAddrVector(devices).c_str());
4474
Mikhail Naganov55773032020-10-01 15:08:13 -07004475 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004476 return BAD_VALUE;
4477 }
4478 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4479 ALOGW_IF(status != NO_ERROR,
4480 "Engine could not set preferred devices %s for audio source %d role %d",
4481 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4482
4483 return status;
4484}
4485
4486status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4487 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4488 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4489 dumpAudioDeviceTypeAddrVector(devices).c_str());
4490
Mikhail Naganov55773032020-10-01 15:08:13 -07004491 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004492 return BAD_VALUE;
4493 }
4494 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4495 ALOGW_IF(status != NO_ERROR,
4496 "Engine could not add preferred devices %s for audio source %d role %d",
4497 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4498
Eric Laurent2517af32020-11-25 15:31:27 +01004499 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004500 return status;
4501}
4502
4503status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4504 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4505{
4506 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4507 dumpAudioDeviceTypeAddrVector(devices).c_str());
4508
Eric Laurent78fedbf2023-03-09 14:40:44 +01004509 if (!areAllDevicesSupported(
4510 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004511 return BAD_VALUE;
4512 }
4513
4514 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4515 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004516 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004517 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004518 if (status == NO_ERROR) {
4519 updateInputRouting();
4520 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004521 return status;
4522}
4523
4524status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4525 device_role_t role) {
4526 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4527
4528 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004529 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004530 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004531 if (status == NO_ERROR) {
4532 updateInputRouting();
4533 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004534 return status;
4535}
4536
4537status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4538 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4539 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4540}
4541
Oscar Azucena90e77632019-11-27 17:12:28 -08004542status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004543 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004544 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004545 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4546 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004547 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004548 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4549 if (status != NO_ERROR) {
4550 ALOGE("%s() could not set device affinity for userId %d",
4551 __FUNCTION__, userId);
4552 return status;
4553 }
4554
4555 // reevaluate outputs for all devices
4556 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004557 changeOutputDevicesMuteState(devices);
4558 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4559 true /* skipDelays */);
4560 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004561
4562 return NO_ERROR;
4563}
4564
4565status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004566 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004567 AudioDeviceTypeAddrVector devices;
4568 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004569 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4570 if (status != NO_ERROR) {
4571 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4572 __FUNCTION__, userId);
4573 return status;
4574 }
4575
4576 // reevaluate outputs for all devices
4577 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004578 changeOutputDevicesMuteState(devices);
4579 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4580 true /* skipDelays */);
4581 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004582
4583 return NO_ERROR;
4584}
4585
Andy Hungc29d82b2018-10-05 12:23:17 -07004586void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004587{
Andy Hungc29d82b2018-10-05 12:23:17 -07004588 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004589 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004590 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004591 std::string stateLiteral;
4592 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004593 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004594 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4595 "communications", "media", "record", "dock", "system",
4596 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4597 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4598 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004599 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4600 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4601 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4602 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4603 dst->append(" (MANUAL: ");
4604 dumpManualSurroundFormats(dst);
4605 dst->append(")");
4606 }
4607 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004608 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004609 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4610 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004611 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004612 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004613
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004614 dst->append("\n");
4615 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4616 dst->append("\n");
4617 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004618 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004619 mOutputs.dump(dst);
4620 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004621 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004622 mAudioPatches.dump(dst);
4623 mPolicyMixes.dump(dst);
4624 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004625
Kevin Rocardb99cc752019-03-21 20:52:24 -07004626 dst->appendFormat(" AllowedCapturePolicies:\n");
4627 for (auto& policy : mAllowedCapturePolicies) {
4628 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4629 }
4630
jiabina84c3d32022-12-02 18:59:55 +00004631 dst->appendFormat(" Preferred mixer audio configuration:\n");
4632 for (const auto it : mPreferredMixerAttrInfos) {
4633 dst->appendFormat(" - device port id: %d\n", it.first);
4634 for (const auto preferredMixerInfoIt : it.second) {
4635 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4636 preferredMixerInfoIt.second->dump(dst);
4637 }
4638 }
4639
François Gaffiec005e562018-11-06 15:04:49 +01004640 dst->appendFormat("\nPolicy Engine dump:\n");
4641 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004642
4643 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4644 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4645 dst->appendFormat(" - device type: %s, driving stream %d\n",
4646 dumpDeviceTypes({it.first}).c_str(),
4647 mEngine->getVolumeGroupForAttributes(it.second));
4648 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004649}
4650
4651status_t AudioPolicyManager::dump(int fd)
4652{
4653 String8 result;
4654 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004655 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004656 return NO_ERROR;
4657}
4658
Kevin Rocardb99cc752019-03-21 20:52:24 -07004659status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4660{
4661 mAllowedCapturePolicies[uid] = capturePolicy;
4662 return NO_ERROR;
4663}
4664
Eric Laurente552edb2014-03-10 17:42:56 -07004665// This function checks for the parameters which can be offloaded.
4666// This can be enhanced depending on the capability of the DSP and policy
4667// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004668audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004669{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004670 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004671 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004672 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004673 offloadInfo.format,
4674 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4675 offloadInfo.has_video);
4676
jiabin2b9d5a12021-12-10 01:06:29 +00004677 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004678 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004679 }
4680
4681 // See if there is a profile to support this.
4682 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004683 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004684 offloadInfo.sample_rate,
4685 offloadInfo.format,
4686 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004687 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4688 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004689 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4690 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4691 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004692 if (profile == nullptr) {
4693 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4694 }
4695 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4696 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4697 }
4698 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004699}
4700
Michael Chana94fbb22018-04-24 14:31:19 +10004701bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4702 const audio_attributes_t& attributes) {
4703 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004704 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004705 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4706 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004707 config.sample_rate,
4708 config.format,
4709 config.channel_mask,
4710 output_flags,
4711 true /* directOnly */);
4712 ALOGV("%s() profile %sfound with name: %s, "
4713 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4714 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004715 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004716 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004717
4718 // also try the MSD module if compatible profile not found
4719 if (profile == nullptr) {
4720 profile = getMsdProfileForOutput(outputDevices,
4721 config.sample_rate,
4722 config.format,
4723 config.channel_mask,
4724 output_flags,
4725 true /* directOnly */);
4726 ALOGV("%s() MSD profile %sfound with name: %s, "
4727 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4728 __FUNCTION__, profile != 0 ? "" : "NOT ",
4729 (profile != 0 ? profile->getTagName().c_str() : "null"),
4730 config.sample_rate, config.format, config.channel_mask, output_flags);
4731 }
4732 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004733}
4734
jiabin2b9d5a12021-12-10 01:06:29 +00004735bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4736 bool durationIgnored) {
4737 if (mMasterMono) {
4738 return false; // no offloading if mono is set.
4739 }
4740
4741 // Check if offload has been disabled
4742 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4743 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4744 return false;
4745 }
4746
4747 // Check if stream type is music, then only allow offload as of now.
4748 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4749 {
4750 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4751 return false;
4752 }
4753
4754 //TODO: enable audio offloading with video when ready
4755 const bool allowOffloadWithVideo =
4756 property_get_bool("audio.offload.video", false /* default_value */);
4757 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4758 ALOGV("%s: has_video == true, returning false", __func__);
4759 return false;
4760 }
4761
4762 //If duration is less than minimum value defined in property, return false
4763 const int min_duration_secs = property_get_int32(
4764 "audio.offload.min.duration.secs", -1 /* default_value */);
4765 if (!durationIgnored) {
4766 if (min_duration_secs >= 0) {
4767 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4768 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4769 __func__, min_duration_secs);
4770 return false;
4771 }
4772 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4773 ALOGV("%s: Offload denied by duration < default min(=%u)",
4774 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4775 return false;
4776 }
4777 }
4778
4779 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4780 // creating an offloaded track and tearing it down immediately after start when audioflinger
4781 // detects there is an active non offloadable effect.
4782 // FIXME: We should check the audio session here but we do not have it in this context.
4783 // This may prevent offloading in rare situations where effects are left active by apps
4784 // in the background.
4785 if (mEffects.isNonOffloadableEffectEnabled()) {
4786 return false;
4787 }
4788
4789 return true;
4790}
4791
4792audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4793 const audio_config_t *config) {
4794 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4795 offloadInfo.format = config->format;
4796 offloadInfo.sample_rate = config->sample_rate;
4797 offloadInfo.channel_mask = config->channel_mask;
4798 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4799 offloadInfo.has_video = false;
4800 offloadInfo.is_streaming = false;
4801 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4802
4803 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4804 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4805 audio_flags_to_audio_output_flags(attr->flags, &flags);
4806 // only retain flags that will drive compressed offload or passthrough
4807 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4808 if (offloadPossible) {
4809 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4810 }
4811 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4812
Dorin Drimusfae3c642022-03-17 18:36:30 +01004813 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004814 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004815 DeviceVector outputDevices = engineOutputDevices;
4816 // the MSD module checks for different conditions and output devices
4817 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4818 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4819 continue;
4820 }
4821 outputDevices = getMsdAudioOutDevices();
4822 }
jiabin2b9d5a12021-12-10 01:06:29 +00004823 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004824 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004825 config->sample_rate, nullptr /*updatedSamplingRate*/,
4826 config->format, nullptr /*updatedFormat*/,
4827 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004828 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004829 continue;
4830 }
4831 // reject profiles not corresponding to a device currently available
4832 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4833 continue;
4834 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004835 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4836 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004837 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004838 != AUDIO_DIRECT_NOT_SUPPORTED) {
4839 // Already reports offload gapless supported. No need to report offload support.
4840 continue;
4841 }
4842 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4843 != AUDIO_OUTPUT_FLAG_NONE) {
4844 // If offload gapless is reported, no need to report offload support.
4845 directMode = (audio_direct_mode_t) ((directMode &
4846 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4847 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4848 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004849 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004850 }
4851 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004852 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004853 }
4854 }
4855 }
4856 return directMode;
4857}
4858
Dorin Drimusf2196d82022-01-03 12:11:18 +01004859status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4860 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004861 if (mEffects.isNonOffloadableEffectEnabled()) {
4862 return OK;
4863 }
jiabinf1c73972022-04-14 16:28:52 -07004864 DeviceVector devices;
4865 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004866 if (status != OK) {
4867 return status;
4868 }
4869 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4870 if (devices.empty()) {
4871 return OK; // no output devices for the attributes
4872 }
jiabinf1c73972022-04-14 16:28:52 -07004873 return getProfilesForDevices(devices, audioProfilesVector,
4874 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004875}
4876
jiabina84c3d32022-12-02 18:59:55 +00004877status_t AudioPolicyManager::getSupportedMixerAttributes(
4878 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4879 ALOGV("%s, portId=%d", __func__, portId);
4880 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4881 if (deviceDescriptor == nullptr) {
4882 ALOGE("%s the requested device is currently unavailable", __func__);
4883 return BAD_VALUE;
4884 }
jiabin96daffc2023-05-11 17:51:55 +00004885 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4886 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4887 deviceDescriptor->type());
4888 return BAD_VALUE;
4889 }
jiabina84c3d32022-12-02 18:59:55 +00004890 for (const auto& hwModule : mHwModules) {
4891 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4892 if (curProfile->supportsDevice(deviceDescriptor)) {
4893 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4894 }
4895 }
4896 }
4897 return NO_ERROR;
4898}
4899
4900status_t AudioPolicyManager::setPreferredMixerAttributes(
4901 const audio_attributes_t *attr,
4902 audio_port_handle_t portId,
4903 uid_t uid,
4904 const audio_mixer_attributes_t *mixerAttributes) {
4905 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4906 "mixerBehavior=%d}, uid=%d, portId=%u",
4907 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4908 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4909 mixerAttributes->mixer_behavior, uid, portId);
4910 if (attr->usage != AUDIO_USAGE_MEDIA) {
4911 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4912 return BAD_VALUE;
4913 }
4914 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4915 if (deviceDescriptor == nullptr) {
4916 ALOGE("%s the requested device is currently unavailable", __func__);
4917 return BAD_VALUE;
4918 }
4919 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4920 ALOGE("%s(%d), type=%d, is not a usb output device",
4921 __func__, portId, deviceDescriptor->type());
4922 return BAD_VALUE;
4923 }
4924
4925 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4926 audio_flags_to_audio_output_flags(attr->flags, &flags);
4927 flags = (audio_output_flags_t) (flags |
4928 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4929 sp<IOProfile> profile = nullptr;
4930 DeviceVector devices(deviceDescriptor);
4931 for (const auto& hwModule : mHwModules) {
4932 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4933 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004934 && curProfile->getCompatibilityScore(
4935 devices,
4936 mixerAttributes->config.sample_rate,
4937 nullptr /*updatedSamplingRate*/,
4938 mixerAttributes->config.format,
4939 nullptr /*updatedFormat*/,
4940 mixerAttributes->config.channel_mask,
4941 nullptr /*updatedChannelMask*/,
4942 flags,
4943 false /*exactMatchRequiredForInputFlags*/)
4944 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004945 profile = curProfile;
4946 break;
4947 }
4948 }
4949 }
4950 if (profile == nullptr) {
4951 ALOGE("%s, there is no compatible profile found", __func__);
4952 return BAD_VALUE;
4953 }
4954
4955 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4956 sp<PreferredMixerAttributesInfo>::make(
4957 uid, portId, profile, flags, *mixerAttributes);
4958 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4959 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4960
4961 // If 1) there is any client from the preferred mixer configuration owner that is currently
4962 // active and matches the strategy and 2) current output is on the preferred device and the
4963 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4964 // configuration.
4965 std::vector<audio_io_handle_t> outputsToReopen;
4966 for (size_t i = 0; i < mOutputs.size(); i++) {
4967 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004968 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4969 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004970 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004971 } else {
4972 for (const auto &client: output->getActiveClients()) {
4973 if (client->uid() == uid && client->strategy() == strategy) {
4974 client->setIsInvalid();
4975 outputsToReopen.push_back(output->mIoHandle);
4976 }
jiabina84c3d32022-12-02 18:59:55 +00004977 }
4978 }
4979 }
4980 }
4981 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4982 config.sample_rate = mixerAttributes->config.sample_rate;
4983 config.channel_mask = mixerAttributes->config.channel_mask;
4984 config.format = mixerAttributes->config.format;
4985 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004986 sp<SwAudioOutputDescriptor> desc =
4987 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4988 if (desc == nullptr) {
4989 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4990 continue;
4991 }
jiabin220eea12024-05-17 17:55:20 +00004992 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004993 }
4994
4995 return NO_ERROR;
4996}
4997
4998sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004999 audio_port_handle_t devicePortId,
5000 product_strategy_t strategy,
5001 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005002 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5003 if (it == mPreferredMixerAttrInfos.end()) {
5004 return nullptr;
5005 }
jiabind9a58d32023-06-01 17:57:30 +00005006 if (activeBitPerfectPreferred) {
5007 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005008 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005009 return info;
5010 }
5011 }
jiabina84c3d32022-12-02 18:59:55 +00005012 }
jiabind9a58d32023-06-01 17:57:30 +00005013 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5014 return strategyMatchedMixerAttrInfoIt == it->second.end()
5015 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005016}
5017
5018status_t AudioPolicyManager::getPreferredMixerAttributes(
5019 const audio_attributes_t *attr,
5020 audio_port_handle_t portId,
5021 audio_mixer_attributes_t* mixerAttributes) {
5022 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5023 portId, mEngine->getProductStrategyForAttributes(*attr));
5024 if (info == nullptr) {
5025 return NAME_NOT_FOUND;
5026 }
5027 *mixerAttributes = info->getMixerAttributes();
5028 return NO_ERROR;
5029}
5030
5031status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5032 audio_port_handle_t portId,
5033 uid_t uid) {
5034 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5035 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5036 if (preferredMixerAttrInfo == nullptr) {
5037 return NAME_NOT_FOUND;
5038 }
5039 if (preferredMixerAttrInfo->getUid() != uid) {
5040 ALOGE("%s, requested uid=%d, owned uid=%d",
5041 __func__, uid, preferredMixerAttrInfo->getUid());
5042 return PERMISSION_DENIED;
5043 }
5044 mPreferredMixerAttrInfos[portId].erase(strategy);
5045 if (mPreferredMixerAttrInfos[portId].empty()) {
5046 mPreferredMixerAttrInfos.erase(portId);
5047 }
5048
5049 // Reconfig existing output
5050 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5051 for (size_t i = 0; i < mOutputs.size(); i++) {
5052 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5053 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5054 }
5055 }
5056 for (const auto output : potentialOutputsToReopen) {
5057 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5058 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5059 preferredMixerAttrInfo->getFlags())) {
5060 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5061 }
5062 }
5063 return NO_ERROR;
5064}
5065
Eric Laurent6a94d692014-05-20 11:18:06 -07005066status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5067 audio_port_type_t type,
5068 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005069 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005070 unsigned int *generation)
5071{
jiabin19cdba52020-11-24 11:28:58 -08005072 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5073 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005074 return BAD_VALUE;
5075 }
5076 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005077 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005078 *num_ports = 0;
5079 }
5080
5081 size_t portsWritten = 0;
5082 size_t portsMax = *num_ports;
5083 *num_ports = 0;
5084 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005085 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5086 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005087 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005088 for (const auto& dev : mAvailableOutputDevices) {
5089 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005090 continue;
5091 }
5092 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005093 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005094 }
5095 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005096 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005097 }
5098 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005099 for (const auto& dev : mAvailableInputDevices) {
5100 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005101 continue;
5102 }
5103 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005104 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005105 }
5106 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005107 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005108 }
5109 }
5110 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5111 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5112 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5113 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5114 }
5115 *num_ports += mInputs.size();
5116 }
5117 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005118 size_t numOutputs = 0;
5119 for (size_t i = 0; i < mOutputs.size(); i++) {
5120 if (!mOutputs[i]->isDuplicated()) {
5121 numOutputs++;
5122 if (portsWritten < portsMax) {
5123 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5124 }
5125 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005126 }
Eric Laurent84c70242014-06-23 08:46:27 -07005127 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005128 }
5129 }
jiabina84c3d32022-12-02 18:59:55 +00005130
Eric Laurent6a94d692014-05-20 11:18:06 -07005131 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005132 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005133 return NO_ERROR;
5134}
5135
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005136status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5137 std::vector<media::AudioPortFw>* _aidl_return) {
5138 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5139 audio_port_v7 port;
5140 dev->toAudioPort(&port);
5141 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5142 _aidl_return->push_back(std::move(aidlPort));
5143 return OK;
5144 };
5145
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005146 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005147 for (const auto& dev : module->getDeclaredDevices()) {
5148 if (role == media::AudioPortRole::NONE ||
5149 ((role == media::AudioPortRole::SOURCE)
5150 == audio_is_input_device(dev->type()))) {
5151 RETURN_STATUS_IF_ERROR(pushPort(dev));
5152 }
5153 }
5154 }
5155 return OK;
5156}
5157
jiabin19cdba52020-11-24 11:28:58 -08005158status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005159{
Eric Laurent99fcae42018-05-17 16:59:18 -07005160 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5161 return BAD_VALUE;
5162 }
5163 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5164 if (dev != 0) {
5165 dev->toAudioPort(port);
5166 return NO_ERROR;
5167 }
5168 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5169 if (dev != 0) {
5170 dev->toAudioPort(port);
5171 return NO_ERROR;
5172 }
5173 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5174 if (out != 0) {
5175 out->toAudioPort(port);
5176 return NO_ERROR;
5177 }
5178 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5179 if (in != 0) {
5180 in->toAudioPort(port);
5181 return NO_ERROR;
5182 }
5183 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005184}
5185
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005186status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5187 audio_patch_handle_t *handle,
5188 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005189{
François Gaffieafd4cea2019-11-18 15:50:22 +01005190 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005191 if (handle == NULL || patch == NULL) {
5192 return BAD_VALUE;
5193 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005194 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005195 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005196 return BAD_VALUE;
5197 }
5198 // only one source per audio patch supported for now
5199 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005200 return INVALID_OPERATION;
5201 }
Eric Laurent874c42872014-08-08 15:13:39 -07005202 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005203 return INVALID_OPERATION;
5204 }
Eric Laurent874c42872014-08-08 15:13:39 -07005205 for (size_t i = 0; i < patch->num_sinks; i++) {
5206 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5207 return INVALID_OPERATION;
5208 }
5209 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005210
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005211 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5212 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5213 if (srcDevice == nullptr || sinkDevice == nullptr) {
5214 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5215 return BAD_VALUE;
5216 }
5217 ALOGV("%s between source %s and sink %s", __func__,
5218 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5219 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5220 // Default attributes, default volume priority, not to infer with non raw audio patches.
5221 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5222 const struct audio_port_config *source = &patch->sources[0];
5223 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005224 new SourceClientDescriptor(
5225 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5226 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005227 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005228 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005229
5230 status_t status =
5231 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5232
5233 if (status != NO_ERROR) {
5234 return INVALID_OPERATION;
5235 }
5236 mAudioSources.add(portId, sourceDesc);
5237 return NO_ERROR;
5238}
5239
5240status_t AudioPolicyManager::connectAudioSourceToSink(
5241 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5242 const struct audio_patch *patch,
5243 audio_patch_handle_t &handle,
5244 uid_t uid, uint32_t delayMs)
5245{
5246 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5247 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5248 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5249 return INVALID_OPERATION;
5250 }
5251 sourceDesc->connect(handle, sinkDevice);
5252 if (isMsdPatch(handle)) {
5253 return NO_ERROR;
5254 }
5255 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5256 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5257 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5258 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5259 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5260 goto FailurePatchAdded;
5261 }
5262 status = swOutput->start();
5263 if (status != NO_ERROR) {
5264 goto FailureSourceAdded;
5265 }
5266 swOutput->addClient(sourceDesc);
5267 status = startSource(swOutput, sourceDesc, &delayMs);
5268 if (status != NO_ERROR) {
5269 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5270 goto FailureSourceActive;
5271 }
5272 if (delayMs != 0) {
5273 usleep(delayMs * 1000);
5274 }
5275 return NO_ERROR;
5276
5277FailureSourceActive:
5278 swOutput->stop();
5279 releaseOutput(sourceDesc->portId());
5280FailureSourceAdded:
5281 sourceDesc->setSwOutput(nullptr);
5282FailurePatchAdded:
5283 releaseAudioPatchInternal(handle);
5284 return INVALID_OPERATION;
5285}
5286
5287status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5288 audio_patch_handle_t *handle,
5289 uid_t uid, uint32_t delayMs,
5290 const sp<SourceClientDescriptor>& sourceDesc)
5291{
5292 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005293 sp<AudioPatch> patchDesc;
5294 ssize_t index = mAudioPatches.indexOfKey(*handle);
5295
François Gaffieafd4cea2019-11-18 15:50:22 +01005296 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5297 patch->sources[0].role,
5298 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005299#if LOG_NDEBUG == 0
5300 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005301 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5302 patch->sinks[i].role,
5303 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005304 }
5305#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005306
5307 if (index >= 0) {
5308 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005309 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5310 __func__, mUidCached, patchDesc->getUid(), uid);
5311 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005312 return INVALID_OPERATION;
5313 }
5314 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005315 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005316 }
5317
5318 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005319 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005320 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005321 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005322 return BAD_VALUE;
5323 }
Eric Laurent84c70242014-06-23 08:46:27 -07005324 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5325 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005326 if (patchDesc != 0) {
5327 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005328 ALOGV("%s source id differs for patch current id %d new id %d",
5329 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005330 return BAD_VALUE;
5331 }
5332 }
Eric Laurent874c42872014-08-08 15:13:39 -07005333 DeviceVector devices;
5334 for (size_t i = 0; i < patch->num_sinks; i++) {
5335 // Only support mix to devices connection
5336 // TODO add support for mix to mix connection
5337 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005338 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005339 return INVALID_OPERATION;
5340 }
5341 sp<DeviceDescriptor> devDesc =
5342 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5343 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005344 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005345 return BAD_VALUE;
5346 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005347
jiabin66acc432024-02-06 00:57:36 +00005348 if (outputDesc->mProfile->getCompatibilityScore(
5349 DeviceVector(devDesc),
5350 patch->sources[0].sample_rate,
5351 nullptr, // updatedSamplingRate
5352 patch->sources[0].format,
5353 nullptr, // updatedFormat
5354 patch->sources[0].channel_mask,
5355 nullptr, // updatedChannelMask
5356 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005357 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005358 return INVALID_OPERATION;
5359 }
5360 devices.add(devDesc);
5361 }
5362 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005363 return INVALID_OPERATION;
5364 }
Eric Laurent874c42872014-08-08 15:13:39 -07005365
Eric Laurent6a94d692014-05-20 11:18:06 -07005366 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005367 ALOGV("%s setting device %s on output %d",
5368 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305369 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005370 index = mAudioPatches.indexOfKey(*handle);
5371 if (index >= 0) {
5372 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005373 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005374 }
5375 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005376 patchDesc->setUid(uid);
5377 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005378 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005379 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005380 return INVALID_OPERATION;
5381 }
5382 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5383 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5384 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005385 // only one sink supported when connecting an input device to a mix
5386 if (patch->num_sinks > 1) {
5387 return INVALID_OPERATION;
5388 }
François Gaffie53615e22015-03-19 09:24:12 +01005389 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005390 if (inputDesc == NULL) {
5391 return BAD_VALUE;
5392 }
5393 if (patchDesc != 0) {
5394 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5395 return BAD_VALUE;
5396 }
5397 }
François Gaffie11d30102018-11-02 16:09:09 +01005398 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005399 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005400 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005401 return BAD_VALUE;
5402 }
5403
jiabin66acc432024-02-06 00:57:36 +00005404 if (inputDesc->mProfile->getCompatibilityScore(
5405 DeviceVector(device),
5406 patch->sinks[0].sample_rate,
5407 nullptr, /*updatedSampleRate*/
5408 patch->sinks[0].format,
5409 nullptr, /*updatedFormat*/
5410 patch->sinks[0].channel_mask,
5411 nullptr, /*updatedChannelMask*/
5412 // FIXME for the parameter type,
5413 // and the NONE
5414 (audio_output_flags_t)
5415 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005416 return INVALID_OPERATION;
5417 }
5418 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005419 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005420 device->toString().c_str(), inputDesc->mIoHandle);
5421 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005422 index = mAudioPatches.indexOfKey(*handle);
5423 if (index >= 0) {
5424 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005425 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005426 }
5427 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005428 patchDesc->setUid(uid);
5429 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005430 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005431 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005432 return INVALID_OPERATION;
5433 }
5434 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5435 // device to device connection
5436 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005437 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005438 return BAD_VALUE;
5439 }
5440 }
François Gaffie11d30102018-11-02 16:09:09 +01005441 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005442 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005443 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005444 return BAD_VALUE;
5445 }
Eric Laurent874c42872014-08-08 15:13:39 -07005446
Eric Laurent6a94d692014-05-20 11:18:06 -07005447 //update source and sink with our own data as the data passed in the patch may
5448 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005449 PatchBuilder patchBuilder;
5450 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005451
5452 // if first sink is to MSD, establish single MSD patch
5453 if (getMsdAudioOutDevices().contains(
5454 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5455 ALOGV("%s patching to MSD", __FUNCTION__);
5456 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5457 goto installPatch;
5458 }
5459
François Gaffieafd4cea2019-11-18 15:50:22 +01005460 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5461 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005462
Eric Laurent874c42872014-08-08 15:13:39 -07005463 for (size_t i = 0; i < patch->num_sinks; i++) {
5464 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005465 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005466 return INVALID_OPERATION;
5467 }
François Gaffie11d30102018-11-02 16:09:09 +01005468 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005469 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005470 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005471 return BAD_VALUE;
5472 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005473 audio_port_config sinkPortConfig = {};
5474 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5475 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005476
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005477 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5478 // volume management purpose (tracking activity)
5479 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5480 // in config XML to reach the sink so that is can be declared as available.
5481 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005482 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005483 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005484 // take care of dynamic routing for SwOutput selection,
5485 audio_attributes_t attributes = sourceDesc->attributes();
5486 audio_stream_type_t stream = sourceDesc->stream();
5487 audio_attributes_t resultAttr;
5488 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5489 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005490 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5491 config.channel_mask =
5492 (audio_channel_mask_get_representation(sourceMask)
5493 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5494 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005495 config.format = sourceDesc->config().format;
5496 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5497 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5498 bool isRequestedDeviceForExclusiveUse = false;
5499 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005500 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005501 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005502 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5503 &stream, sourceDesc->uid(), &config, &flags,
5504 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005505 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005506 if (output == AUDIO_IO_HANDLE_NONE) {
5507 ALOGV("%s no output for device %s",
5508 __FUNCTION__, sinkDevice->toString().c_str());
5509 return INVALID_OPERATION;
5510 }
5511 outputDesc = mOutputs.valueFor(output);
5512 if (outputDesc->isDuplicated()) {
5513 ALOGE("%s output is duplicated", __func__);
5514 return INVALID_OPERATION;
5515 }
François Gaffie7e39df22022-04-26 12:48:49 +02005516 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5517 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005518 } else {
5519 // Same for "raw patches" aka created from createAudioPatch API
5520 SortedVector<audio_io_handle_t> outputs =
5521 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5522 // if the sink device is reachable via an opened output stream, request to
5523 // go via this output stream by adding a second source to the patch
5524 // description
5525 output = selectOutput(outputs);
5526 if (output == AUDIO_IO_HANDLE_NONE) {
5527 ALOGE("%s no output available for internal patch sink", __func__);
5528 return INVALID_OPERATION;
5529 }
5530 outputDesc = mOutputs.valueFor(output);
5531 if (outputDesc->isDuplicated()) {
5532 ALOGV("%s output for device %s is duplicated",
5533 __func__, sinkDevice->toString().c_str());
5534 return INVALID_OPERATION;
5535 }
François Gaffie7e39df22022-04-26 12:48:49 +02005536 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005537 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005538 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005539 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005540 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005541 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005542 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5543 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005544 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5545 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005546 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005547 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005548 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005549 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005550 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005551 return INVALID_OPERATION;
5552 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005553 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005554 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005555 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005556 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005557 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005558 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005559 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005560 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5561 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005562 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005563 }
Eric Laurent83b88082014-06-20 18:31:16 -07005564 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005565 }
5566 // TODO: check from routing capabilities in config file and other conflicting patches
5567
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005568installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005569 status_t status = installPatch(
5570 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005571 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005572 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005573 return INVALID_OPERATION;
5574 }
5575 } else {
5576 return BAD_VALUE;
5577 }
5578 } else {
5579 return BAD_VALUE;
5580 }
5581 return NO_ERROR;
5582}
5583
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005584status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005585{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005586 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005587 ssize_t index = mAudioPatches.indexOfKey(handle);
5588
5589 if (index < 0) {
5590 return BAD_VALUE;
5591 }
5592 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005593 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5594 __func__, mUidCached, patchDesc->getUid(), uid);
5595 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005596 return INVALID_OPERATION;
5597 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005598 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5599 for (size_t i = 0; i < mAudioSources.size(); i++) {
5600 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5601 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5602 portId = sourceDesc->portId();
5603 break;
5604 }
5605 }
5606 return portId != AUDIO_PORT_HANDLE_NONE ?
5607 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005608}
Eric Laurent6a94d692014-05-20 11:18:06 -07005609
François Gaffieafd4cea2019-11-18 15:50:22 +01005610status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005611 uint32_t delayMs,
5612 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005613{
5614 ALOGV("%s patch %d", __func__, handle);
5615 if (mAudioPatches.indexOfKey(handle) < 0) {
5616 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5617 return BAD_VALUE;
5618 }
5619 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005620 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005621 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005622 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005623 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005624 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005625 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005626 return BAD_VALUE;
5627 }
5628
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305629 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005630 getNewOutputDevices(outputDesc, true /*fromCache*/),
5631 true,
5632 0,
5633 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005634 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5635 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005636 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005637 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005638 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005639 return BAD_VALUE;
5640 }
5641 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005642 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005643 true,
5644 NULL);
5645 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005646 status_t status =
5647 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5648 ALOGV("%s patch panel returned %d patchHandle %d",
5649 __func__, status, patchDesc->getAfHandle());
5650 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005651 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005652 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005653 // SW or HW Bridge
5654 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5655 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005656 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005657 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5658 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5659 outputDesc = sourceDesc->swOutput().promote();
5660 }
5661 if (outputDesc == nullptr) {
5662 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5663 // releaseOutput has already called closeOutput in case of direct output
5664 return NO_ERROR;
5665 }
François Gaffie7e39df22022-04-26 12:48:49 +02005666 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005667 // While using a HwBridge, force reconsidering device only if not reusing an existing
5668 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005669 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005670 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5671 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5672 // Reconsider device only for cases:
5673 // 1 / Active Output
5674 // 2 / Inactive Output previously hosting HwBridge
5675 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5676 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5677 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305678 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005679 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5680 outputDesc->devices(),
5681 force,
5682 0,
5683 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005684 } else {
5685 return BAD_VALUE;
5686 }
5687 } else {
5688 return BAD_VALUE;
5689 }
5690 return NO_ERROR;
5691}
5692
5693status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5694 struct audio_patch *patches,
5695 unsigned int *generation)
5696{
François Gaffie53615e22015-03-19 09:24:12 +01005697 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005698 return BAD_VALUE;
5699 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005700 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005701 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005702}
5703
Eric Laurente1715a42014-05-20 11:30:42 -07005704status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005705{
Eric Laurente1715a42014-05-20 11:30:42 -07005706 ALOGV("setAudioPortConfig()");
5707
5708 if (config == NULL) {
5709 return BAD_VALUE;
5710 }
5711 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5712 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005713 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5714 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005715 }
5716
Eric Laurenta121f902014-06-03 13:32:54 -07005717 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005718 if (config->type == AUDIO_PORT_TYPE_MIX) {
5719 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005720 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005721 if (outputDesc == NULL) {
5722 return BAD_VALUE;
5723 }
Eric Laurent84c70242014-06-23 08:46:27 -07005724 ALOG_ASSERT(!outputDesc->isDuplicated(),
5725 "setAudioPortConfig() called on duplicated output %d",
5726 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005727 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005728 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005729 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005730 if (inputDesc == NULL) {
5731 return BAD_VALUE;
5732 }
Eric Laurenta121f902014-06-03 13:32:54 -07005733 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005734 } else {
5735 return BAD_VALUE;
5736 }
5737 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5738 sp<DeviceDescriptor> deviceDesc;
5739 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5740 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5741 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5742 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5743 } else {
5744 return BAD_VALUE;
5745 }
5746 if (deviceDesc == NULL) {
5747 return BAD_VALUE;
5748 }
Eric Laurenta121f902014-06-03 13:32:54 -07005749 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005750 } else {
5751 return BAD_VALUE;
5752 }
5753
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005754 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005755 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5756 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005757 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005758 audioPortConfig->toAudioPortConfig(&newConfig, config);
5759 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005760 }
Eric Laurenta121f902014-06-03 13:32:54 -07005761 if (status != NO_ERROR) {
5762 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005763 }
Eric Laurente1715a42014-05-20 11:30:42 -07005764
5765 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005766}
5767
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005768void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5769{
Eric Laurentd60560a2015-04-10 11:31:20 -07005770 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005771 clearAudioPatches(uid);
5772 clearSessionRoutes(uid);
5773}
5774
Eric Laurent6a94d692014-05-20 11:18:06 -07005775void AudioPolicyManager::clearAudioPatches(uid_t uid)
5776{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005777 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005778 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005779 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005780 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005781 }
5782 }
5783}
5784
François Gaffiec005e562018-11-06 15:04:49 +01005785void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005786{
François Gaffiec005e562018-11-06 15:04:49 +01005787 // Take the first attributes following the product strategy as it is used to retrieve the routed
5788 // device. All attributes wihin a strategy follows the same "routing strategy"
5789 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5790 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005791 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005792 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005793 for (size_t j = 0; j < mOutputs.size(); j++) {
5794 if (mOutputs.keyAt(j) == ouptutToSkip) {
5795 continue;
5796 }
5797 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005798 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005799 continue;
5800 }
5801 // If the default device for this strategy is on another output mix,
5802 // invalidate all tracks in this strategy to force re connection.
5803 // Otherwise select new device on the output mix.
5804 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005805 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005806 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005807 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005808 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005809 // If the device is using preferred mixer attributes, the output need to reopen
5810 // with default configuration when the new selected devices are different from
5811 // current routing devices.
5812 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5813 continue;
5814 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305815 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005816 }
5817 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005818 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005819}
5820
5821void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5822{
5823 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005824 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005825 for (size_t i = 0; i < mOutputs.size(); i++) {
5826 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005827 for (const auto& client : outputDesc->getClientIterable()) {
5828 if (client->hasPreferredDevice() && client->uid() == uid) {
5829 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005830 auto clientStrategy = client->strategy();
5831 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5832 end(affectedStrategies)) {
5833 continue;
5834 }
5835 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005836 }
5837 }
5838 }
5839 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005840 for (const auto& strategy : affectedStrategies) {
5841 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005842 }
5843
5844 // remove input routes associated with this uid
5845 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005846 for (size_t i = 0; i < mInputs.size(); i++) {
5847 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005848 for (const auto& client : inputDesc->getClientIterable()) {
5849 if (client->hasPreferredDevice() && client->uid() == uid) {
5850 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5851 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005852 }
5853 }
5854 }
5855 // reroute inputs if necessary
5856 SortedVector<audio_io_handle_t> inputsToClose;
5857 for (size_t i = 0; i < mInputs.size(); i++) {
5858 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005859 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005860 inputsToClose.add(inputDesc->mIoHandle);
5861 }
5862 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005863 for (const auto& input : inputsToClose) {
5864 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005865 }
5866}
5867
Eric Laurentd60560a2015-04-10 11:31:20 -07005868void AudioPolicyManager::clearAudioSources(uid_t uid)
5869{
5870 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005871 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5872 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005873 stopAudioSource(mAudioSources.keyAt(i));
5874 }
5875 }
5876}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005877
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005878status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5879 audio_io_handle_t *ioHandle,
5880 audio_devices_t *device)
5881{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005882 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5883 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005884 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005885 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5886 if (deviceDesc == nullptr) {
5887 return INVALID_OPERATION;
5888 }
5889 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005890
François Gaffiedf372692015-03-19 10:43:27 +01005891 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005892}
5893
Eric Laurentd60560a2015-04-10 11:31:20 -07005894status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005895 const audio_attributes_t *attributes,
5896 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005897 uid_t uid) {
5898 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00005899 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00005900}
5901
5902status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5903 const audio_attributes_t *attributes,
5904 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00005905 uid_t uid, bool internal, bool isCallRx,
5906 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005907{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005908 ALOGV("%s", __FUNCTION__);
5909 *portId = AUDIO_PORT_HANDLE_NONE;
5910
5911 if (source == NULL || attributes == NULL || portId == NULL) {
5912 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5913 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005914 return BAD_VALUE;
5915 }
5916
Eric Laurentd60560a2015-04-10 11:31:20 -07005917 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5918 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005919 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5920 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005921 return INVALID_OPERATION;
5922 }
5923
François Gaffie11d30102018-11-02 16:09:09 +01005924 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005925 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005926 String8(source->ext.device.address),
5927 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005928 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005929 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005930 return BAD_VALUE;
5931 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005932
jiabin4ef93452019-09-10 14:29:54 -07005933 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005934
François Gaffieaaac0fd2018-11-22 17:56:39 +01005935 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005936 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005937 mEngine->getStreamTypeForAttributes(*attributes),
5938 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005939 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005940
David Lif85c5e32024-07-01 13:14:10 +00005941 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005942 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005943 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005944 }
5945 return status;
5946}
5947
David Lif85c5e32024-07-01 13:14:10 +00005948status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5949 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005950{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005951 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005952
5953 // make sure we only have one patch per source.
5954 disconnectAudioSource(sourceDesc);
5955
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005956 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005957 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5958 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5959 sourceDesc->srcDevice()->type(),
5960 String8(sourceDesc->srcDevice()->address().c_str()),
5961 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005962 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005963 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005964 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005965 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005966 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5967 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5968 return INVALID_OPERATION;
5969 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005970 PatchBuilder patchBuilder;
5971 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5972 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005973
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005974 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00005975 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005976}
5977
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005978status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005979{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005980 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5981 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005982 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005983 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005984 return BAD_VALUE;
5985 }
5986 status_t status = disconnectAudioSource(sourceDesc);
5987
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005988 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005989 return status;
5990}
5991
Andy Hung2ddee192015-12-18 17:34:44 -08005992status_t AudioPolicyManager::setMasterMono(bool mono)
5993{
5994 if (mMasterMono == mono) {
5995 return NO_ERROR;
5996 }
5997 mMasterMono = mono;
5998 // if enabling mono we close all offloaded devices, which will invalidate the
5999 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6000 // for recreating the new AudioTrack as non-offloaded PCM.
6001 //
6002 // If disabling mono, we leave all tracks as is: we don't know which clients
6003 // and tracks are able to be recreated as offloaded. The next "song" should
6004 // play back offloaded.
6005 if (mMasterMono) {
6006 Vector<audio_io_handle_t> offloaded;
6007 for (size_t i = 0; i < mOutputs.size(); ++i) {
6008 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6009 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6010 offloaded.push(desc->mIoHandle);
6011 }
6012 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006013 for (const auto& handle : offloaded) {
6014 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006015 }
6016 }
6017 // update master mono for all remaining outputs
6018 for (size_t i = 0; i < mOutputs.size(); ++i) {
6019 updateMono(mOutputs.keyAt(i));
6020 }
6021 return NO_ERROR;
6022}
6023
6024status_t AudioPolicyManager::getMasterMono(bool *mono)
6025{
6026 *mono = mMasterMono;
6027 return NO_ERROR;
6028}
6029
Eric Laurentac9cef52017-06-09 15:46:26 -07006030float AudioPolicyManager::getStreamVolumeDB(
6031 audio_stream_type_t stream, int index, audio_devices_t device)
6032{
Vlad Popa9d482762024-06-21 16:40:23 -07006033 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6034 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006035}
6036
jiabin81772902018-04-02 17:52:27 -07006037status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6038 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006039 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006040{
Kriti Dang6537def2021-03-02 13:46:59 +01006041 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6042 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006043 return BAD_VALUE;
6044 }
Kriti Dang6537def2021-03-02 13:46:59 +01006045 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6046 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006047
6048 size_t formatsWritten = 0;
6049 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006050
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006051 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006052 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6053 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006054 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006055 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006056 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006057 bool formatEnabled = true;
6058 switch (forceUse) {
6059 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006060 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006061 break;
6062 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6063 formatEnabled = false;
6064 break;
6065 default: // AUTO or ALWAYS => true
6066 break;
jiabin81772902018-04-02 17:52:27 -07006067 }
6068 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6069 }
jiabin81772902018-04-02 17:52:27 -07006070 }
6071 return NO_ERROR;
6072}
6073
Kriti Dang6537def2021-03-02 13:46:59 +01006074status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6075 audio_format_t *surroundFormats) {
6076 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6077 return BAD_VALUE;
6078 }
6079 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6080 __func__, *numSurroundFormats, surroundFormats);
6081
6082 size_t formatsWritten = 0;
6083 size_t formatsMax = *numSurroundFormats;
6084 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6085
6086 // Return formats from all device profiles that have already been resolved by
6087 // checkOutputsForDevice().
6088 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6089 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6090 audio_devices_t deviceType = device->type();
6091 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6092 // returns formats reported by HDMI devices.
6093 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
6094 continue;
6095 }
6096 // Formats reported by sink devices
6097 std::unordered_set<audio_format_t> formatset;
6098 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6099 formatset.insert(it->second.begin(), it->second.end());
6100 }
6101
6102 // Formats hard-coded in the in policy configuration file (if any).
6103 FormatVector encodedFormats = device->encodedFormats();
6104 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6105 // Filter the formats which are supported by the vendor hardware.
6106 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006107 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006108 formats.insert(*it);
6109 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006110 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006111 if (pair.second.count(*it) != 0) {
6112 formats.insert(pair.first);
6113 break;
6114 }
6115 }
6116 }
6117 }
6118 }
6119 *numSurroundFormats = formats.size();
6120 for (const auto& format: formats) {
6121 if (formatsWritten < formatsMax) {
6122 surroundFormats[formatsWritten++] = format;
6123 }
6124 }
6125 return NO_ERROR;
6126}
6127
jiabin81772902018-04-02 17:52:27 -07006128status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6129{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006130 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006131 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6132 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006133 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006134 return BAD_VALUE;
6135 }
6136
Mikhail Naganov100f0122018-11-29 11:22:16 -08006137 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6138 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006139 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006140 return INVALID_OPERATION;
6141 }
6142
Mikhail Naganov100f0122018-11-29 11:22:16 -08006143 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006144 return NO_ERROR;
6145 }
6146
Mikhail Naganov100f0122018-11-29 11:22:16 -08006147 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006148 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006149 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006150 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006151 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006152 }
6153 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006154 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006155 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006156 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006157 }
6158 }
6159
6160 sp<SwAudioOutputDescriptor> outputDesc;
6161 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006162 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6163 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006164 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6165 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006166 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006167 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006168 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6169 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6170 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006171 name.c_str(),
6172 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006173 if (status != NO_ERROR) {
6174 continue;
6175 }
6176 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6177 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6178 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006179 name.c_str(),
6180 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006181 profileUpdated |= (status == NO_ERROR);
6182 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006183 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006184 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006185 AUDIO_DEVICE_IN_HDMI);
6186 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6187 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006188 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006189 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006190 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6191 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6192 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006193 name.c_str(),
6194 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006195 if (status != NO_ERROR) {
6196 continue;
6197 }
6198 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6199 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6200 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006201 name.c_str(),
6202 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006203 profileUpdated |= (status == NO_ERROR);
6204 }
6205
jiabin81772902018-04-02 17:52:27 -07006206 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006207 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006208 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006209 }
6210
6211 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6212}
6213
Eric Laurent5ada82e2019-08-29 17:53:54 -07006214void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006215{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006216 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006217 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006218 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006219 }
6220}
6221
jiabin6012f912018-11-02 17:06:30 -07006222bool AudioPolicyManager::isHapticPlaybackSupported()
6223{
6224 for (const auto& hwModule : mHwModules) {
6225 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6226 for (const auto &outProfile : outputProfiles) {
6227 struct audio_port audioPort;
6228 outProfile->toAudioPort(&audioPort);
6229 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6230 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6231 return true;
6232 }
6233 }
6234 }
6235 }
6236 return false;
6237}
6238
Carter Hsu325a8eb2022-01-19 19:56:51 +08006239bool AudioPolicyManager::isUltrasoundSupported()
6240{
6241 bool hasUltrasoundOutput = false;
6242 bool hasUltrasoundInput = false;
6243 for (const auto& hwModule : mHwModules) {
6244 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6245 if (!hasUltrasoundOutput) {
6246 for (const auto &outProfile : outputProfiles) {
6247 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6248 hasUltrasoundOutput = true;
6249 break;
6250 }
6251 }
6252 }
6253
6254 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6255 if (!hasUltrasoundInput) {
6256 for (const auto &inputProfile : inputProfiles) {
6257 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6258 hasUltrasoundInput = true;
6259 break;
6260 }
6261 }
6262 }
6263
6264 if (hasUltrasoundOutput && hasUltrasoundInput)
6265 return true;
6266 }
6267 return false;
6268}
6269
Atneya Nair698f5ef2022-12-15 16:15:09 -08006270bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6271{
6272 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6273 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6274 for (const auto& hwModule : mHwModules) {
6275 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6276 for (const auto &inputProfile : inputProfiles) {
6277 if ((inputProfile->getFlags() & mask) == mask) {
6278 return true;
6279 }
6280 }
6281 }
6282 return false;
6283}
6284
Eric Laurent8340e672019-11-06 11:01:08 -08006285bool AudioPolicyManager::isCallScreenModeSupported()
6286{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006287 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006288}
6289
6290
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006291status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006292{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006293 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006294 if (!sourceDesc->isConnected()) {
6295 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6296 return NO_ERROR;
6297 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006298 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6299 if (swOutput != 0) {
6300 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006301 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006302 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006303 }
jiabinbce0c1d2020-10-05 11:20:18 -07006304 if (releaseOutput(sourceDesc->portId())) {
6305 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6306 // no need to release audio patch here but just return NO_ERROR.
6307 return NO_ERROR;
6308 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006309 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006310 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006311 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006312 // close Hwoutput and remove from mHwOutputs
6313 } else {
6314 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6315 }
6316 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006317 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006318 sourceDesc->disconnect();
6319 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006320}
6321
François Gaffiec005e562018-11-06 15:04:49 +01006322sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6323 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006324{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006325 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006326 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006327 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006328 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006329 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6330 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006331 source = sourceDesc;
6332 break;
6333 }
6334 }
6335 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006336}
6337
Eric Laurentb4f42a92022-01-17 17:37:31 +01006338bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006339 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006340 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006341{
6342 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6343 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006344 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006345 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006346 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6347 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6348 return false;
6349 }
6350 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6351 return false;
6352 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006353 }
6354
Eric Laurentd332bc82023-08-04 11:45:23 +02006355 // The caller can have the audio config criteria ignored by either passing a null ptr or
6356 // the AUDIO_CONFIG_INITIALIZER value.
6357 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006358 // some positional channel masks and PCM format and for stereo if low latency performance
6359 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006360
6361 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006362 static const bool stereo_spatialization_enabled =
6363 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006364 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006365 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006366 ? audio_channel_mask_contains_stereo(config->channel_mask)
6367 : audio_is_channel_mask_spatialized(config->channel_mask);
6368 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006369 return false;
6370 }
6371 if (!audio_is_linear_pcm(config->format)) {
6372 return false;
6373 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006374 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6375 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6376 return false;
6377 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006378 }
6379
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006380 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006381 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006382 if (profile == nullptr) {
6383 return false;
6384 }
6385
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006386 return true;
6387}
6388
Shunkai Yao4c3af932024-04-26 04:12:21 +00006389// The Spatializer output is compatible with Haptic use cases if:
6390// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6391// with client if client haptic channel bits were set, or
6392// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6393// including the haptic bits or creating the HapticGenerator effect for same session.
6394bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6395 const audio_config_t* config, audio_session_t sessionId) const {
6396 const auto clientHapticChannel =
6397 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6398 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6399 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6400
6401 if (threadOutputHapticChannel) {
6402 // check format and sampleRate match if client haptic channel mask exist
6403 if (clientHapticChannel) {
6404 return mSpatializerOutput->getFormat() == config->format &&
6405 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6406 }
6407 return true;
6408 } else {
6409 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6410 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6411 // HapticGenerator effect for this session) are not supported.
6412 return clientHapticChannel == 0 &&
6413 !mEffects.hasOrphanEffectsForSessionAndType(sessionId, FX_IID_HAPTICGENERATOR);
6414 }
6415}
6416
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006417void AudioPolicyManager::checkVirtualizerClientRoutes() {
6418 std::set<audio_stream_type_t> streamsToInvalidate;
6419 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006420 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6421 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006422 audio_attributes_t attr = client->attributes();
6423 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6424 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6425 audio_config_base_t clientConfig = client->config();
6426 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006427 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006428 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006429 streamsToInvalidate.insert(client->stream());
6430 }
6431 }
6432 }
6433
jiabinc44b3462022-12-08 12:52:31 -08006434 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006435}
6436
Eric Laurente191d1b2022-04-15 11:59:25 +02006437
6438bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6439 const sp<SwAudioOutputDescriptor>& outputDesc) {
6440 if (outputDesc->isDuplicated()) {
6441 return false;
6442 }
6443 DeviceVector devices = outputDesc->supportedDevices();
6444 for (size_t i = 0; i < mOutputs.size(); i++) {
6445 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6446 if (desc == outputDesc || desc->isDuplicated()) {
6447 continue;
6448 }
6449 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6450 if (!sharedDevices.isEmpty()
6451 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6452 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6453 return false;
6454 }
6455 }
6456 return true;
6457}
6458
6459
Eric Laurentfa0f6742021-08-17 18:39:44 +02006460status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006461 const audio_attributes_t *attr,
6462 audio_io_handle_t *output) {
6463 *output = AUDIO_IO_HANDLE_NONE;
6464
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006465 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6466 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6467 audio_config_t *configPtr = nullptr;
6468 audio_config_t config;
6469 if (mixerConfig != nullptr) {
6470 config = audio_config_initializer(mixerConfig);
6471 configPtr = &config;
6472 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006473 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006474 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006475 return BAD_VALUE;
6476 }
6477
6478 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006479 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006480 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006481 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006482 return BAD_VALUE;
6483 }
6484
Eric Laurente191d1b2022-04-15 11:59:25 +02006485 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006486 for (size_t i = 0; i < mOutputs.size(); i++) {
6487 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006488 if (!desc->isDuplicated()
6489 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6490 spatializerOutputs.push_back(desc);
6491 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006492 }
6493 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006494 mSpatializerOutput.clear();
6495 bool outputsChanged = false;
6496 for (const auto& desc : spatializerOutputs) {
6497 if (desc->mProfile == profile
6498 && (configPtr == nullptr
6499 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6500 mSpatializerOutput = desc;
6501 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6502 } else {
6503 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6504 " and devices %s", __func__, desc->mIoHandle,
6505 configPtr != nullptr ? configPtr->channel_mask : 0,
6506 devices.toString().c_str());
6507 closeOutput(desc->mIoHandle);
6508 outputsChanged = true;
6509 }
Eric Laurent39095982021-08-24 18:29:27 +02006510 }
6511
Eric Laurente191d1b2022-04-15 11:59:25 +02006512 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006513 sp<SwAudioOutputDescriptor> desc =
6514 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006515 if (desc != nullptr) {
6516 mSpatializerOutput = desc;
6517 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006518 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006519 }
6520
6521 checkVirtualizerClientRoutes();
6522
Eric Laurente191d1b2022-04-15 11:59:25 +02006523 if (outputsChanged) {
6524 mPreviousOutputs = mOutputs;
6525 mpClientInterface->onAudioPortListUpdate();
6526 }
6527
6528 if (mSpatializerOutput == nullptr) {
6529 ALOGV("%s could not open spatializer output with requested config", __func__);
6530 return BAD_VALUE;
6531 }
Eric Laurent39095982021-08-24 18:29:27 +02006532 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006533 ALOGV("%s returning new spatializer output %d", __func__, *output);
6534 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006535}
6536
Eric Laurentfa0f6742021-08-17 18:39:44 +02006537status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6538 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006539 return INVALID_OPERATION;
6540 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006541 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006542 return BAD_VALUE;
6543 }
Eric Laurent39095982021-08-24 18:29:27 +02006544
Eric Laurente191d1b2022-04-15 11:59:25 +02006545 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6546 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6547 closeOutput(mSpatializerOutput->mIoHandle);
6548 //from now on mSpatializerOutput is null
6549 checkVirtualizerClientRoutes();
6550 }
Eric Laurent39095982021-08-24 18:29:27 +02006551
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006552 return NO_ERROR;
6553}
6554
Eric Laurente552edb2014-03-10 17:42:56 -07006555// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006556// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006557// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006558uint32_t AudioPolicyManager::nextAudioPortGeneration()
6559{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006560 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006561}
6562
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006563AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006564 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006565 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006566 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006567 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006568 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006569 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006570 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006571 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006572 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006573 mAudioPortGeneration(1),
6574 mBeaconMuteRefCount(0),
6575 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006576 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006577 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006578 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006579 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006580{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006581}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006582
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006583status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006584 if (mEngine == nullptr) {
6585 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006586 }
6587 mEngine->setObserver(this);
6588 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006589 if (status != NO_ERROR) {
6590 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6591 return status;
6592 }
François Gaffie2110e042015-03-24 08:41:51 +01006593
jiabin29230182023-04-04 21:02:36 +00006594 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6595 // at the end of this function.
6596 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006597 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6598 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6599
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006600 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006601 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006602 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006603
Eric Laurent3a4311c2014-03-17 12:00:47 -07006604 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006605 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6606 defaultOutputDevice == nullptr ||
6607 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6608 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6609 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006610 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006611 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006612 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006613
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006614 // Silence ALOGV statements
6615 property_set("log.tag." LOG_TAG, "D");
6616
Eric Laurente552edb2014-03-10 17:42:56 -07006617 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006618 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006619}
6620
Eric Laurente0720872014-03-11 09:30:41 -07006621AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006622{
Eric Laurente552edb2014-03-10 17:42:56 -07006623 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006624 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006625 }
6626 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006627 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006628 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006629 mAvailableOutputDevices.clear();
6630 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006631 mOutputs.clear();
6632 mInputs.clear();
6633 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006634 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006635 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006636}
6637
Eric Laurente0720872014-03-11 09:30:41 -07006638status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006639{
Eric Laurent87ffa392015-05-22 10:32:38 -07006640 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006641}
6642
Eric Laurente552edb2014-03-10 17:42:56 -07006643// ---
6644
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006645void AudioPolicyManager::onNewAudioModulesAvailable()
6646{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006647 DeviceVector newDevices;
6648 onNewAudioModulesAvailableInt(&newDevices);
6649 if (!newDevices.empty()) {
6650 nextAudioPortGeneration();
6651 mpClientInterface->onAudioPortListUpdate();
6652 }
6653}
6654
6655void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6656{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006657 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006658 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6659 continue;
6660 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006661 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006662 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6663 handle != AUDIO_MODULE_HANDLE_NONE) {
6664 hwModule->setHandle(handle);
6665 } else {
6666 ALOGW("could not load HW module %s", hwModule->getName());
6667 continue;
6668 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006669 }
6670 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006671 // open all output streams needed to access attached devices.
6672 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006673 // This also validates mAvailableOutputDevices list
6674 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6675 if (!outProfile->canOpenNewIo()) {
6676 ALOGE("Invalid Output profile max open count %u for profile %s",
6677 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6678 continue;
6679 }
6680 if (!outProfile->hasSupportedDevices()) {
6681 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6682 continue;
6683 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006684 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6685 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006686 mTtsOutputAvailable = true;
6687 }
6688
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006689 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006690 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006691 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006692 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6693 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006694 } else {
6695 // choose first device present in profile's SupportedDevices also part of
6696 // mAvailableOutputDevices.
6697 if (availProfileDevices.isEmpty()) {
6698 continue;
6699 }
6700 supportedDevice = availProfileDevices.itemAt(0);
6701 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006702 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006703 continue;
6704 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306705
6706 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6707 && availProfileDevices.areAllDevicesAttached()) {
6708 ALOGV("%s skip opening output for mmap profile %s", __func__,
6709 outProfile->getTagName().c_str());
6710 continue;
6711 }
6712
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006713 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6714 mpClientInterface);
6715 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006716 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6717 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006718 AUDIO_STREAM_DEFAULT,
6719 AUDIO_OUTPUT_FLAG_NONE, &output);
6720 if (status != NO_ERROR) {
6721 ALOGW("Cannot open output stream for devices %s on hw module %s",
6722 supportedDevice->toString().c_str(), hwModule->getName());
6723 continue;
6724 }
6725 for (const auto &device : availProfileDevices) {
6726 // give a valid ID to an attached device once confirmed it is reachable
6727 if (!device->isAttached()) {
6728 device->attach(hwModule);
6729 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006730 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006731 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006732 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6733 }
6734 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006735 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006736 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6737 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006738 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006739 }
Eric Laurent39095982021-08-24 18:29:27 +02006740 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006741 outputDesc->close();
6742 } else {
6743 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306744 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006745 DeviceVector(supportedDevice),
6746 true,
6747 0,
6748 NULL);
6749 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006750 }
6751 // open input streams needed to access attached devices to validate
6752 // mAvailableInputDevices list
6753 for (const auto& inProfile : hwModule->getInputProfiles()) {
6754 if (!inProfile->canOpenNewIo()) {
6755 ALOGE("Invalid Input profile max open count %u for profile %s",
6756 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6757 continue;
6758 }
6759 if (!inProfile->hasSupportedDevices()) {
6760 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6761 continue;
6762 }
6763 // chose first device present in profile's SupportedDevices also part of
6764 // available input devices
6765 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006766 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006767 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006768 ALOGV("%s: Input device list is empty! for profile %s",
6769 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006770 continue;
6771 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306772
6773 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6774 && availProfileDevices.areAllDevicesAttached()) {
6775 ALOGV("%s skip opening input for mmap profile %s", __func__,
6776 inProfile->getTagName().c_str());
6777 continue;
6778 }
6779
Eric Laurentc71b11b2024-06-03 12:54:53 +00006780 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6781 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006782
6783 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6784 status_t status = inputDesc->open(nullptr,
6785 availProfileDevices.itemAt(0),
6786 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306787 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006788 &input);
6789 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306790 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6791 __func__, availProfileDevices.toString().c_str(),
6792 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006793 continue;
6794 }
6795 for (const auto &device : availProfileDevices) {
6796 // give a valid ID to an attached device once confirmed it is reachable
6797 if (!device->isAttached()) {
6798 device->attach(hwModule);
6799 device->importAudioPortAndPickAudioProfile(inProfile, true);
6800 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006801 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006802 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6803 }
6804 }
6805 inputDesc->close();
6806 }
6807 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006808
6809 // Check if spatializer outputs can be closed until used.
6810 // mOutputs vector never contains duplicated outputs at this point.
6811 std::vector<audio_io_handle_t> outputsClosed;
6812 for (size_t i = 0; i < mOutputs.size(); i++) {
6813 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6814 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6815 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6816 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006817 nextAudioPortGeneration();
6818 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6819 if (index >= 0) {
6820 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6821 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6822 patchDesc->getAfHandle(), 0);
6823 mAudioPatches.removeItemsAt(index);
6824 mpClientInterface->onAudioPatchListUpdate();
6825 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006826 desc->close();
6827 }
6828 }
6829 for (auto output : outputsClosed) {
6830 removeOutput(output);
6831 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006832}
6833
Eric Laurent98e38192018-02-15 18:31:53 -08006834void AudioPolicyManager::addOutput(audio_io_handle_t output,
6835 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006836{
Eric Laurent1c333e22014-05-20 10:48:17 -07006837 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006838 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006839 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006840 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006841 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006842}
6843
François Gaffie53615e22015-03-19 09:24:12 +01006844void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6845{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006846 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6847 ALOGV("%s: removing primary output", __func__);
6848 mPrimaryOutput = nullptr;
6849 }
François Gaffie53615e22015-03-19 09:24:12 +01006850 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006851 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006852}
6853
Eric Laurent98e38192018-02-15 18:31:53 -08006854void AudioPolicyManager::addInput(audio_io_handle_t input,
6855 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006856{
Eric Laurent1c333e22014-05-20 10:48:17 -07006857 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006858 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006859}
Eric Laurente552edb2014-03-10 17:42:56 -07006860
François Gaffie11d30102018-11-02 16:09:09 +01006861status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006862 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006863 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006864{
François Gaffie11d30102018-11-02 16:09:09 +01006865 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006866 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006867 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006868
François Gaffie11d30102018-11-02 16:09:09 +01006869 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006870 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006871 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006872 }
Eric Laurente552edb2014-03-10 17:42:56 -07006873
Eric Laurent3b73df72014-03-11 09:06:29 -07006874 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006875 // first call getAudioPort to get the supported attributes from the HAL
6876 struct audio_port_v7 port = {};
6877 device->toAudioPort(&port);
6878 status_t status = mpClientInterface->getAudioPort(&port);
6879 if (status == NO_ERROR) {
6880 device->importAudioPort(port);
6881 }
6882
6883 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006884 for (size_t i = 0; i < mOutputs.size(); i++) {
6885 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006886 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006887 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006888 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6889 mOutputs.keyAt(i), device->toString().c_str());
6890 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006891 }
6892 }
6893 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006894 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006895 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006896 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6897 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006898 if (profile->supportsDevice(device)) {
6899 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05306900 ALOGV("%s(): adding profile %s from module %s",
6901 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006902 }
6903 }
6904 }
6905
Eric Laurent7b279bb2015-12-14 10:18:23 -08006906 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006907
Eric Laurente552edb2014-03-10 17:42:56 -07006908 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006909 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006910 return BAD_VALUE;
6911 }
6912
6913 // open outputs for matching profiles if needed. Direct outputs are also opened to
6914 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6915 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006916 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006917
6918 // nothing to do if one output is already opened for this profile
6919 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006920 for (j = 0; j < outputs.size(); j++) {
6921 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006922 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006923 // matching profile: save the sample rates, format and channel masks supported
6924 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006925 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006926 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006927 }
Eric Laurente552edb2014-03-10 17:42:56 -07006928 break;
6929 }
6930 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006931 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006932 continue;
6933 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306934 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6935 ALOGV("%s skip opening output for mmap profile %s",
6936 __func__, profile->getTagName().c_str());
6937 continue;
6938 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006939 if (!profile->canOpenNewIo()) {
6940 ALOGW("Max Output number %u already opened for this profile %s",
6941 profile->maxOpenCount, profile->getTagName().c_str());
6942 continue;
6943 }
6944
Eric Laurent83efe1c2017-07-09 16:51:08 -07006945 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006946 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006947 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6948 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006949 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006950 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006951 profiles.removeAt(profile_index);
6952 profile_index--;
6953 } else {
6954 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006955 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006956 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006957 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6958 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006959 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006960 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006961
François Gaffie11d30102018-11-02 16:09:09 +01006962 if (device_distinguishes_on_address(deviceType)) {
6963 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6964 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306965 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6966 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006967 }
Eric Laurente552edb2014-03-10 17:42:56 -07006968 ALOGV("checkOutputsForDevice(): adding output %d", output);
6969 }
6970 }
6971
6972 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006973 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006974 return BAD_VALUE;
6975 }
Eric Laurentd4692962014-05-05 18:13:44 -07006976 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006977 // check if one opened output is not needed any more after disconnecting one device
6978 for (size_t i = 0; i < mOutputs.size(); i++) {
6979 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006980 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006981 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006982 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006983 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006984 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006985 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006986 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6987 mOutputs.keyAt(i));
6988 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006989 }
Eric Laurente552edb2014-03-10 17:42:56 -07006990 }
6991 }
Eric Laurentd4692962014-05-05 18:13:44 -07006992 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006993 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006994 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6995 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006996 if (!profile->supportsDevice(device)) {
6997 continue;
6998 }
Jaideep Sharma33173202024-06-18 17:46:45 +05306999 ALOGV("%s(): clearing direct output profile %s on module %s",
7000 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007001 profile->clearAudioProfiles();
7002 if (!profile->hasDynamicAudioProfile()) {
7003 continue;
7004 }
7005 // When a device is disconnected, if there is an IOProfile that contains dynamic
7006 // profiles and supports the disconnected device, call getAudioPort to repopulate
7007 // the capabilities of the devices that is supported by the IOProfile.
7008 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7009 if (supportedDevice == device ||
7010 !mAvailableOutputDevices.contains(supportedDevice)) {
7011 continue;
7012 }
7013 struct audio_port_v7 port;
7014 supportedDevice->toAudioPort(&port);
7015 status_t status = mpClientInterface->getAudioPort(&port);
7016 if (status == NO_ERROR) {
7017 supportedDevice->importAudioPort(port);
7018 }
Eric Laurente552edb2014-03-10 17:42:56 -07007019 }
7020 }
7021 }
7022 }
7023 return NO_ERROR;
7024}
7025
François Gaffie11d30102018-11-02 16:09:09 +01007026status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007027 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007028{
François Gaffie11d30102018-11-02 16:09:09 +01007029 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007030 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007031 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007032 }
7033
Eric Laurentd4692962014-05-05 18:13:44 -07007034 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007035 sp<AudioInputDescriptor> desc;
7036
jiabinbf5f4262023-04-12 21:48:34 +00007037 // first call getAudioPort to get the supported attributes from the HAL
7038 struct audio_port_v7 port = {};
7039 device->toAudioPort(&port);
7040 status_t status = mpClientInterface->getAudioPort(&port);
7041 if (status == NO_ERROR) {
7042 device->importAudioPort(port);
7043 }
7044
Eric Laurent0dd51852019-04-19 18:18:58 -07007045 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007046 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007047 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007048 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007049 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007050 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007051 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007052
François Gaffie11d30102018-11-02 16:09:09 +01007053 if (profile->supportsDevice(device)) {
7054 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307055 ALOGV("%s : adding profile %s from module %s", __func__,
7056 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007057 }
7058 }
7059 }
7060
Eric Laurent0dd51852019-04-19 18:18:58 -07007061 if (profiles.isEmpty()) {
7062 ALOGW("%s: No input profile available for device %s",
7063 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007064 return BAD_VALUE;
7065 }
7066
7067 // open inputs for matching profiles if needed. Direct inputs are also opened to
7068 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7069 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7070
Eric Laurent1c333e22014-05-20 10:48:17 -07007071 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007072
Eric Laurentd4692962014-05-05 18:13:44 -07007073 // nothing to do if one input is already opened for this profile
7074 size_t input_index;
7075 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7076 desc = mInputs.valueAt(input_index);
7077 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007078 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007079 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007080 }
Eric Laurentd4692962014-05-05 18:13:44 -07007081 break;
7082 }
7083 }
7084 if (input_index != mInputs.size()) {
7085 continue;
7086 }
7087
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307088 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7089 ALOGV("%s skip opening input for mmap profile %s",
7090 __func__, profile->getTagName().c_str());
7091 continue;
7092 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007093 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307094 ALOGW("%s Max Input number %u already opened for this profile %s",
7095 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007096 continue;
7097 }
7098
Eric Laurentc71b11b2024-06-03 12:54:53 +00007099 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007100 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307101 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307102 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7103 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007104
Eric Laurentcf2c0212014-07-25 16:20:43 -07007105 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007106 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007107 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007108 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007109 mpClientInterface->setParameters(input, String8(param));
7110 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007111 }
jiabin12537fc2023-10-12 17:56:08 +00007112 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007113 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307114 ALOGW("%s direct input missing param for profile %s", __func__,
7115 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007116 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007117 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007118 }
7119
Eric Laurent0dd51852019-04-19 18:18:58 -07007120 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007121 addInput(input, desc);
7122 }
7123 } // endif input != 0
7124
Eric Laurentcf2c0212014-07-25 16:20:43 -07007125 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307126 ALOGW("%s could not open input for device %s on profile %s", __func__,
7127 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007128 profiles.removeAt(profile_index);
7129 profile_index--;
7130 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007131 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007132 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007133 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307134 ALOGV("%s: adding input %d for profile %s", __func__,
7135 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007136
7137 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307138 ALOGV("%s: closing input %d for profile %s", __func__,
7139 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007140 closeInput(input);
7141 }
Eric Laurentd4692962014-05-05 18:13:44 -07007142 }
7143 } // end scan profiles
7144
7145 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007146 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007147 return BAD_VALUE;
7148 }
7149 } else {
7150 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007151 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007152 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007153 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007154 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007155 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007156 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007157 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307158 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7159 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007160 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007161 }
7162 }
7163 }
7164 } // end disconnect
7165
7166 return NO_ERROR;
7167}
7168
7169
Eric Laurente0720872014-03-11 09:30:41 -07007170void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007171{
7172 ALOGV("closeOutput(%d)", output);
7173
François Gaffie1c878552018-11-22 16:53:21 +01007174 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7175 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007176 ALOGW("closeOutput() unknown output %d", output);
7177 return;
7178 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007179 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007180 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007181
Eric Laurente552edb2014-03-10 17:42:56 -07007182 // look for duplicated outputs connected to the output being removed.
7183 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007184 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7185 if (dupOutput->isDuplicated() &&
7186 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7187 sp<SwAudioOutputDescriptor> remainingOutput =
7188 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007189 // As all active tracks on duplicated output will be deleted,
7190 // and as they were also referenced on the other output, the reference
7191 // count for their stream type must be adjusted accordingly on
7192 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007193 const bool wasActive = remainingOutput->isActive();
7194 // Note: no-op on the closing output where all clients has already been set inactive
7195 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007196 // stop() will be a no op if the output is still active but is needed in case all
7197 // active streams refcounts where cleared above
7198 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007199 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007200 }
Eric Laurente552edb2014-03-10 17:42:56 -07007201 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7202 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7203
7204 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007205 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007206 }
7207 }
7208
Eric Laurent05b90f82014-08-27 15:32:29 -07007209 nextAudioPortGeneration();
7210
François Gaffie1c878552018-11-22 16:53:21 +01007211 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007212 if (index >= 0) {
7213 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007214 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7215 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007216 mAudioPatches.removeItemsAt(index);
7217 mpClientInterface->onAudioPatchListUpdate();
7218 }
7219
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007220 if (closingOutputWasActive) {
7221 closingOutput->stop();
7222 }
François Gaffie1c878552018-11-22 16:53:21 +01007223 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007224 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007225 for (const auto device : closingOutput->devices()) {
7226 device->setPreferredConfig(nullptr);
7227 }
7228 }
Eric Laurente552edb2014-03-10 17:42:56 -07007229
François Gaffie53615e22015-03-19 09:24:12 +01007230 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007231 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007232 if (closingOutput == mSpatializerOutput) {
7233 mSpatializerOutput.clear();
7234 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007235
7236 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7237 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007238 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007239 bool directOutputOpen = false;
7240 for (size_t i = 0; i < mOutputs.size(); i++) {
7241 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7242 directOutputOpen = true;
7243 break;
7244 }
7245 }
7246 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007247 ALOGV("no direct outputs open, reset MSD patches");
7248 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7249 // how output devices for patching are resolved. Avoid by caching and reusing the
7250 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7251 // devices to patch to. This may be complicated by the fact that devices may become
7252 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007253 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007254 }
7255 }
jiabin220eea12024-05-17 17:55:20 +00007256
7257 if (closingOutput->mPreferredAttrInfo != nullptr) {
7258 closingOutput->mPreferredAttrInfo->resetActiveClient();
7259 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007260}
7261
7262void AudioPolicyManager::closeInput(audio_io_handle_t input)
7263{
7264 ALOGV("closeInput(%d)", input);
7265
7266 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7267 if (inputDesc == NULL) {
7268 ALOGW("closeInput() unknown input %d", input);
7269 return;
7270 }
7271
Eric Laurent6a94d692014-05-20 11:18:06 -07007272 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007273
François Gaffie11d30102018-11-02 16:09:09 +01007274 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007275 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007276 if (index >= 0) {
7277 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007278 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7279 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007280 mAudioPatches.removeItemsAt(index);
7281 mpClientInterface->onAudioPatchListUpdate();
7282 }
7283
François Gaffie6ebbce02023-07-19 13:27:53 +02007284 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007285 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007286 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007287
François Gaffie11d30102018-11-02 16:09:09 +01007288 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7289 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007290 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007291 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007292 }
Eric Laurente552edb2014-03-10 17:42:56 -07007293}
7294
François Gaffie11d30102018-11-02 16:09:09 +01007295SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7296 const DeviceVector &devices,
7297 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007298{
7299 SortedVector<audio_io_handle_t> outputs;
7300
François Gaffie11d30102018-11-02 16:09:09 +01007301 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007302 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007303 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007304 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007305 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007306 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007307 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007308 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007309 outputs.add(openOutputs.keyAt(i));
7310 }
7311 }
7312 return outputs;
7313}
7314
Mikhail Naganov37977152018-07-11 15:54:44 -07007315void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7316{
7317 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7318 // output is suspended before any tracks are moved to it
7319 checkA2dpSuspend();
7320 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007321 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007322 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007323 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007324 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007325 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7326 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7327 // configuration changes will ultimately be rerouted correctly. We can still avoid
7328 // unnecessary rerouting by caching and reusing the arguments to
7329 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7330 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007331 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007332 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007333 // an event that changed routing likely occurred, inform upper layers
7334 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007335}
7336
François Gaffiec005e562018-11-06 15:04:49 +01007337bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7338 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007339{
François Gaffiec005e562018-11-06 15:04:49 +01007340 return mEngine->getProductStrategyForAttributes(lAttr) ==
7341 mEngine->getProductStrategyForAttributes(rAttr);
7342}
7343
Francois Gaffieff1eb522020-05-06 18:37:04 +02007344void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7345{
7346 for (size_t i = 0; i < mAudioSources.size(); i++) {
7347 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7348 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007349 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007350 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007351 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007352 }
7353 }
7354}
7355
7356void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7357{
7358 for (size_t i = 0; i < mAudioSources.size(); i++) {
7359 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7360 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7361 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7362 disconnectAudioSource(sourceDesc);
7363 }
7364 }
7365}
7366
François Gaffiec005e562018-11-06 15:04:49 +01007367void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7368{
7369 auto psId = mEngine->getProductStrategyForAttributes(attr);
7370
7371 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7372 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007373
François Gaffie11d30102018-11-02 16:09:09 +01007374 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7375 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007376
Eric Laurentc209fe42020-06-05 18:11:23 -07007377 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007378 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007379 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007380 // take into account dynamic audio policies related changes: if a client is now associated
7381 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007382 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007383 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7384 if (desc->isDuplicated()) {
7385 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007386 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007387 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7388 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7389 continue;
7390 }
7391 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007392 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007393 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7394 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7395 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007396 if (status != OK) {
7397 continue;
7398 }
yucliuf4de36d2020-09-14 14:57:56 -07007399 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007400 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007401 maxLatency = desc->latency();
7402 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007403 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007404 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007405 }
7406 }
7407
Eric Laurent56ed8842022-11-15 16:04:41 +01007408 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007409 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7410 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007411 for (audio_io_handle_t srcOut : srcOutputs) {
7412 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007413 if (desc == nullptr) continue;
7414
7415 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007416 maxLatency = desc->latency();
7417 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007418
Eric Laurent56ed8842022-11-15 16:04:41 +01007419 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007420 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007421 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007422 // a client on a non direct outputs has necessarily a linear PCM format
7423 // so we can call selectOutput() safely
7424 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7425 client->flags(),
7426 client->config().format,
7427 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007428 client->config().sample_rate,
7429 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007430 if (newOutput != srcOut) {
7431 invalidate = true;
7432 break;
7433 }
7434 } else {
7435 sp<IOProfile> profile = getProfileForOutput(newDevices,
7436 client->config().sample_rate,
7437 client->config().format,
7438 client->config().channel_mask,
7439 client->flags(),
7440 true /* directOnly */);
7441 if (profile != desc->mProfile) {
7442 invalidate = true;
7443 break;
7444 }
7445 }
7446 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007447 // mute strategy while moving tracks from one output to another
7448 if (invalidate) {
7449 invalidatedOutputs.push_back(desc);
7450 if (desc->isStrategyActive(psId)) {
7451 setStrategyMute(psId, true, desc);
7452 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7453 newDevices.types());
7454 }
Eric Laurente552edb2014-03-10 17:42:56 -07007455 }
François Gaffiec005e562018-11-06 15:04:49 +01007456 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007457 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007458 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007459 }
Eric Laurente552edb2014-03-10 17:42:56 -07007460 }
7461
Eric Laurent56ed8842022-11-15 16:04:41 +01007462 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7463 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7464 std::to_string(srcOutputs[0]).c_str(),
7465 std::to_string(dstOutputs[0]).c_str());
7466
François Gaffiec005e562018-11-06 15:04:49 +01007467 // Move effects associated to this stream from previous output to new output
7468 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007469 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007470 }
François Gaffiec005e562018-11-06 15:04:49 +01007471 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007472 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007473 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007474 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007475 desc->setTracksInvalidatedStatusByStrategy(psId);
7476 }
Eric Laurente552edb2014-03-10 17:42:56 -07007477 }
7478 }
7479}
7480
Eric Laurente0720872014-03-11 09:30:41 -07007481void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007482{
François Gaffiec005e562018-11-06 15:04:49 +01007483 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7484 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7485 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007486 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007487 }
Eric Laurente552edb2014-03-10 17:42:56 -07007488}
7489
Kevin Rocard153f92d2018-12-18 18:33:28 -08007490void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007491 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007492 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007493 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007494 for (size_t i = 0; i < mOutputs.size(); i++) {
7495 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7496 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007497 sp<AudioPolicyMix> primaryMix;
7498 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007499 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007500 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7501 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7502 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007503 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7504 for (auto &secondaryMix : secondaryMixes) {
7505 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7506 if (outputDesc != nullptr &&
7507 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7508 secondaryDescs.push_back(outputDesc);
7509 }
7510 }
7511
jiabinc44b3462022-12-08 12:52:31 -08007512 if (status != OK &&
7513 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7514 // When it failed to query secondary output, only invalidate the client that is not
7515 // MMAP. The reason is that MMAP stream will not support secondary output.
7516 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007517 } else if (!std::equal(
7518 client->getSecondaryOutputs().begin(),
7519 client->getSecondaryOutputs().end(),
7520 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007521 if (!audio_is_linear_pcm(client->config().format)) {
7522 // If the format is not PCM, the tracks should be invalidated to get correct
7523 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007524 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007525 } else {
7526 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7527 std::vector<audio_io_handle_t> secondaryOutputIds;
7528 for (const auto &secondaryDesc: secondaryDescs) {
7529 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7530 weakSecondaryDescs.push_back(secondaryDesc);
7531 }
7532 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7533 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007534 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007535 }
7536 }
7537 }
jiabin10a03f12021-05-07 23:46:28 +00007538 if (!trackSecondaryOutputs.empty()) {
7539 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7540 }
jiabinc44b3462022-12-08 12:52:31 -08007541 if (!clientsToInvalidate.empty()) {
7542 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7543 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007544 }
7545}
7546
Eric Laurent2517af32020-11-25 15:31:27 +01007547bool AudioPolicyManager::isScoRequestedForComm() const {
7548 AudioDeviceTypeAddrVector devices;
7549 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7550 for (const auto &device : devices) {
7551 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7552 return true;
7553 }
7554 }
7555 return false;
7556}
7557
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007558bool AudioPolicyManager::isHearingAidUsedForComm() const {
7559 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7560 true /*fromCache*/);
7561 for (const auto &device : devices) {
7562 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7563 return true;
7564 }
7565 }
7566 return false;
7567}
7568
7569
Eric Laurente0720872014-03-11 09:30:41 -07007570void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007571{
François Gaffie53615e22015-03-19 09:24:12 +01007572 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007573 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007574 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007575 return;
7576 }
7577
Eric Laurent3a4311c2014-03-17 12:00:47 -07007578 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007579 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7580 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007581 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007582
7583 // if suspended, restore A2DP output if:
7584 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007585 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007586 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007587 //
Eric Laurentf732e072016-08-03 19:30:28 -07007588 // if not suspended, suspend A2DP output if:
7589 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007590 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007591 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007592 //
7593 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007594 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007595 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007596 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007597 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007598
7599 mpClientInterface->restoreOutput(a2dpOutput);
7600 mA2dpSuspended = false;
7601 }
7602 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007603 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007604 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007605 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007606 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007607
7608 mpClientInterface->suspendOutput(a2dpOutput);
7609 mA2dpSuspended = true;
7610 }
7611 }
7612}
7613
François Gaffie11d30102018-11-02 16:09:09 +01007614DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7615 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007616{
François Gaffiedb1755b2023-09-01 11:50:35 +02007617 if (outputDesc == nullptr) {
7618 return DeviceVector{};
7619 }
François Gaffie11d30102018-11-02 16:09:09 +01007620
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007621 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007622 if (index >= 0) {
7623 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007624 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007625 ALOGV("%s device %s forced by patch %d", __func__,
7626 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7627 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007628 }
7629 }
7630
Dean Wheatley514b4312020-06-17 21:45:00 +10007631 // Do not retrieve engine device for outputs through MSD
7632 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7633 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7634 return outputDesc->devices();
7635 }
7636
Eric Laurent97ac8712018-07-27 18:59:02 -07007637 // Honor explicit routing requests only if no client using default routing is active on this
7638 // input: a specific app can not force routing for other apps by setting a preferred device.
7639 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007640 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007641 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007642 if (device != nullptr) {
7643 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007644 }
7645
François Gaffiea807ef92018-11-05 10:44:33 +01007646 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7647 // of setForceUse / Default Bus device here
7648 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7649 if (device != nullptr) {
7650 return DeviceVector(device);
7651 }
7652
François Gaffiedb1755b2023-09-01 11:50:35 +02007653 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007654 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7655 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307656 auto hasStreamActive = [&](auto stream) {
7657 return hasStream(streams, stream) && isStreamActive(stream, 0);
7658 };
Eric Laurent484e9272018-06-07 17:29:23 -07007659
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307660 auto doGetOutputDevicesForVoice = [&]() {
7661 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007662 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307663 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007664 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7665 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307666 };
7667
7668 // With low-latency playing on speaker, music on WFD, when the first low-latency
7669 // output is stopped, getNewOutputDevices checks for a product strategy
7670 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007671 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307672 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7673 // stream is associated to the output descriptor.
7674 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7675 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7676 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7677 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007678 // Retrieval of devices for voice DL is done on primary output profile, cannot
7679 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007680 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007681 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7682 break;
7683 }
Eric Laurente552edb2014-03-10 17:42:56 -07007684 }
François Gaffiec005e562018-11-06 15:04:49 +01007685 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007686 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007687}
7688
François Gaffie11d30102018-11-02 16:09:09 +01007689sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7690 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007691{
François Gaffie11d30102018-11-02 16:09:09 +01007692 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007693
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007694 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007695 if (index >= 0) {
7696 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007697 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007698 ALOGV("getNewInputDevice() device %s forced by patch %d",
7699 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7700 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007701 }
7702 }
7703
Eric Laurent97ac8712018-07-27 18:59:02 -07007704 // Honor explicit routing requests only if no client using default routing is active on this
7705 // input: a specific app can not force routing for other apps by setting a preferred device.
7706 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007707 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7708 if (device != nullptr) {
7709 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007710 }
7711
Eric Laurentdc95a252018-04-12 12:46:56 -07007712 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007713 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007714 audio_attributes_t attributes;
7715 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007716 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007717 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7718 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007719 attributes = topClient->attributes();
7720 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007721 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007722 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007723 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7724 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007725 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007726 }
7727
Francois Gaffie716e1432019-01-14 16:58:59 +01007728 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7729 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007730 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007731 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007732 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007733 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007734
Eric Laurente552edb2014-03-10 17:42:56 -07007735 return device;
7736}
7737
Eric Laurent794fde22016-03-11 09:50:45 -08007738bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7739 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007740 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007741}
7742
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007743status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007744 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007745 if (devices == nullptr) {
7746 return BAD_VALUE;
7747 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007748
Andy Hung6d23c0f2022-02-16 09:37:15 -08007749 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007750 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7751 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007752 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007753 for (const auto& device : curDevices) {
7754 devices->push_back(device->getDeviceTypeAddr());
7755 }
7756 return NO_ERROR;
7757}
7758
Eric Laurente0720872014-03-11 09:30:41 -07007759void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007760 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007761 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007762 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007763 updateDevicesAndOutputs();
7764 break;
7765 default:
7766 break;
7767 }
7768}
7769
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007770uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007771
7772 // skip beacon mute management if a dedicated TTS output is available
7773 if (mTtsOutputAvailable) {
7774 return 0;
7775 }
7776
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007777 switch(event) {
7778 case STARTING_OUTPUT:
7779 mBeaconMuteRefCount++;
7780 break;
7781 case STOPPING_OUTPUT:
7782 if (mBeaconMuteRefCount > 0) {
7783 mBeaconMuteRefCount--;
7784 }
7785 break;
7786 case STARTING_BEACON:
7787 mBeaconPlayingRefCount++;
7788 break;
7789 case STOPPING_BEACON:
7790 if (mBeaconPlayingRefCount > 0) {
7791 mBeaconPlayingRefCount--;
7792 }
7793 break;
7794 }
7795
7796 if (mBeaconMuteRefCount > 0) {
7797 // any playback causes beacon to be muted
7798 return setBeaconMute(true);
7799 } else {
7800 // no other playback: unmute when beacon starts playing, mute when it stops
7801 return setBeaconMute(mBeaconPlayingRefCount == 0);
7802 }
7803}
7804
7805uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7806 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7807 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7808 // keep track of muted state to avoid repeating mute/unmute operations
7809 if (mBeaconMuted != mute) {
7810 // mute/unmute AUDIO_STREAM_TTS on all outputs
7811 ALOGV("\t muting %d", mute);
7812 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007813 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7814 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7815 ALOGV("\t no tts volume source available");
7816 return 0;
7817 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007818 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007819 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007820 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007821 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007822 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007823 maxLatency = latency;
7824 }
7825 }
7826 mBeaconMuted = mute;
7827 return maxLatency;
7828 }
7829 return 0;
7830}
7831
Eric Laurente0720872014-03-11 09:30:41 -07007832void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007833{
François Gaffiec005e562018-11-06 15:04:49 +01007834 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007835 mPreviousOutputs = mOutputs;
7836}
7837
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007838uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007839 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007840 uint32_t delayMs)
7841{
7842 // mute/unmute strategies using an incompatible device combination
7843 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7844 // if unmuting, unmute only after the specified delay
7845 if (outputDesc->isDuplicated()) {
7846 return 0;
7847 }
7848
7849 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007850 DeviceVector devices = outputDesc->devices();
7851 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007852
François Gaffiec005e562018-11-06 15:04:49 +01007853 auto productStrategies = mEngine->getOrderedProductStrategies();
7854 for (const auto &productStrategy : productStrategies) {
7855 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7856 DeviceVector curDevices =
7857 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7858 curDevices = curDevices.filter(outputDesc->supportedDevices());
7859 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007860 bool doMute = false;
7861
François Gaffiec005e562018-11-06 15:04:49 +01007862 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007863 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007864 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7865 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007866 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007867 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007868 }
Eric Laurent99401132014-05-07 19:48:15 -07007869 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007870 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007871 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007872 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007873 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007874 continue;
7875 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307876 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007877 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7878 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7879 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007880 if (mute) {
7881 // FIXME: should not need to double latency if volume could be applied
7882 // immediately by the audioflinger mixer. We must account for the delay
7883 // between now and the next time the audioflinger thread for this output
7884 // will process a buffer (which corresponds to one buffer size,
7885 // usually 1/2 or 1/4 of the latency).
7886 if (muteWaitMs < desc->latency() * 2) {
7887 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007888 }
7889 }
7890 }
7891 }
7892 }
7893 }
7894
Eric Laurent99401132014-05-07 19:48:15 -07007895 // temporary mute output if device selection changes to avoid volume bursts due to
7896 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007897 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007898 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007899
Eric Laurentdc462862016-07-19 12:29:53 -07007900 if (muteWaitMs < tempMuteWaitMs) {
7901 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007902 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007903
7904 // If recommended duration is defined, replace temporary mute duration to avoid
7905 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7906 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7907 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7908 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7909 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7910
François Gaffieaaac0fd2018-11-22 17:56:39 +01007911 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7912 // make sure that we do not start the temporary mute period too early in case of
7913 // delayed device change
7914 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7915 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007916 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007917 }
7918 }
7919
Eric Laurente552edb2014-03-10 17:42:56 -07007920 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7921 if (muteWaitMs > delayMs) {
7922 muteWaitMs -= delayMs;
7923 usleep(muteWaitMs * 1000);
7924 return muteWaitMs;
7925 }
7926 return 0;
7927}
7928
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307929uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7930 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007931 const DeviceVector &devices,
7932 bool force,
7933 int delayMs,
7934 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007935 bool requiresMuteCheck, bool requiresVolumeCheck,
7936 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007937{
jiabin3ff8d7d2022-12-13 06:27:44 +00007938 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307939 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7940 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7941 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007942 uint32_t muteWaitMs;
7943
7944 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307945 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007946 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307947 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007948 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007949 return muteWaitMs;
7950 }
Eric Laurente552edb2014-03-10 17:42:56 -07007951
7952 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007953 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007954 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007955 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007956
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307957 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7958 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007959
7960 if (!filteredDevices.isEmpty()) {
7961 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007962 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007963
7964 // if the outputs are not materially active, there is no need to mute.
7965 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007966 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007967 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307968 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7969 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007970 muteWaitMs = 0;
7971 }
Eric Laurente552edb2014-03-10 17:42:56 -07007972
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007973 bool outputRouted = outputDesc->isRouted();
7974
Eric Laurent79ea9582020-06-11 18:49:24 -07007975 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7976 // output profile or if new device is not supported AND previous device(s) is(are) still
7977 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007978 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307979 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7980 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007981 // restore previous device after evaluating strategy mute state
7982 outputDesc->setDevices(prevDevices);
7983 return muteWaitMs;
7984 }
7985
Eric Laurente552edb2014-03-10 17:42:56 -07007986 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007987 // the requested device is AUDIO_DEVICE_NONE
7988 // OR the requested device is the same as current device
7989 // AND force is not specified
7990 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007991 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007992 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307993 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7994 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7995 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007996 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307997 ALOGV("%s %s setting same device on routed output, force apply volumes",
7998 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007999 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8000 }
Eric Laurente552edb2014-03-10 17:42:56 -07008001 return muteWaitMs;
8002 }
8003
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308004 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8005 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008006
Eric Laurente552edb2014-03-10 17:42:56 -07008007 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008008 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008009 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008010 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008011 PatchBuilder patchBuilder;
8012 patchBuilder.addSource(outputDesc);
8013 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8014 for (const auto &filteredDevice : filteredDevices) {
8015 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008016 }
8017
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008018 // Add half reported latency to delayMs when muteWaitMs is null in order
8019 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008020 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8021 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8022 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008023 }
Eric Laurente552edb2014-03-10 17:42:56 -07008024
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008025 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8026 if (!skipMuteDelay) {
8027 // update stream volumes according to new device
8028 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8029 }
Eric Laurente552edb2014-03-10 17:42:56 -07008030
8031 return muteWaitMs;
8032}
8033
Eric Laurentc75307b2015-03-17 15:29:32 -07008034status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008035 int delayMs,
8036 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008037{
Eric Laurent6a94d692014-05-20 11:18:06 -07008038 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008039 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8040 return INVALID_OPERATION;
8041 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008042 if (patchHandle) {
8043 index = mAudioPatches.indexOfKey(*patchHandle);
8044 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008045 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008046 }
8047 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008048 return INVALID_OPERATION;
8049 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008050 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008051 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008052 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008053 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008054 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008055 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008056 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008057 return status;
8058}
8059
8060status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008061 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008062 bool force,
8063 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008064{
8065 status_t status = NO_ERROR;
8066
Eric Laurent1f2f2232014-06-02 12:01:23 -07008067 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008068 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8069 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008070
François Gaffie11d30102018-11-02 16:09:09 +01008071 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008072 PatchBuilder patchBuilder;
8073 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008074 // AUDIO_SOURCE_HOTWORD is for internal use only:
8075 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008076 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8077 auto result = usecase;
8078 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8079 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8080 }
8081 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07008082 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01008083 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008084 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008085 }
8086 }
8087 return status;
8088}
8089
Eric Laurent6a94d692014-05-20 11:18:06 -07008090status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8091 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008092{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008093 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008094 ssize_t index;
8095 if (patchHandle) {
8096 index = mAudioPatches.indexOfKey(*patchHandle);
8097 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008098 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008099 }
8100 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008101 return INVALID_OPERATION;
8102 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008103 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008104 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008105 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008106 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008107 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008108 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008109 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008110 return status;
8111}
8112
François Gaffie11d30102018-11-02 16:09:09 +01008113sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008114 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008115 audio_format_t& format,
8116 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008117 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008118{
8119 // Choose an input profile based on the requested capture parameters: select the first available
8120 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008121 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008122
Atneya Nair0f0a8032022-12-12 16:20:12 -08008123 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8124 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8125 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8126
8127 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008128
jiabin2fd710d2022-05-02 23:20:22 +00008129 for (;;) {
8130 sp<IOProfile> firstInexact = nullptr;
8131 uint32_t updatedSamplingRate = 0;
8132 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8133 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8134 for (const auto& hwModule : mHwModules) {
8135 for (const auto& profile : hwModule->getInputProfiles()) {
8136 // profile->log();
8137 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008138 if (profile->getCompatibilityScore(
8139 DeviceVector(device),
8140 samplingRate,
8141 &updatedSamplingRate,
8142 format,
8143 &updatedFormat,
8144 channelMask,
8145 &updatedChannelMask,
8146 // FIXME ugly cast
8147 (audio_output_flags_t) flags,
8148 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8149 samplingRate = updatedSamplingRate;
8150 format = updatedFormat;
8151 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008152 return profile;
8153 }
jiabin66acc432024-02-06 00:57:36 +00008154 if (firstInexact == nullptr
8155 && profile->getCompatibilityScore(
8156 DeviceVector(device),
8157 samplingRate,
8158 &updatedSamplingRate,
8159 format,
8160 &updatedFormat,
8161 channelMask,
8162 &updatedChannelMask,
8163 // FIXME ugly cast
8164 (audio_output_flags_t) flags,
8165 false /*exactMatchRequiredForInputFlags*/)
8166 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008167 firstInexact = profile;
8168 }
8169 }
8170 }
8171
8172 if (firstInexact != nullptr) {
8173 samplingRate = updatedSamplingRate;
8174 format = updatedFormat;
8175 channelMask = updatedChannelMask;
8176 return firstInexact;
8177 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8178 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8179 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8180 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8181 flags = AUDIO_INPUT_FLAG_NONE;
8182 } else { // fail
8183 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8184 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8185 samplingRate, format, channelMask, oriFlags);
8186 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008187 }
8188 }
jiabin2fd710d2022-05-02 23:20:22 +00008189
8190 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008191}
8192
Vlad Popa87e0e582024-05-20 18:49:20 -07008193float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8194 VolumeSource volumeSource,
8195 int index,
8196 const DeviceTypeSet &deviceTypes)
8197{
8198 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8199 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8200 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8201
8202 if (com_android_media_audio_abs_volume_index_fix()) {
8203 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8204 mAbsoluteVolumeDrivingStreams.end()) {
8205 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8206 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8207 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8208 ALOGD("%s: no group matching with %s", __FUNCTION__,
8209 toString(attributesToDriveAbs).c_str());
8210 return volumeDb;
8211 }
8212
8213 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8214 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8215 if (vsToDriveAbs == volumeSource) {
8216 // attenuation is applied by the abs volume controller
Eric Laurent64e868f2024-06-28 16:42:49 +00008217 return (index != 0) ? volumeDbMax : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008218 } else {
8219 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8220 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8221 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8222 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8223 curvesAbs.getVolumeIndexMax());
8224 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8225 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8226 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8227 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8228 return newVolumeDb;
8229 }
8230 }
8231 return volumeDb;
8232 } else {
8233 return volumeDb;
8234 }
8235}
8236
François Gaffieaaac0fd2018-11-22 17:56:39 +01008237float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8238 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008239 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008240 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008241 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008242 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008243{
Vlad Popa9d482762024-06-21 16:40:23 -07008244 float volumeDb;
8245 if (adjustAttenuation) {
8246 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8247 } else {
8248 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8249 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008250 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8251 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8252
8253 if (!computeInternalInteraction) {
8254 return volumeDb;
8255 }
8256
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008257 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8258 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8259 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8260 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008261 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8262 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8263 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8264 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8265 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008266 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008267 mOutputs.isActive(ringVolumeSrc, 0)) {
8268 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008269 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008270 adjustAttenuation,
8271 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008272 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008273 }
8274
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008275 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008276 if ((volumeSource != callVolumeSrc && (isInCall() ||
8277 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008278 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008279 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8280 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008281 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8282 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8283 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008284 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008285 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008286 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008287 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008288 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008289 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008290 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008291 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8292 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8293 // programmatically muted.
8294 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8295 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8296 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008297 bool exemptFromCapping =
8298 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8299 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008300 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8301 volumeSource, volumeDb);
8302 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008303 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8304 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8305 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008306 }
8307 }
Eric Laurente552edb2014-03-10 17:42:56 -07008308 // if a headset is connected, apply the following rules to ring tones and notifications
8309 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008310 // - always attenuate notifications volume by 6dB
8311 // - attenuate ring tones volume by 6dB unless music is not playing and
8312 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008313 // - if music is playing, always limit the volume to current music volume,
8314 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008315 if (!Intersection(deviceTypes,
8316 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8317 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008318 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8319 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008320 ((volumeSource == alarmVolumeSrc ||
8321 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008322 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8323 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8324 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008325 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8326 curves.canBeMuted()) {
8327
Eric Laurente552edb2014-03-10 17:42:56 -07008328 // when the phone is ringing we must consider that music could have been paused just before
8329 // by the music application and behave as if music was active if the last music track was
8330 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008331 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8332 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008333 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008334 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008335 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8336 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008337 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008338 float musicVolDb = computeVolume(musicCurves,
8339 musicVolumeSrc,
8340 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008341 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008342 adjustAttenuation,
8343 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008344 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8345 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8346 if (volumeDb > minVolDb) {
8347 volumeDb = minVolDb;
8348 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008349 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008350 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8351 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008352 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8353 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8354 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8355 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008356 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008357 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008358 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8359 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008360 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8361 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008362 }
8363 }
jiabin9a3361e2019-10-01 09:38:30 -07008364 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008365 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008366 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008367 }
8368 }
8369
François Gaffie43c73442018-11-08 08:21:55 +01008370 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008371}
8372
Eric Laurent3839bc02018-07-10 18:33:34 -07008373int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008374 VolumeSource fromVolumeSource,
8375 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008376{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008377 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008378 return srcIndex;
8379 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008380 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8381 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008382 float minSrc = (float)srcCurves.getVolumeIndexMin();
8383 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8384 float minDst = (float)dstCurves.getVolumeIndexMin();
8385 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008386
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008387 // preserve mute request or correct range
8388 if (srcIndex < minSrc) {
8389 if (srcIndex == 0) {
8390 return 0;
8391 }
8392 srcIndex = minSrc;
8393 } else if (srcIndex > maxSrc) {
8394 srcIndex = maxSrc;
8395 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008396 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8397}
8398
François Gaffieaaac0fd2018-11-22 17:56:39 +01008399status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8400 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008401 int index,
8402 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008403 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008404 int delayMs,
8405 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008406{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008407 // do not change actual attributes volume if the attributes is muted
8408 if (outputDesc->isMuted(volumeSource)) {
8409 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8410 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008411 return NO_ERROR;
8412 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008413
Eric Laurentae6e88c2024-01-10 14:42:57 +01008414 bool isVoiceVolSrc;
8415 bool isBtScoVolSrc;
8416 if (!isVolumeConsistentForCalls(
8417 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008418 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008419 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008420 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008421 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008422
jiabin9a3361e2019-10-01 09:38:30 -07008423 if (deviceTypes.empty()) {
8424 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008425 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008426 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008427 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008428 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008429
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008430 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8431 ALOGE("invalid volume index range");
8432 return BAD_VALUE;
8433 }
8434
jiabin9a3361e2019-10-01 09:38:30 -07008435 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8436 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008437 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008438 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008439 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8440 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008441 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008442 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008443 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008444 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8445 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008446
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008447 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008448 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8449 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8450 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008451 }
Eric Laurente552edb2014-03-10 17:42:56 -07008452 return NO_ERROR;
8453}
8454
Eric Laurentae6e88c2024-01-10 14:42:57 +01008455void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008456 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008457 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008458 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008459 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008460 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008461 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8462 } else {
8463 voiceVolume = index == 0 ? 0.0 : 1.0;
8464 }
8465 if (voiceVolume != mLastVoiceVolume) {
8466 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8467 mLastVoiceVolume = voiceVolume;
8468 }
8469}
8470
8471bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8472 const DeviceTypeSet& deviceTypes,
8473 bool& isVoiceVolSrc,
8474 bool& isBtScoVolSrc,
8475 const char* caller) {
8476 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8477 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8478 const bool isScoRequested = isScoRequestedForComm();
8479 const bool isHAUsed = isHearingAidUsedForComm();
8480
8481 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8482 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8483
8484 if ((callVolSrc != btScoVolSrc) &&
8485 ((isVoiceVolSrc && isScoRequested) ||
8486 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8487 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8488 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8489 volumeSource, isScoRequested ? " " : " not ");
8490 return false;
8491 }
8492 return true;
8493}
8494
Eric Laurentc75307b2015-03-17 15:29:32 -07008495void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008496 const DeviceTypeSet& deviceTypes,
8497 int delayMs,
8498 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008499{
jiabincd510522020-01-22 09:40:55 -08008500 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008501 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8502 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8503 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008504 curves.getVolumeIndex(deviceTypes),
8505 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008506 }
8507}
8508
François Gaffiec005e562018-11-06 15:04:49 +01008509void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8510 bool on,
8511 const sp<AudioOutputDescriptor>& outputDesc,
8512 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008513 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008514{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008515 std::vector<VolumeSource> sourcesToMute;
8516 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8517 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8518 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008519 VolumeSource source = toVolumeSource(attributes, false);
8520 if ((source != VOLUME_SOURCE_NONE) &&
8521 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8522 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008523 sourcesToMute.push_back(source);
8524 }
Eric Laurente552edb2014-03-10 17:42:56 -07008525 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008526 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008527 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008528 }
8529
Eric Laurente552edb2014-03-10 17:42:56 -07008530}
8531
François Gaffieaaac0fd2018-11-22 17:56:39 +01008532void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8533 bool on,
8534 const sp<AudioOutputDescriptor>& outputDesc,
8535 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008536 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008537{
jiabin9a3361e2019-10-01 09:38:30 -07008538 if (deviceTypes.empty()) {
8539 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008540 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008541 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008542 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008543 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008544 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008545 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008546 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8547 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008548 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008549 }
8550 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008551 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8552 // ignored
8553 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008554 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008555 if (!outputDesc->isMuted(volumeSource)) {
8556 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008557 return;
8558 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008559 if (outputDesc->decMuteCount(volumeSource) == 0) {
8560 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008561 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008562 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008563 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008564 delayMs);
8565 }
8566 }
8567}
8568
François Gaffie53615e22015-03-19 09:24:12 +01008569bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8570{
François Gaffiec005e562018-11-06 15:04:49 +01008571 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008572 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8573 return true;
8574 }
8575
8576 // has known usage?
8577 switch (paa->usage) {
8578 case AUDIO_USAGE_UNKNOWN:
8579 case AUDIO_USAGE_MEDIA:
8580 case AUDIO_USAGE_VOICE_COMMUNICATION:
8581 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8582 case AUDIO_USAGE_ALARM:
8583 case AUDIO_USAGE_NOTIFICATION:
8584 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8585 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8586 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8587 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8588 case AUDIO_USAGE_NOTIFICATION_EVENT:
8589 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8590 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8591 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8592 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008593 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008594 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008595 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008596 case AUDIO_USAGE_EMERGENCY:
8597 case AUDIO_USAGE_SAFETY:
8598 case AUDIO_USAGE_VEHICLE_STATUS:
8599 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008600 break;
8601 default:
8602 return false;
8603 }
8604 return true;
8605}
8606
François Gaffie2110e042015-03-24 08:41:51 +01008607audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8608{
8609 return mEngine->getForceUse(usage);
8610}
8611
Eric Laurent96d1dda2022-03-14 17:14:19 +01008612bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008613 return isStateInCall(mEngine->getPhoneState());
8614}
8615
Eric Laurent96d1dda2022-03-14 17:14:19 +01008616bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008617 return is_state_in_call(state);
8618}
8619
Eric Laurentf9cccec2022-11-16 19:12:00 +01008620bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008621 audio_mode_t mode = mEngine->getPhoneState();
8622 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008623 || (mode == AUDIO_MODE_CALL_SCREEN)
8624 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008625}
8626
Eric Laurentf9cccec2022-11-16 19:12:00 +01008627bool AudioPolicyManager::isInCallOrScreening() const {
8628 audio_mode_t mode = mEngine->getPhoneState();
8629 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8630}
8631
Eric Laurentd60560a2015-04-10 11:31:20 -07008632void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8633{
8634 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008635 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008636 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008637 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008638 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008639 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008640 }
8641 }
8642
8643 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8644 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8645 bool release = false;
8646 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8647 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8648 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8649 source->ext.device.type == deviceDesc->type()) {
8650 release = true;
8651 }
8652 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008653 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008654 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8655 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8656 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008657 sink->ext.device.type == deviceDesc->type() &&
8658 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8659 || strncmp(sink->ext.device.address, address,
8660 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008661 release = true;
8662 }
8663 }
8664 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008665 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8666 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008667 }
8668 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008669
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008670 mInputs.clearSessionRoutesForDevice(deviceDesc);
8671
Francois Gaffie716e1432019-01-14 16:58:59 +01008672 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008673}
8674
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008675void AudioPolicyManager::modifySurroundFormats(
8676 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008677 std::unordered_set<audio_format_t> enforcedSurround(
8678 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008679 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008680 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008681 allSurround.insert(pair.first);
8682 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8683 }
Phil Burk09bc4612016-02-24 15:58:15 -08008684
8685 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8686 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008687 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008688 // This is the resulting set of formats depending on the surround mode:
8689 // 'all surround' = allSurround
8690 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8691 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8692 // 'manual surround' = mManualSurroundFormats
8693 // AUTO: formats v 'enforced surround'
8694 // ALWAYS: formats v 'all surround' v 'enforced surround'
8695 // NEVER: formats ^ 'non-surround'
8696 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008697
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008698 std::unordered_set<audio_format_t> formatSet;
8699 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8700 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008701 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008702 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008703 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008704 formatSet.insert(*formatIter);
8705 }
8706 }
8707 } else {
8708 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8709 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008710 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008711
jiabin81772902018-04-02 17:52:27 -07008712 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008713 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008714 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8715 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8716 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008717 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008718 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8719 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8720 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008721 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008722 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008723 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008724 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008725 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008726 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008727}
8728
jiabin06e4bab2019-07-29 10:13:34 -07008729void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8730 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008731 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8732 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8733
8734 // If NEVER, then remove support for channelMasks > stereo.
8735 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008736 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8737 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008738 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008739 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008740 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008741 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008742 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008743 }
8744 }
jiabin81772902018-04-02 17:52:27 -07008745 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8746 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8747 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008748 bool supports5dot1 = false;
8749 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008750 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008751 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8752 supports5dot1 = true;
8753 break;
8754 }
8755 }
8756 // If not then add 5.1 support.
8757 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008758 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008759 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008760 }
Phil Burk09bc4612016-02-24 15:58:15 -08008761 }
8762}
8763
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008764void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008765 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008766 const sp<IOProfile>& profile) {
8767 if (!profile->hasDynamicAudioProfile()) {
8768 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008769 }
François Gaffie112b0af2015-11-19 16:13:25 +01008770
jiabin12537fc2023-10-12 17:56:08 +00008771 audio_port_v7 devicePort;
8772 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008773
jiabin12537fc2023-10-12 17:56:08 +00008774 audio_port_v7 mixPort;
8775 profile->toAudioPort(&mixPort);
8776 mixPort.ext.mix.handle = ioHandle;
8777
8778 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8779 if (status != NO_ERROR) {
8780 ALOGE("%s failed to query the attributes of the mix port", __func__);
8781 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008782 }
jiabin12537fc2023-10-12 17:56:08 +00008783
8784 std::set<audio_format_t> supportedFormats;
8785 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8786 supportedFormats.insert(mixPort.audio_profiles[i].format);
8787 }
8788 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8789 mReportedFormatsMap[devDesc] = formats;
8790
8791 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8792 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8793 modifySurroundFormats(devDesc, &formats);
8794 size_t modifiedNumProfiles = 0;
8795 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8796 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8797 formats.end()) {
8798 // Skip the format that is not present after modifying surround formats.
8799 continue;
8800 }
8801 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8802 sizeof(struct audio_profile));
8803 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8804 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8805 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8806 modifySurroundChannelMasks(&channels);
8807 std::copy(channels.begin(), channels.end(),
8808 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8809 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8810 }
8811 mixPort.num_audio_profiles = modifiedNumProfiles;
8812 }
8813 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008814}
Eric Laurentd60560a2015-04-10 11:31:20 -07008815
Mikhail Naganovdc769682018-05-04 15:34:08 -07008816status_t AudioPolicyManager::installPatch(const char *caller,
8817 audio_patch_handle_t *patchHandle,
8818 AudioIODescriptorInterface *ioDescriptor,
8819 const struct audio_patch *patch,
8820 int delayMs)
8821{
8822 ssize_t index = mAudioPatches.indexOfKey(
8823 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8824 *patchHandle : ioDescriptor->getPatchHandle());
8825 sp<AudioPatch> patchDesc;
8826 status_t status = installPatch(
8827 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8828 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008829 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008830 }
8831 return status;
8832}
8833
8834status_t AudioPolicyManager::installPatch(const char *caller,
8835 ssize_t index,
8836 audio_patch_handle_t *patchHandle,
8837 const struct audio_patch *patch,
8838 int delayMs,
8839 uid_t uid,
8840 sp<AudioPatch> *patchDescPtr)
8841{
8842 sp<AudioPatch> patchDesc;
8843 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8844 if (index >= 0) {
8845 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008846 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008847 }
8848
8849 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8850 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8851 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8852 if (status == NO_ERROR) {
8853 if (index < 0) {
8854 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008855 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008856 } else {
8857 patchDesc->mPatch = *patch;
8858 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008859 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008860 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008861 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008862 }
8863 nextAudioPortGeneration();
8864 mpClientInterface->onAudioPatchListUpdate();
8865 }
8866 if (patchDescPtr) *patchDescPtr = patchDesc;
8867 return status;
8868}
8869
jiabinbce0c1d2020-10-05 11:20:18 -07008870bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8871{
8872 const TrackClientVector activeClients = output->getActiveClients();
8873 if (activeClients.empty()) {
8874 return true;
8875 }
8876 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8877 if (index < 0) {
8878 ALOGE("%s, no audio patch found while there are active clients on output %d",
8879 __func__, output->getId());
8880 return false;
8881 }
8882 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8883 DeviceVector routedDevices;
8884 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8885 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8886 patchDesc->mPatch.sinks[i].id);
8887 if (device == nullptr) {
8888 ALOGE("%s, no audio device found with id(%d)",
8889 __func__, patchDesc->mPatch.sinks[i].id);
8890 return false;
8891 }
8892 routedDevices.add(device);
8893 }
8894 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008895 if (client->isInvalid()) {
8896 // No need to take care about invalidated clients.
8897 continue;
8898 }
jiabinbce0c1d2020-10-05 11:20:18 -07008899 sp<DeviceDescriptor> preferredDevice =
8900 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8901 if (mEngine->getOutputDevicesForAttributes(
8902 client->attributes(), preferredDevice, false) == routedDevices) {
8903 return false;
8904 }
8905 }
8906 return true;
8907}
8908
8909sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008910 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008911 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8912 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008913{
8914 for (const auto& device : devices) {
8915 // TODO: This should be checking if the profile supports the device combo.
8916 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008917 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8918 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008919 return nullptr;
8920 }
8921 }
8922 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8923 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008924 status_t status = desc->open(halConfig, mixerConfig, devices,
8925 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008926 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008927 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008928 return nullptr;
8929 }
jiabin14b50cc2023-12-13 19:01:52 +00008930 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8931 auto portConfig = desc->getConfig();
8932 for (const auto& device : devices) {
8933 device->setPreferredConfig(&portConfig);
8934 }
8935 }
jiabinbce0c1d2020-10-05 11:20:18 -07008936
8937 // Here is where the out_set_parameters() for card & device gets called
8938 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8939 const audio_devices_t deviceType = device->type();
8940 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008941 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008942 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8943 mpClientInterface->setParameters(output, String8(param));
8944 free(param);
8945 }
jiabin12537fc2023-10-12 17:56:08 +00008946 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008947 if (!profile->hasValidAudioProfile()) {
8948 ALOGW("%s() missing param", __func__);
8949 desc->close();
8950 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008951 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8952 // Reopen the output with the best audio profile picked by APM when the profile supports
8953 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008954 desc->close();
8955 output = AUDIO_IO_HANDLE_NONE;
8956 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8957 profile->pickAudioProfile(
8958 config.sample_rate, config.channel_mask, config.format);
8959 config.offload_info.sample_rate = config.sample_rate;
8960 config.offload_info.channel_mask = config.channel_mask;
8961 config.offload_info.format = config.format;
8962
jiabina84c3d32022-12-02 18:59:55 +00008963 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008964 if (status != NO_ERROR) {
8965 return nullptr;
8966 }
8967 }
8968
8969 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008970 setOutputDevices(__func__, desc,
8971 devices,
8972 true,
8973 0,
8974 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008975 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8976 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8977
jiabinbce0c1d2020-10-05 11:20:18 -07008978 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8979 sp<AudioPolicyMix> policyMix;
8980 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8981 policyMix->setOutput(desc);
8982 desc->mPolicyMix = policyMix;
8983 } else {
8984 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008985 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008986 }
8987
baek.kim -61c20122022-07-27 10:05:32 +00008988 } else if (hasPrimaryOutput() && speaker != nullptr
8989 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008990 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8991 // no duplicated output for:
8992 // - direct outputs
8993 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008994 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008995 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8996
8997 //TODO: configure audio effect output stage here
8998
8999 // open a duplicating output thread for the new output and the primary output
9000 sp<SwAudioOutputDescriptor> dupOutputDesc =
9001 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9002 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9003 if (status == NO_ERROR) {
9004 // add duplicated output descriptor
9005 addOutput(duplicatedOutput, dupOutputDesc);
9006 } else {
9007 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9008 mPrimaryOutput->mIoHandle, output);
9009 desc->close();
9010 removeOutput(output);
9011 nextAudioPortGeneration();
9012 return nullptr;
9013 }
9014 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009015 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9016 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9017 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009018 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009019 }
jiabinbce0c1d2020-10-05 11:20:18 -07009020 return desc;
9021}
9022
jiabinf1c73972022-04-14 16:28:52 -07009023status_t AudioPolicyManager::getDevicesForAttributes(
9024 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
9025 // Devices are determined in the following precedence:
9026 //
9027 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9028 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9029 //
9030 // If no such dynamic policy then
9031 // 2) Devices containing an active client using setPreferredDevice
9032 // with same strategy as the attributes.
9033 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9034 //
9035 // If no corresponding active client with setPreferredDevice then
9036 // 3) Devices associated with the strategy determined by the attributes
9037 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9038 //
9039 // See related getOutputForAttrInt().
9040
9041 // check dynamic policies but only for primary descriptors (secondary not used for audible
9042 // audio routing, only used for duplication for playback capture)
9043 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009044 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009045 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009046 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9047 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9048 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009049 if (status != OK) {
9050 return status;
9051 }
9052
9053 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9054 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9055 // as they are unaffected by device/stream volume
9056 // (per SwAudioOutputDescriptor::isFixedVolume()).
9057 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9058 ) {
9059 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9060 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9061 devices.add(deviceDesc);
9062 } else {
9063 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9064 // which selects setPreferredDevice if active. This means forVolume call
9065 // will take an active setPreferredDevice, if such exists.
9066
9067 devices = mEngine->getOutputDevicesForAttributes(
9068 attr, nullptr /* preferredDevice */, false /* fromCache */);
9069 }
9070
9071 if (forVolume) {
9072 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9073 // for single volume control in AudioService (such relationship should exist if
9074 // SPEAKER_SAFE is present).
9075 //
9076 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9077 DeviceVector speakerSafeDevices =
9078 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9079 if (!speakerSafeDevices.isEmpty()) {
9080 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9081 devices.remove(speakerSafeDevices);
9082 }
9083 }
9084
9085 return NO_ERROR;
9086}
9087
9088status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9089 AudioProfileVector& audioProfiles,
9090 uint32_t flags,
9091 bool isInput) {
9092 for (const auto& hwModule : mHwModules) {
9093 // the MSD module checks for different conditions
9094 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9095 continue;
9096 }
9097 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9098 : hwModule->getOutputProfiles();
9099 for (const auto& profile : ioProfiles) {
9100 if (!profile->areAllDevicesSupported(devices) ||
9101 !profile->isCompatibleProfileForFlags(
9102 flags, false /*exactMatchRequiredForInputFlags*/)) {
9103 continue;
9104 }
9105 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9106 }
9107 }
9108
9109 if (!isInput) {
9110 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9111 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9112 if (msdModule != nullptr) {
9113 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9114 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9115 for (const auto &profile: msdModule->getOutputProfiles()) {
9116 if (!profile->asAudioPort()->isDirectOutput()) {
9117 continue;
9118 }
9119 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9120 }
9121 } else {
9122 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9123 }
9124 }
9125 }
9126
9127 return NO_ERROR;
9128}
9129
jiabin3ff8d7d2022-12-13 06:27:44 +00009130sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9131 const audio_config_t *config,
9132 audio_output_flags_t flags,
9133 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009134 closeOutput(outputDesc->mIoHandle);
9135 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9136 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9137 if (preferredOutput == nullptr) {
9138 ALOGE("%s failed to reopen output device=%d, caller=%s",
9139 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009140 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009141 return preferredOutput;
9142}
9143
9144void AudioPolicyManager::reopenOutputsWithDevices(
9145 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9146 for (const auto& [output, devices] : outputsToReopen) {
9147 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9148 closeOutput(output);
9149 openOutputWithProfileAndDevice(desc->mProfile, devices);
9150 }
jiabina84c3d32022-12-02 18:59:55 +00009151}
9152
jiabinc44b3462022-12-08 12:52:31 -08009153PortHandleVector AudioPolicyManager::getClientsForStream(
9154 audio_stream_type_t streamType) const {
9155 PortHandleVector clients;
9156 for (size_t i = 0; i < mOutputs.size(); ++i) {
9157 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9158 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9159 }
9160 return clients;
9161}
9162
9163void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9164 PortHandleVector clients;
9165 for (auto stream : streams) {
9166 PortHandleVector clientsForStream = getClientsForStream(stream);
9167 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9168 }
9169 mpClientInterface->invalidateTracks(clients);
9170}
9171
jiabin220eea12024-05-17 17:55:20 +00009172void AudioPolicyManager::updateClientsInternalMute(
9173 const sp<android::SwAudioOutputDescriptor> &desc) {
9174 if (!desc->isBitPerfect() ||
9175 !com::android::media::audioserver::
9176 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9177 // This is only used for bit perfect output now.
9178 return;
9179 }
9180 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9181 bool bitPerfectClientInternalMute = false;
9182 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9183 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9184 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9185 bitPerfectClient = client;
9186 continue;
9187 }
9188 bool muted = false;
9189 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9190 // System sound is muted.
9191 muted = true;
9192 } else {
9193 bitPerfectClientInternalMute = true;
9194 }
9195 if (client->setInternalMute(muted)) {
9196 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9197 if (!result.ok()) {
9198 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9199 continue;
9200 }
9201 media::TrackInternalMuteInfo info;
9202 info.portId = result.value();
9203 info.muted = client->getInternalMute();
9204 clientsInternalMute.push_back(std::move(info));
9205 }
9206 }
9207 if (bitPerfectClient != nullptr &&
9208 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9209 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9210 if (result.ok()) {
9211 media::TrackInternalMuteInfo info;
9212 info.portId = result.value();
9213 info.muted = bitPerfectClient->getInternalMute();
9214 clientsInternalMute.push_back(std::move(info));
9215 } else {
9216 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9217 __func__, bitPerfectClient->portId());
9218 }
9219 }
9220 if (!clientsInternalMute.empty()) {
9221 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9222 status != NO_ERROR) {
9223 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9224 }
9225 }
9226}
9227
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009228} // namespace android