blob: b61d3ec496aca6d04703f8fc8fbaace4074af46f [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>
Jiabin Huangaa6e9e32024-10-21 17:19:28 +000043#include <android/media/audio/common/AudioMMapPolicy.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010044#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080045#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010046#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080047#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070048#include <cutils/bitops.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"
Shunkai Yao2dcd60c2024-08-27 21:08:53 +000058#include "SpatializerHelper.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010059#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070060
Eric Laurent3b73df72014-03-11 09:06:29 -070061namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070062
Marvin Raminbdefaf02023-11-01 09:10:32 +010063
64namespace audio_flags = android::media::audiopolicy;
65
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010066using android::media::audio::common::AudioDevice;
67using android::media::audio::common::AudioDeviceAddress;
Jiabin Huangaa6e9e32024-10-21 17:19:28 +000068using android::media::audio::common::AudioDeviceDescription;
69using android::media::audio::common::AudioMMapPolicy;
70using android::media::audio::common::AudioMMapPolicyInfo;
71using android::media::audio::common::AudioMMapPolicyType;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010072using android::media::audio::common::AudioPortDeviceExt;
73using android::media::audio::common::AudioPortExt;
Eric Laurentb2fb4102024-06-21 12:25:26 +000074using com::android::media::audioserver::fix_call_audio_patch;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000075using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070076
Eric Laurentdc462862016-07-19 12:29:53 -070077//FIXME: workaround for truncated touch sounds
78// to be removed when the problem is handled by system UI
79#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070080
81// Largest difference in dB on earpiece in call between the voice volume and another
82// media / notification / system volume.
83constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
84
jiabin06e4bab2019-07-29 10:13:34 -070085template <typename T>
86bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
87{
88 if (left.size() != right.size()) {
89 return false;
90 }
91 for (size_t index = 0; index < right.size(); index++) {
92 if (left[index] != right[index]) {
93 return false;
94 }
95 }
96 return true;
97}
98
99template <typename T>
100bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
101{
102 return !(left == right);
103}
104
Eric Laurente552edb2014-03-10 17:42:56 -0700105// ----------------------------------------------------------------------------
106// AudioPolicyInterface implementation
107// ----------------------------------------------------------------------------
108
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100109status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
110 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
111 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800112 nextAudioPortGeneration();
113 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800114}
115
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
117 audio_policy_dev_state_t state,
118 const char* device_address,
119 const char* device_name,
120 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800121 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100122 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
123 status == OK) {
124 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
125 } else {
126 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
127 return status;
128 }
129}
130
Ping Tsai2a5a5242024-08-16 13:39:10 +0800131status_t AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000132 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200133{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000134 audio_port_v7 devicePort;
135 device->toAudioPort(&devicePort);
Ping Tsai2a5a5242024-08-16 13:39:10 +0800136 status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
137 ALOGE_IF(status != OK, "Error %d while setting connected state %d for device %s", status,
138 static_cast<int>(state), device->getDeviceTypeAddr().toString(false).c_str());
139
140 return status;
François Gaffie44481e72016-04-20 07:49:57 +0200141}
142
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100143status_t AudioPolicyManager::setDeviceConnectionStateInt(
144 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
145 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100146 if (port.ext.getTag() != AudioPortExt::device) {
147 return BAD_VALUE;
148 }
149 audio_devices_t device_type;
150 std::string device_address;
151 if (status_t status = aidl2legacy_AudioDevice_audio_device(
152 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
153 status != OK) {
154 return status;
155 };
156 const char* device_name = port.name.c_str();
157 // connect/disconnect only 1 device at a time
158 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
159 return BAD_VALUE;
160
161 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
162 device_type, device_address.c_str(), device_name, encodedFormat,
163 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000164 if (device == nullptr) {
165 return INVALID_OPERATION;
166 }
167 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
168 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
169 }
170 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100171}
172
François Gaffie11d30102018-11-02 16:09:09 +0100173status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800174 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100175 const char* device_address,
176 const char* device_name,
177 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800178 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100179 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
180 status == OK) {
181 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
182 } else {
183 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
184 return status;
185 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700186}
Paul McLeane743a472015-01-28 11:07:31 -0800187
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700188status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
189 audio_policy_dev_state_t state)
190{
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700192 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700193 SortedVector <audio_io_handle_t> outputs;
194
François Gaffie11d30102018-11-02 16:09:09 +0100195 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700196
Eric Laurente552edb2014-03-10 17:42:56 -0700197 // save a copy of the opened output descriptors before any output is opened or closed
198 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
199 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100200
201 bool wasLeUnicastActive = isLeUnicastActive();
202
Eric Laurente552edb2014-03-10 17:42:56 -0700203 switch (state)
204 {
205 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800206 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700207 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100208 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700209 return INVALID_OPERATION;
210 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800211 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700212 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700213
Eric Laurente552edb2014-03-10 17:42:56 -0700214 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200215 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700216 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700217 }
218
François Gaffie44481e72016-04-20 07:49:57 +0200219 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
220 // parameters on newly connected devices (instead of opening the outputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800221 if (broadcastDeviceConnectionState(
222 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
223 mAvailableOutputDevices.remove(device);
224 mHwModules.cleanUpForDevice(device);
225 ALOGE("%s() device %s format %x connection failed", __func__,
226 device->toString().c_str(), device->getEncodedFormat());
227 return INVALID_OPERATION;
228 }
François Gaffie44481e72016-04-20 07:49:57 +0200229
François Gaffie11d30102018-11-02 16:09:09 +0100230 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
231 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200232
jiabinc0048632023-04-27 22:04:31 +0000233 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700234
235 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700236 return INVALID_OPERATION;
237 }
François Gaffie2110e042015-03-24 08:41:51 +0100238
jiabin1c4794b2020-05-05 10:08:05 -0700239 // Populate encapsulation information when a output device is connected.
240 device->setEncapsulationInfoFromHal(mpClientInterface);
241
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700242 // outputs should never be empty here
243 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
244 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100245 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800246
Eric Laurent3ae5f312015-02-03 17:12:08 -0800247 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700248 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700249 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700250 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100251 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700252 return INVALID_OPERATION;
253 }
254
François Gaffie11d30102018-11-02 16:09:09 +0100255 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700256
jiabinc0048632023-04-27 22:04:31 +0000257 // Notify the HAL to prepare to disconnect device
258 broadcastDeviceConnectionState(
259 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700260
Eric Laurente552edb2014-03-10 17:42:56 -0700261 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100262 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700263
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100264 mOutputs.clearSessionRoutesForDevice(device);
265
François Gaffie11d30102018-11-02 16:09:09 +0100266 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100267
jiabinc0048632023-04-27 22:04:31 +0000268 // Send Disconnect to HALs
269 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
270
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800271 // Reset active device codec
272 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
273
Kriti Dangef6be8f2020-11-05 11:58:19 +0100274 // remove device from mReportedFormatsMap cache
275 mReportedFormatsMap.erase(device);
276
jiabina84c3d32022-12-02 18:59:55 +0000277 // remove preferred mixer configurations
278 mPreferredMixerAttrInfos.erase(device->getId());
279
Eric Laurente552edb2014-03-10 17:42:56 -0700280 } break;
281
282 default:
François Gaffie11d30102018-11-02 16:09:09 +0100283 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700284 return BAD_VALUE;
285 }
286
Eric Laurent736a1022019-03-27 18:28:46 -0700287 // Propagate device availability to Engine
288 setEngineDeviceConnectionState(device, state);
289
Eric Laurentae970022019-01-29 14:25:04 -0800290 // No need to evaluate playback routing when connecting a remote submix
291 // output device used by a dynamic policy of type recorder as no
292 // playback use case is affected.
293 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700294 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800295 for (audio_io_handle_t output : outputs) {
296 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800297 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
298 if (policyMix != nullptr
299 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000300 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800301 doCheckForDeviceAndOutputChanges = false;
302 break;
303 }
304 }
305 }
306
307 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700308 // outputs must be closed after checkOutputForAllStrategies() is executed
309 if (!outputs.isEmpty()) {
310 for (audio_io_handle_t output : outputs) {
311 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100312 // close unused outputs after device disconnection or direct outputs that have
313 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200314 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200315 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
316 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200317 (desc->mDirectOpenCount == 0))
318 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
319 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200320 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700321 closeOutput(output);
322 }
Eric Laurente552edb2014-03-10 17:42:56 -0700323 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700324 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
325 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700326 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700327 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800328 };
329
330 if (doCheckForDeviceAndOutputChanges) {
331 checkForDeviceAndOutputChanges(checkCloseOutputs);
332 } else {
333 checkCloseOutputs();
334 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100335 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100336 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700337 const DeviceVector activeMediaDevices =
338 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000339 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700340 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700341 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530342 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
343 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100344 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700345 // do not force device change on duplicated output because if device is 0, it will
346 // also force a device 0 for the two outputs it is duplicated to which may override
347 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100348 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100349 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700350 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700351 // always force when disconnecting (a non-duplicated device)
352 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000353 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000354 // If the device is using preferred mixer attributes, the output need to reopen
355 // with default configuration when the new selected devices are different from
356 // current routing devices
357 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
358 continue;
359 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530360 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700361 }
jiabinbce0c1d2020-10-05 11:20:18 -0700362 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000363 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700364 desc->supportsDevicesForPlayback(activeMediaDevices)) {
365 // Reopen the output to query the dynamic profiles when there is not active
366 // clients or all active clients will be rerouted. Otherwise, set the flag
367 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
368 // can be reopened to query dynamic profiles when all clients are inactive.
369 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000370 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700371 } else {
372 desc->mPendingReopenToQueryProfiles = true;
373 }
374 }
375 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
376 // Clear the flag that previously set for re-querying profiles.
377 desc->mPendingReopenToQueryProfiles = false;
378 }
379 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000380 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700381
Eric Laurentd60560a2015-04-10 11:31:20 -0700382 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700384 }
385
Eric Laurent96d1dda2022-03-14 17:14:19 +0100386 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
387
Eric Laurent72aa32f2014-05-30 18:51:48 -0700388 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530389 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700390 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700391 } // end if is output device
392
Eric Laurente552edb2014-03-10 17:42:56 -0700393 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700394 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100395 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700396 switch (state)
397 {
398 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700399 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700400 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100401 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700402 return INVALID_OPERATION;
403 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700404
Jaideep Sharma33173202024-06-18 17:46:45 +0530405 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
406
Eric Laurent0dd51852019-04-19 18:18:58 -0700407 if (mAvailableInputDevices.add(device) < 0) {
408 return NO_MEMORY;
409 }
410
François Gaffie44481e72016-04-20 07:49:57 +0200411 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
412 // parameters on newly connected devices (instead of opening the inputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800413 if (broadcastDeviceConnectionState(
414 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
415 mAvailableInputDevices.remove(device);
416 mHwModules.cleanUpForDevice(device);
417 ALOGE("%s() device %s format %x connection failed", __func__,
418 device->toString().c_str(), device->getEncodedFormat());
419 return INVALID_OPERATION;
420 }
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700421 // Propagate device availability to Engine
422 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200423
Eric Laurent0dd51852019-04-19 18:18:58 -0700424 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700425 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
426
Eric Laurent0dd51852019-04-19 18:18:58 -0700427 mAvailableInputDevices.remove(device);
428
jiabinc0048632023-04-27 22:04:31 +0000429 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100430
431 mHwModules.cleanUpForDevice(device);
432
Eric Laurentd4692962014-05-05 18:13:44 -0700433 return INVALID_OPERATION;
434 }
435
Eric Laurentd4692962014-05-05 18:13:44 -0700436 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700437
438 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700439 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700440 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100441 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700442 return INVALID_OPERATION;
443 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700444
François Gaffie11d30102018-11-02 16:09:09 +0100445 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700446
jiabinc0048632023-04-27 22:04:31 +0000447 // Notify the HAL to prepare to disconnect device
448 broadcastDeviceConnectionState(
449 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700450
François Gaffie11d30102018-11-02 16:09:09 +0100451 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700452
453 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100454
jiabinc0048632023-04-27 22:04:31 +0000455 // Set Disconnect to HALs
456 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
457
Kriti Dangef6be8f2020-11-05 11:58:19 +0100458 // remove device from mReportedFormatsMap cache
459 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700460
461 // Propagate device availability to Engine
462 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700463 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700464
465 default:
François Gaffie11d30102018-11-02 16:09:09 +0100466 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700467 return BAD_VALUE;
468 }
469
Eric Laurent0dd51852019-04-19 18:18:58 -0700470 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700471 // As the input device list can impact the output device selection, update
472 // getDeviceForStrategy() cache
473 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700474
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100475 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200476 // Reconnect Audio Source
477 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
478 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
479 checkAudioSourceForAttributes(attributes);
480 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700481 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100482 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700483 }
484
Eric Laurentb52c1522014-05-20 11:27:36 -0700485 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530486 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700487 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700488 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700489
François Gaffie11d30102018-11-02 16:09:09 +0100490 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700491 return BAD_VALUE;
492}
493
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100494status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
495 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800496 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700497 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
498 devDescr->setName(device_name);
499 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100500}
501
Eric Laurent736a1022019-03-27 18:28:46 -0700502void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
503 audio_policy_dev_state_t state) {
504
505 // the Engine does not have to know about remote submix devices used by dynamic audio policies
506 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
507 return;
508 }
509 mEngine->setDeviceConnectionState(device, state);
510}
511
512
Eric Laurente0720872014-03-11 09:30:41 -0700513audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100514 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700515{
Eric Laurent634b7142016-04-20 13:48:02 -0700516 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
518 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700519 (strlen(device_address) != 0)/*matchAddress*/);
520
521 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100522 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700523 device, device_address);
524 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
525 }
François Gaffie53615e22015-03-19 09:24:12 +0100526
Eric Laurent3a4311c2014-03-17 12:00:47 -0700527 DeviceVector *deviceVector;
528
Eric Laurente552edb2014-03-10 17:42:56 -0700529 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700530 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700531 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700532 deviceVector = &mAvailableInputDevices;
533 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100534 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700535 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700536 }
Eric Laurent634b7142016-04-20 13:48:02 -0700537
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800538 return (deviceVector->getDevice(
539 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700540 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800541}
542
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800543status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
544 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800545 const char *device_name,
546 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800547{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800548 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
549 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800550
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800551 // connect/disconnect only 1 device at a time
552 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
553
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800554 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700555 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800556 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800557 // Nothing to do: device is not connected
558 return NO_ERROR;
559 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800560 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800561
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700562 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800563 // configure codecs.
564 // Handle two specific cases by sending a set parameter to
565 // configure A2DP codecs. No need to toggle device state.
566 // Case 1: A2DP active device switches from primary to primary
567 // module
568 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100569 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700570 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800571 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
572 if (availablePrimaryOutputDevices().contains(devDesc) &&
573 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100574 bool isA2dp = audio_is_a2dp_out_device(device);
575 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
576 : String8(AudioParameter::keyReconfigLeSupported);
577 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800578 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100579 int isReconfigSupported;
580 repliedParameters.getInt(supportKey, isReconfigSupported);
581 if (isReconfigSupported) {
582 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
583 : String8(AudioParameter::keyReconfigLe);
584 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800585 param.add(key, String8("true"));
586 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
587 devDesc->setEncodedFormat(encodedFormat);
588 return NO_ERROR;
589 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700590 }
591 }
cnx421bd2dcc42020-07-11 14:58:44 +0800592 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000593 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800594 for (size_t i = 0; i < mOutputs.size(); i++) {
595 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000596 // mute media strategies to avoid sending the music tail into
597 // the earpiece or headset.
598 if (desc->isStrategyActive(musicStrategy)) {
599 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
600 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
601 tempRecommendedMuteDuration : desc->latency() * 4;
602 if (muteWaitMs < tempMuteDurationMs) {
603 muteWaitMs = tempMuteDurationMs;
604 }
605 }
cnx421bd2dcc42020-07-11 14:58:44 +0800606 setStrategyMute(musicStrategy, true, desc);
607 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
608 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
609 nullptr, true /*fromCache*/).types());
610 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000611 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
612 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
613 // happens after the actual device switch.
614 if (muteWaitMs > 0) {
615 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
616 usleep(muteWaitMs * 1000);
617 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800618 // Toggle the device state: UNAVAILABLE -> AVAILABLE
619 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100620 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800621 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800622 device_address, device_name,
623 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800624 if (status != NO_ERROR) {
625 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
626 status);
627 return status;
628 }
629
630 status = setDeviceConnectionState(device,
631 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800632 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800633 if (status != NO_ERROR) {
634 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
635 status);
636 return status;
637 }
638
639 return NO_ERROR;
640}
641
Pattydd807582021-11-04 21:01:03 +0800642status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
643 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800644{
Pattydd807582021-11-04 21:01:03 +0800645 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800646 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800647 std::unordered_set<audio_format_t> formatSet;
648 sp<HwModule> primaryModule =
649 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700650 if (primaryModule == nullptr) {
651 ALOGE("%s() unable to get primary module", __func__);
652 return NO_INIT;
653 }
Pattydd807582021-11-04 21:01:03 +0800654
655 DeviceTypeSet audioDeviceSet;
656
657 switch(device) {
658 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
659 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
660 break;
661 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800662 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
663 break;
664 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
665 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800666 break;
667 default:
668 ALOGE("%s() device type 0x%08x not supported", __func__, device);
669 return BAD_VALUE;
670 }
671
jiabin9a3361e2019-10-01 09:38:30 -0700672 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800673 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800674 for (const auto& device : declaredDevices) {
675 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800676 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800677 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800678 return status;
679}
680
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100681DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
682{
683 DeviceVector rxSinkdevices{};
684 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
685 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
686 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
687 auto rxSinkDevice = rxSinkdevices.itemAt(0);
688 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
689 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
690 // retrieve Rx Source device descriptor
691 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
692 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
693
694 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
695 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
696 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
697 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
698 return DeviceVector(rxSinkDevice);
699 }
700 }
701 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
702 // the device returned is not necessarily reachable via this output
703 // (filter later by setOutputDevices())
704 return getNewOutputDevices(mPrimaryOutput, fromCache);
705}
706
707status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
708{
François Gaffiedb1755b2023-09-01 11:50:35 +0200709 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100710 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
711 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
712 }
713 return INVALID_OPERATION;
714}
715
716status_t AudioPolicyManager::updateCallRoutingInternal(
717 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700718{
719 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100720 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700721 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200722 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700723 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100724 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700725 }
François Gaffie11d30102018-11-02 16:09:09 +0100726
Francois Gaffie716e1432019-01-14 16:58:59 +0100727 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100728 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200729
Eric Laurentb2fb4102024-06-21 12:25:26 +0000730 if (!fix_call_audio_patch()) {
731 disconnectTelephonyAudioSource(mCallRxSourceClient);
732 disconnectTelephonyAudioSource(mCallTxSourceClient);
733 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200734
735 if (rxDevices.isEmpty()) {
736 ALOGW("%s() no selected output device", __func__);
737 return INVALID_OPERATION;
738 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000739 if (txSourceDevice == nullptr) {
740 ALOGE("%s() selected input device not available", __func__);
741 return INVALID_OPERATION;
742 }
François Gaffiec005e562018-11-06 15:04:49 +0100743
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100744 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100745 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700746
François Gaffie9eb18552018-11-05 10:33:26 +0100747 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700748 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100749 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700750 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100751 // retrieve Rx Source and Tx Sink device descriptors
752 sp<DeviceDescriptor> rxSourceDevice =
753 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
754 String8(),
755 AUDIO_FORMAT_DEFAULT);
756 sp<DeviceDescriptor> txSinkDevice =
757 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
758 String8(),
759 AUDIO_FORMAT_DEFAULT);
760
761 // RX and TX Telephony device are declared by Primary Audio HAL
762 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
763 (telephonyRxModule->getHalVersionMajor() >= 3)) {
764 if (rxSourceDevice == 0 || txSinkDevice == 0) {
765 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100766 ALOGE("%s() no telephony Tx and/or RX device", __func__);
767 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100768 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100769 // createAudioPatchInternal now supports both HW / SW bridging
770 createRxPatch = true;
771 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100772 } else {
773 // If the RX device is on the primary HW module, then use legacy routing method for
774 // voice calls via setOutputDevice() on primary output.
775 // Otherwise, create two audio patches for TX and RX path.
776 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
777 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700778 // If the TX device is also on the primary HW module, setOutputDevice() will take care
779 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100780 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
781 (txSinkDevice != 0);
782 }
783 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
784 // Otherwise, create two audio patches for TX and RX path.
785 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000786 if (fix_call_audio_patch()) {
787 disconnectTelephonyAudioSource(mCallRxSourceClient);
788 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200789 if (!hasPrimaryOutput()) {
790 ALOGW("%s() no primary output available", __func__);
791 return INVALID_OPERATION;
792 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530793 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700794 } else { // create RX path audio patch
David Lif85c5e32024-07-01 13:14:10 +0000795 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800796 // If the TX device is on the primary HW module but RX device is
797 // on other HW module, SinkMetaData of telephony input should handle it
798 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700799 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700800 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100801 // terminate active capture if on the same HW module as the call TX source device
802 // FIXME: would be better to refine to only inputs whose profile connects to the
803 // call TX device but this information is not in the audio patch and logic here must be
804 // symmetric to the one in startInput()
805 for (const auto& activeDesc : mInputs.getActiveInputs()) {
806 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
807 closeActiveClients(activeDesc);
808 }
809 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200810 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000811 } else if (fix_call_audio_patch()) {
812 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800813 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100814 if (waitMs != nullptr) {
815 *waitMs = muteWaitMs;
816 }
817 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800818}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700819
Mikhail Naganov100f0122018-11-29 11:22:16 -0800820bool AudioPolicyManager::isDeviceOfModule(
821 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
822 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
823 if (module != 0) {
824 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
825 .indexOf(devDesc) != NAME_NOT_FOUND
826 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
827 .indexOf(devDesc) != NAME_NOT_FOUND;
828 }
829 return false;
830}
831
David Lif85c5e32024-07-01 13:14:10 +0000832void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200833{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000834 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
835
836 if (fix_call_audio_patch()) {
837 if (mCallRxSourceClient != nullptr) {
838 DeviceVector rxDevices =
839 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
840 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
841 "connectTelephonyRxAudioSource(): no device found for call RX source");
842 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
843 if (mCallRxSourceClient->isConnected()
844 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
845 return;
846 }
847 disconnectTelephonyAudioSource(mCallRxSourceClient);
848 }
849 } else {
850 disconnectTelephonyAudioSource(mCallRxSourceClient);
851 }
852
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200853 const struct audio_port_config source = {
854 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
855 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
856 };
Eric Laurent541a2002024-01-15 18:11:42 +0100857 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000858
Eric Laurentccbd7872024-06-20 12:34:15 +0000859 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Lif85c5e32024-07-01 13:14:10 +0000860 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100861 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
862 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000863 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
864 mCallRxSourceClient->srcDevice()->toString().c_str(),
865 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200866 ALOGE_IF(mCallRxSourceClient == nullptr,
867 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200868}
869
Francois Gaffie601801d2021-06-22 13:27:39 +0200870void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200871{
Francois Gaffie601801d2021-06-22 13:27:39 +0200872 if (clientDesc == nullptr) {
873 return;
874 }
875 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
876 "%s error stopping audio source", __func__);
877 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200878}
879
880void AudioPolicyManager::connectTelephonyTxAudioSource(
881 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
882 uint32_t delayMs)
883{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200884 if (srcDevice == nullptr || sinkDevice == nullptr) {
885 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
886 return;
887 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000888
889 if (fix_call_audio_patch()) {
890 if (mCallTxSourceClient != nullptr) {
891 if (mCallTxSourceClient->isConnected()
892 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
893 return;
894 }
895 disconnectTelephonyAudioSource(mCallTxSourceClient);
896 }
897 } else {
898 disconnectTelephonyAudioSource(mCallTxSourceClient);
899 }
900
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200901 PatchBuilder patchBuilder;
902 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000903
Francois Gaffie601801d2021-06-22 13:27:39 +0200904 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200905 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
906
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200907 struct audio_port_config source = {};
908 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100909 mCallTxSourceClient = new SourceClientDescriptor(
910 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000911 mCommunnicationStrategy, toVolumeSource(aa), true,
912 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100913 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
914
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200915 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
916 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200917 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
918 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200919 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000920 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
921 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200922 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200923 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200924 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200925}
926
Eric Laurente0720872014-03-11 09:30:41 -0700927void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700928{
929 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100930 // store previous phone state for management of sonification strategy below
931 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100932 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100933
934 if (mEngine->setPhoneState(state) != NO_ERROR) {
935 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700936 return;
937 }
François Gaffie2110e042015-03-24 08:41:51 +0100938 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700939 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700940 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700941 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800942 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700943 }
944
François Gaffie2110e042015-03-24 08:41:51 +0100945 /**
946 * Switching to or from incall state or switching between telephony and VoIP lead to force
947 * routing command.
948 */
Eric Laurent74b71512019-11-06 17:21:57 -0800949 bool force = ((isStateInCall(oldState) != isStateInCall(state))
950 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700951
952 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700953 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700954
Eric Laurente552edb2014-03-10 17:42:56 -0700955 int delayMs = 0;
956 if (isStateInCall(state)) {
957 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100958 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
959 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700960 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700961 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700962 // mute media and sonification strategies and delay device switch by the largest
963 // latency of any output where either strategy is active.
964 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100965 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
966 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
967 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700968 (delayMs < (int)desc->latency()*2)) {
969 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700970 }
François Gaffiec005e562018-11-06 15:04:49 +0100971 setStrategyMute(musicStrategy, true, desc);
972 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
973 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
974 nullptr, true /*fromCache*/).types());
975 setStrategyMute(sonificationStrategy, true, desc);
976 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
977 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
978 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700979 }
980 }
981
François Gaffiedb1755b2023-09-01 11:50:35 +0200982 if (state == AUDIO_MODE_IN_CALL) {
983 (void)updateCallRouting(false /*fromCache*/, delayMs);
984 } else {
985 if (oldState == AUDIO_MODE_IN_CALL) {
986 disconnectTelephonyAudioSource(mCallRxSourceClient);
987 disconnectTelephonyAudioSource(mCallTxSourceClient);
988 }
989 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100990 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
991 // force routing command to audio hardware when ending call
992 // even if no device change is needed
993 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
994 rxDevices = mPrimaryOutput->devices();
995 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530996 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700997 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700998 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700999
jiabin3ff8d7d2022-12-13 06:27:44 +00001000 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001001 // reevaluate routing on all outputs in case tracks have been started during the call
1002 for (size_t i = 0; i < mOutputs.size(); i++) {
1003 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01001004 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00001005 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
1006 && desc->mPreferredAttrInfo != nullptr) {
1007 // If the output is using preferred mixer attributes and the audio mode is not normal,
1008 // the output need to reopen with default configuration.
1009 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
1010 continue;
1011 }
Francois Gaffie601801d2021-06-22 13:27:39 +02001012 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
1013 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05301014 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +02001015 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001016 }
1017 }
jiabin3ff8d7d2022-12-13 06:27:44 +00001018 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001019
Eric Laurent96d1dda2022-03-14 17:14:19 +01001020 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
1021
Eric Laurente552edb2014-03-10 17:42:56 -07001022 if (isStateInCall(state)) {
1023 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001024 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001025 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001026 }
1027
1028 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001029 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1030 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001031}
1032
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001033audio_mode_t AudioPolicyManager::getPhoneState() {
1034 return mEngine->getPhoneState();
1035}
1036
Eric Laurente0720872014-03-11 09:30:41 -07001037void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001038 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001039{
François Gaffie2110e042015-03-24 08:41:51 +01001040 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001041 if (config == mEngine->getForceUse(usage)) {
1042 return;
1043 }
Eric Laurente552edb2014-03-10 17:42:56 -07001044
François Gaffie2110e042015-03-24 08:41:51 +01001045 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1046 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1047 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001048 }
François Gaffie2110e042015-03-24 08:41:51 +01001049 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1050 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1051 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001052
1053 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001054 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001055
Eric Laurent22fcda22019-05-17 16:28:47 -07001056 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1057 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001058 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001059 }
1060
Eric Laurentdc462862016-07-19 12:29:53 -07001061 //FIXME: workaround for truncated touch sounds
1062 // to be removed when the problem is handled by system UI
1063 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001064 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1065 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1066 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001067
1068 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001069 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001070}
1071
Eric Laurente0720872014-03-11 09:30:41 -07001072void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001073{
1074 ALOGV("setSystemProperty() property %s, value %s", property, value);
1075}
1076
Dorin Drimusecc9f422022-03-09 17:57:40 +01001077// Find an MSD output profile compatible with the parameters passed.
1078// When "directOnly" is set, restrict search to profiles for direct outputs.
1079sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1080 const DeviceVector& devices,
1081 uint32_t samplingRate,
1082 audio_format_t format,
1083 audio_channel_mask_t channelMask,
1084 audio_output_flags_t flags,
1085 bool directOnly)
1086{
1087 flags = getRelevantFlags(flags, directOnly);
1088
1089 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1090 if (msdModule != nullptr) {
1091 // for the msd module check if there are patches to the output devices
1092 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1093 HwModuleCollection modules;
1094 modules.add(msdModule);
1095 return searchCompatibleProfileHwModules(
1096 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1097 flags, directOnly);
1098 }
1099 }
1100 return nullptr;
1101}
1102
Michael Chana94fbb22018-04-24 14:31:19 +10001103// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1104// search to profiles for direct outputs.
1105sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001106 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001107 uint32_t samplingRate,
1108 audio_format_t format,
1109 audio_channel_mask_t channelMask,
1110 audio_output_flags_t flags,
1111 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001112{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001113 flags = getRelevantFlags(flags, directOnly);
1114
1115 return searchCompatibleProfileHwModules(
1116 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1117}
1118
1119audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1120 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001121 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001122 // only retain flags that will drive the direct output profile selection
1123 // if explicitly requested
1124 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001125 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001126 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1127 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001128 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001129 return flags;
1130}
Eric Laurent861a6282015-05-18 15:40:16 -07001131
Dorin Drimusecc9f422022-03-09 17:57:40 +01001132sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1133 const HwModuleCollection& hwModules,
1134 const DeviceVector& devices,
1135 uint32_t samplingRate,
1136 audio_format_t format,
1137 audio_channel_mask_t channelMask,
1138 audio_output_flags_t flags,
1139 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001140 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001141 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001142 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001143 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001144 samplingRate, NULL /*updatedSamplingRate*/,
1145 format, NULL /*updatedFormat*/,
1146 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001147 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001148 continue;
1149 }
1150 // reject profiles not corresponding to a device currently available
1151 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1152 continue;
1153 }
1154 // reject profiles if connected device does not support codec
1155 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1156 continue;
1157 }
1158 if (!directOnly) {
1159 return curProfile;
1160 }
1161
1162 // when searching for direct outputs, if several profiles are compatible, give priority
1163 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001164 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001165 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001166 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001167 }
1168 profile = curProfile;
1169 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1170 break;
1171 }
Eric Laurente552edb2014-03-10 17:42:56 -07001172 }
1173 }
Eric Laurent861a6282015-05-18 15:40:16 -07001174 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001175}
1176
Eric Laurentfa0f6742021-08-17 18:39:44 +02001177sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001178 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001179{
1180 for (const auto& hwModule : mHwModules) {
1181 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001182 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001183 continue;
1184 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001185 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001186 // reject profiles not corresponding to a device currently available
1187 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1188 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1189 continue;
1190 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001191 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1192 != devices.size()) {
1193 continue;
1194 }
1195 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001196 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1197 return curProfile;
1198 }
1199 }
1200 return nullptr;
1201}
1202
Eric Laurentf4e63452017-11-06 19:31:46 +00001203audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001204{
François Gaffiec005e562018-11-06 15:04:49 +01001205 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001206
1207 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1208 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1209 // format, flags, etc. This may result in some discrepancy for functions that utilize
1210 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1211 // and AudioSystem::getOutputSamplingRate().
1212
François Gaffie11d30102018-11-02 16:09:09 +01001213 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001214 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov806170e2024-09-05 17:26:50 -07001215 if (stream == AUDIO_STREAM_MUSIC && mConfig->useDeepBufferForMedia()) {
Mingyu Shih75563d32023-05-24 04:47:40 +08001216 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1217 }
1218 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001219
François Gaffie11d30102018-11-02 16:09:09 +01001220 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1221 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001222 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001223}
1224
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001225status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1226 const audio_attributes_t *srcAttr,
1227 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001228{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001229 if (srcAttr != NULL) {
1230 if (!isValidAttributes(srcAttr)) {
1231 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1232 __func__,
1233 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1234 srcAttr->tags);
1235 return BAD_VALUE;
1236 }
1237 *dstAttr = *srcAttr;
1238 } else {
1239 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1240 ALOGE("%s: invalid stream type", __func__);
1241 return BAD_VALUE;
1242 }
François Gaffiec005e562018-11-06 15:04:49 +01001243 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001244 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001245
1246 // Only honor audibility enforced when required. The client will be
1247 // forced to reconnect if the forced usage changes.
1248 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001249 dstAttr->flags = static_cast<audio_flags_mask_t>(
1250 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001251 }
1252
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001253 return NO_ERROR;
1254}
1255
Kevin Rocard153f92d2018-12-18 18:33:28 -08001256status_t AudioPolicyManager::getOutputForAttrInt(
1257 audio_attributes_t *resultAttr,
1258 audio_io_handle_t *output,
1259 audio_session_t session,
1260 const audio_attributes_t *attr,
1261 audio_stream_type_t *stream,
1262 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001263 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001264 audio_output_flags_t *flags,
Robert Wufb971192024-10-30 21:54:35 +00001265 DeviceIdVector *selectedDeviceIds,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001266 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001267 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001268 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001269 bool *isSpatialized,
1270 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001271{
François Gaffiec005e562018-11-06 15:04:49 +01001272 DeviceVector outputDevices;
Robert Wufb971192024-10-30 21:54:35 +00001273 audio_port_handle_t requestedPortId = getFirstDeviceId(*selectedDeviceIds);
1274 selectedDeviceIds->clear();
François Gaffie11d30102018-11-02 16:09:09 +01001275 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001276 const sp<DeviceDescriptor> requestedDevice =
1277 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1278
Eric Laurent8a1095a2019-11-08 14:44:16 -08001279 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001280 *isSpatialized = false;
1281
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001282 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1283 if (status != NO_ERROR) {
1284 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001285 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001286 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001287 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001288 }
François Gaffiec005e562018-11-06 15:04:49 +01001289 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001290
François Gaffiec005e562018-11-06 15:04:49 +01001291 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1292 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001293
Oscar Azucena873d10f2023-01-12 18:34:42 -08001294 bool usePrimaryOutputFromPolicyMixes = false;
1295
Kevin Rocard153f92d2018-12-18 18:33:28 -08001296 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1297 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1298 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001299 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001300 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1301 .channel_mask = config->channel_mask,
1302 .format = config->format,
1303 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001304 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001305 mAvailableOutputDevices, requestedDevice, primaryMix,
1306 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001307 if (status != OK) {
1308 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001309 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001310
Kevin Rocard153f92d2018-12-18 18:33:28 -08001311 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001312 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungdb27c442024-08-14 11:37:57 -07001313 && (!audio_is_linear_pcm(config->format) ||
1314 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001315 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001316 return BAD_VALUE;
1317 }
1318 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001319 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001320 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1321 primaryMix->mDeviceAddress,
1322 AUDIO_FORMAT_DEFAULT);
1323 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001324 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001325 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1326 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001327 // if a direct output can be opened to deliver the track's multi-channel content to the
1328 // output rather than being downmixed by the primary output, then use this direct
1329 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1330 // mix.
1331 bool tryDirectForChannelMask = policyDesc != nullptr
1332 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1333 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001334 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001335 audio_io_handle_t newOutput;
1336 status = openDirectOutput(
1337 *stream, session, config,
1338 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangf6e304f2024-07-09 23:06:58 -07001339 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001340 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001341 policyDesc = mOutputs.valueFor(newOutput);
1342 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001343 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001344 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001345 policyDesc = nullptr;
1346 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001347 }
1348 if (policyDesc != nullptr) {
1349 policyDesc->mPolicyMix = primaryMix;
1350 *output = policyDesc->mIoHandle;
Robert Wufb971192024-10-30 21:54:35 +00001351 if (policyMixDevice != nullptr) {
1352 selectedDeviceIds->push_back(policyMixDevice->getId());
1353 }
jiabin24ff57a2023-11-27 21:06:51 +00001354 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1355 // Remove direct flag as it is not on a direct output.
1356 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1357 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001358
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001359 ALOGV("getOutputForAttr() returns output %d", *output);
1360 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1361 *outputType = API_OUT_MIX_PLAYBACK;
1362 } else {
1363 *outputType = API_OUTPUT_LEGACY;
1364 }
1365 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001366 } else {
1367 if (policyMixDevice != nullptr) {
1368 ALOGE("%s, try to use primary mix but no output found", __func__);
1369 return INVALID_OPERATION;
1370 }
1371 // Fallback to default engine selection as the selected primary mix device is not
1372 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001373 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001374 }
François Gaffiec005e562018-11-06 15:04:49 +01001375 // Virtual sources must always be dynamicaly or explicitly routed
1376 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1377 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1378 return BAD_VALUE;
1379 }
1380 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1381 // in order to let the choice of the order to future vendor engine
1382 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001383
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001384 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001385 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001386 }
1387
Nadav Barb2f18162018-07-18 13:01:53 +03001388 // Set incall music only if device was explicitly set, and fallback to the device which is
1389 // chosen by the engine if not.
1390 // FIXME: provide a more generic approach which is not device specific and move this back
1391 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001392 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001393 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001394 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001395 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001396 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001397 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001398 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001399 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001400 }
1401 }
1402
François Gaffiec005e562018-11-06 15:04:49 +01001403 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1404 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1405 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001406
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001407 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001408 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001409 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001410 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001411 ALOGV("%s() Using MSD devices %s instead of devices %s",
1412 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001413 } else {
1414 *output = AUDIO_IO_HANDLE_NONE;
1415 }
1416 }
1417 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001418 sp<PreferredMixerAttributesInfo> info = nullptr;
1419 if (outputDevices.size() == 1) {
1420 info = getPreferredMixerAttributesInfo(
1421 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001422 mEngine->getProductStrategyForAttributes(*resultAttr),
1423 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001424 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1425 // and it is currently active.
1426 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001427 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001428 info = nullptr;
1429 }
jiabin8a096672024-09-18 18:20:24 +00001430
1431 if (info != nullptr && info->isBitPerfect() &&
1432 (*flags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
1433 AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1434 // Reject direct request if a preferred mixer config in use is bit-perfect.
1435 ALOGD("%s reject direct request as bit-perfect mixer attributes is active",
1436 __func__);
1437 return BAD_VALUE;
1438 }
1439
jiabin220eea12024-05-17 17:55:20 +00001440 if (com::android::media::audioserver::
1441 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1442 if (info != nullptr && info->getUid() == uid &&
1443 info->configMatches(*config) &&
1444 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1445 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1446 [this, &outputDevices](audio_usage_t usage) {
1447 return mOutputs.isUsageActiveOnDevice(
1448 usage, outputDevices[0]); }))) {
1449 // Bit-perfect request is not allowed when the phone mode is not normal or
1450 // there is any higher priority user case active.
1451 return INVALID_OPERATION;
1452 }
1453 }
jiabina84c3d32022-12-02 18:59:55 +00001454 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001455 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001456 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001457 // The client will be active if the client is currently preferred mixer owner and the
1458 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001459 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001460 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001461 && info->getUid() == uid
1462 && *output != AUDIO_IO_HANDLE_NONE
1463 // When bit-perfect output is selected for the preferred mixer attributes owner,
1464 // only need to consider the config matches.
1465 && mOutputs.valueFor(*output)->isConfigurationMatched(
1466 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001467
1468 if (*isBitPerfect) {
1469 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1470 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001471 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001472 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001473 AudioProfileVector profiles;
1474 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1475 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001476 const auto channels = profiles[0]->getChannels();
1477 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1478 config->channel_mask = *channels.begin();
1479 }
1480 const auto sampleRates = profiles[0]->getSampleRates();
1481 if (!sampleRates.empty() &&
1482 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1483 config->sample_rate = *sampleRates.begin();
1484 }
jiabinf1c73972022-04-14 16:28:52 -07001485 config->format = profiles[0]->getFormat();
1486 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001487 return INVALID_OPERATION;
1488 }
Paul McLeanaa981192015-03-21 09:55:15 -07001489
Michael Chan6fb34492020-12-08 15:44:49 +11001490 for (auto &outputDevice : outputDevices) {
Robert Wufb971192024-10-30 21:54:35 +00001491 if (std::find(selectedDeviceIds->begin(), selectedDeviceIds->end(),
1492 outputDevice->getId()) == selectedDeviceIds->end()) {
1493 selectedDeviceIds->push_back(outputDevice->getId());
1494 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
1495 std::swap(selectedDeviceIds->front(), selectedDeviceIds->back());
1496 }
Michael Chan6fb34492020-12-08 15:44:49 +11001497 }
1498 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001499
Eric Laurent8a1095a2019-11-08 14:44:16 -08001500 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1501 *outputType = API_OUTPUT_TELEPHONY_TX;
1502 } else {
1503 *outputType = API_OUTPUT_LEGACY;
1504 }
1505
Robert Wufb971192024-10-30 21:54:35 +00001506 ALOGV("%s returns output %d selectedDeviceIds %s", __func__, *output,
1507 toString(*selectedDeviceIds).c_str());
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001508
1509 return NO_ERROR;
1510}
1511
1512status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1513 audio_io_handle_t *output,
1514 audio_session_t session,
1515 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001516 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001517 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001518 audio_output_flags_t *flags,
Robert Wufb971192024-10-30 21:54:35 +00001519 DeviceIdVector *selectedDeviceIds,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001520 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001521 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001522 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001523 bool *isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +00001524 bool *isBitPerfect,
Vlad Popa1e865e62024-08-15 19:11:42 -07001525 float *volume,
1526 bool *muted)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001527{
1528 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1529 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1530 return INVALID_OPERATION;
1531 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001532 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001533 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001534 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001535 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001536 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Robert Wufb971192024-10-30 21:54:35 +00001537 DeviceIdVector requestedDeviceIds = *selectedDeviceIds;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001538
1539 // Prevent from storing invalid requested device id in clients
Robert Wufb971192024-10-30 21:54:35 +00001540 DeviceIdVector sanitizedRequestedPortIds;
1541 for (auto deviceId : *selectedDeviceIds) {
1542 if (mAvailableOutputDevices.getDeviceFromId(deviceId) != nullptr) {
1543 sanitizedRequestedPortIds.push_back(deviceId);
1544 }
1545 }
1546 *selectedDeviceIds = sanitizedRequestedPortIds;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001547
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001548 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Robert Wufb971192024-10-30 21:54:35 +00001549 config, flags, selectedDeviceIds, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001550 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1551 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001552 if (status != NO_ERROR) {
1553 return status;
1554 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001555 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001556 if (secondaryOutputs != nullptr) {
1557 for (auto &secondaryMix : secondaryMixes) {
1558 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1559 if (outputDesc != nullptr &&
1560 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1561 secondaryOutputs->push_back(outputDesc->mIoHandle);
1562 weakSecondaryOutputDescs.push_back(outputDesc);
1563 }
1564 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001565 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001566
Eric Laurent8fc147b2018-07-22 19:13:55 -07001567 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001568 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001569 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001570 };
jiabin4ef93452019-09-10 14:29:54 -07001571 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001572
Eric Laurentc209fe42020-06-05 18:11:23 -07001573 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Robert Wufb971192024-10-30 21:54:35 +00001574 // TODO(b/367816690): Add device id sets to TrackClientDescriptor
Eric Laurent8fc147b2018-07-22 19:13:55 -07001575 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001576 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Robert Wufb971192024-10-30 21:54:35 +00001577 getFirstDeviceId(sanitizedRequestedPortIds), *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001578 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001579 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001580 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001581 std::move(weakSecondaryOutputDescs),
1582 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001583 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001584
Andy Hung6b137d12024-08-27 22:35:17 +00001585 *volume = Volume::DbToAmpl(outputDesc->getCurVolume(toVolumeSource(resultAttr)));
Vlad Popa1e865e62024-08-15 19:11:42 -07001586 *muted = outputDesc->isMutedByGroup(toVolumeSource(resultAttr));
Andy Hung6b137d12024-08-27 22:35:17 +00001587
Robert Wufb971192024-10-30 21:54:35 +00001588 ALOGV("%s() returns output %d requestedPortIds %s selectedDeviceIds %s for port ID %d",
1589 __func__, *output, toString(requestedDeviceIds).c_str(),
1590 toString(*selectedDeviceIds).c_str(), *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001591
Eric Laurente83b55d2014-11-14 10:06:21 -08001592 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001593}
1594
Eric Laurentc529cf62020-04-17 18:19:10 -07001595status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1596 audio_session_t session,
1597 const audio_config_t *config,
1598 audio_output_flags_t flags,
1599 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001600 audio_io_handle_t *output,
1601 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001602
1603 *output = AUDIO_IO_HANDLE_NONE;
1604
1605 // skip direct output selection if the request can obviously be attached to a mixed output
1606 // and not explicitly requested
1607 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1608 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1609 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1610 return NAME_NOT_FOUND;
1611 }
1612
Mikhail Naganov806170e2024-09-05 17:26:50 -07001613 // Reject flag combinations that do not make sense. Note that the requested flags might not
1614 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1615 // combine the requested flags with its own flags, yielding an unsupported combination.
1616 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1617 return NAME_NOT_FOUND;
1618 }
1619
Eric Laurentc529cf62020-04-17 18:19:10 -07001620 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1621 // This prevents creating an offloaded track and tearing it down immediately after start
1622 // when audioflinger detects there is an active non offloadable effect.
1623 // FIXME: We should check the audio session here but we do not have it in this context.
1624 // This may prevent offloading in rare situations where effects are left active by apps
1625 // in the background.
1626 sp<IOProfile> profile;
1627 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1628 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1629 profile = getProfileForOutput(
1630 devices, config->sample_rate, config->format, config->channel_mask,
1631 flags, true /* directOnly */);
1632 }
1633
1634 if (profile == nullptr) {
1635 return NAME_NOT_FOUND;
1636 }
1637
1638 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1639 for (size_t i = 0; i < mOutputs.size(); i++) {
1640 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1641 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1642 // reuse direct output if currently open by the same client
1643 // and configured with same parameters
1644 if ((config->sample_rate == desc->getSamplingRate()) &&
1645 (config->format == desc->getFormat()) &&
1646 (config->channel_mask == desc->getChannelMask()) &&
1647 (session == desc->mDirectClientSession)) {
1648 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301649 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001650 mOutputs.keyAt(i), session);
1651 *output = mOutputs.keyAt(i);
1652 return NO_ERROR;
1653 }
1654 }
1655 }
1656
1657 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001658 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301659 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1660 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001661 return NAME_NOT_FOUND;
1662 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1663 // MMAP gracefully handles lack of an exclusive track resource by mixing
1664 // above the audio framework. For AAudio to know that the limit is reached,
1665 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301666 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1667 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001668 return NAME_NOT_FOUND;
1669 } else {
1670 // Close outputs on this profile, if available, to free resources for this request
1671 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1672 const auto desc = mOutputs.valueAt(i);
1673 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301674 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1675 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001676 closeOutput(desc->mIoHandle);
1677 }
1678 }
1679 }
1680 }
1681
1682 // Unable to close streams to find free resources for this request
1683 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301684 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1685 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001686 return NAME_NOT_FOUND;
1687 }
1688
Atneya Nairb16666a2023-12-11 20:18:33 -08001689 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001690
Michael Chan6fb34492020-12-08 15:44:49 +11001691 // An MSD patch may be using the only output stream that can service this request. Release
1692 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001693 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001694
Eric Laurentf1f22e72021-07-13 14:04:14 +02001695 status_t status =
Dean Wheatleydfb67b82024-01-23 09:36:29 +11001696 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001697 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001698
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001699 // only accept an output with the requested parameters, unless the format can be IEC61937
1700 // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1701 const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1702 && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1703 && audio_has_proportional_frames(outputDesc->getFormat());
Eric Laurentc529cf62020-04-17 18:19:10 -07001704 if (status != NO_ERROR ||
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001705 (!ignoreRequestedParametersCheck &&
1706 ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1707 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1708 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001709 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1710 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1711 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1712 config->channel_mask, outputDesc->getChannelMask());
1713 if (*output != AUDIO_IO_HANDLE_NONE) {
1714 outputDesc->close();
1715 }
1716 // fall back to mixer output if possible when the direct output could not be open
1717 if (audio_is_linear_pcm(config->format) &&
1718 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1719 return NAME_NOT_FOUND;
1720 }
1721 *output = AUDIO_IO_HANDLE_NONE;
1722 return BAD_VALUE;
1723 }
1724 outputDesc->mDirectOpenCount = 1;
1725 outputDesc->mDirectClientSession = session;
1726
1727 addOutput(*output, outputDesc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07001728 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
1729 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
1730 hwModule->getHalVersionMajor() >= 3) {
1731 setOutputDevices(__func__, outputDesc, devices, true, 0, NULL);
1732 }
Eric Laurentc529cf62020-04-17 18:19:10 -07001733 mPreviousOutputs = mOutputs;
1734 ALOGV("%s returns new direct output %d", __func__, *output);
1735 mpClientInterface->onAudioPortListUpdate();
1736 return NO_ERROR;
1737}
1738
François Gaffie11d30102018-11-02 16:09:09 +01001739audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1740 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001741 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001742 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001743 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001744 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001745 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001746 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001747 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001748{
Andy Hungc88b0642018-04-27 15:42:35 -07001749 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001750
jiabine375d412019-02-26 12:54:53 -08001751 // Discard haptic channel mask when forcing muting haptic channels.
1752 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001753 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1754 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001755
Eric Laurente552edb2014-03-10 17:42:56 -07001756 // open a direct output if required by specified parameters
1757 //force direct flag if offload flag is set: offloading implies a direct output stream
1758 // and all common behaviors are driven by checking only the direct flag
1759 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001760 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1761 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001762 }
Nadav Bar766fb022018-01-07 12:18:03 +02001763 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1764 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001765 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001766
1767 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1768
Eric Laurente83b55d2014-11-14 10:06:21 -08001769 // only allow deep buffering for music stream type
1770 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001771 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001772 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov806170e2024-09-05 17:26:50 -07001773 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001774 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001775 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001776 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001777 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001778 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001779 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001780 audio_is_linear_pcm(config->format) &&
1781 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001782 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001783 AUDIO_OUTPUT_FLAG_DIRECT);
1784 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001785 }
Eric Laurente552edb2014-03-10 17:42:56 -07001786
Carter Hsua3abb402021-10-26 11:11:20 +08001787 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1788 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1789 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1790 }
1791
Eric Laurentf9230d52024-01-26 18:49:09 +01001792 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001793 // was specified and offload or direct playback is not explicitly requested, and there is no
1794 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001795 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001796 if (mSpatializerOutput != nullptr &&
1797 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1798 prefMixerConfigInfo == nullptr &&
1799 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1800 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001801 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001802 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001803 }
1804
Eric Laurentc529cf62020-04-17 18:19:10 -07001805 audio_config_t directConfig = *config;
1806 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001807
1808 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1809 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001810 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001811 return output;
1812 }
1813
Eric Laurent14cbfca2016-03-17 09:42:16 -07001814 // A request for HW A/V sync cannot fallback to a mixed output because time
1815 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001816 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001817 return AUDIO_IO_HANDLE_NONE;
1818 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001819 // A request for Tuner cannot fallback to a mixed output
1820 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1821 return AUDIO_IO_HANDLE_NONE;
1822 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001823
Eric Laurente552edb2014-03-10 17:42:56 -07001824 // ignoring channel mask due to downmix capability in mixer
1825
1826 // open a non direct output
1827
1828 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001829 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001830 // get which output is suitable for the specified stream. The actual
1831 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001832 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001833 if (prefMixerConfigInfo != nullptr) {
1834 for (audio_io_handle_t outputHandle : outputs) {
1835 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1836 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1837 output = outputHandle;
1838 break;
1839 }
1840 }
1841 if (output == AUDIO_IO_HANDLE_NONE) {
1842 // No output open with the preferred profile. Open a new one.
1843 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1844 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1845 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1846 config.format = prefMixerConfigInfo->getConfigBase().format;
1847 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1848 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1849 &config, prefMixerConfigInfo->getFlags());
1850 if (preferredOutput == nullptr) {
1851 ALOGE("%s failed to open output with preferred mixer config", __func__);
1852 } else {
1853 output = preferredOutput->mIoHandle;
1854 }
1855 }
1856 } else {
1857 // at this stage we should ignore the DIRECT flag as no direct output could be
1858 // found earlier
1859 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001860 if (com::android::media::audioserver::
1861 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1862 // If the preferred mixer attributes is null, do not select the bit-perfect output
1863 // unless the bit-perfect output is the only output.
1864 // The bit-perfect output can exist while the passed in preferred mixer attributes
1865 // info is null when it is a high priority client. The high priority clients are
1866 // ringtone or alarm, which is not a bit-perfect use case.
1867 size_t i = 0;
1868 while (i < outputs.size() && outputs.size() > 1) {
1869 auto desc = mOutputs.valueFor(outputs[i]);
1870 // The output descriptor must not be null here.
1871 if (desc->isBitPerfect()) {
1872 outputs.removeItemsAt(i);
1873 } else {
1874 i += 1;
1875 }
1876 }
1877 }
jiabina84c3d32022-12-02 18:59:55 +00001878 output = selectOutput(
1879 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1880 }
Eric Laurente552edb2014-03-10 17:42:56 -07001881 }
François Gaffie11d30102018-11-02 16:09:09 +01001882 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001883 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001884 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001885
Eric Laurente552edb2014-03-10 17:42:56 -07001886 return output;
1887}
1888
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001889sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001890 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1891 mAvailableInputDevices);
1892 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1893}
1894
1895DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1896 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1897 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001898}
1899
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001900const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001901 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001902 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1903 if (msdModule != 0) {
1904 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1905 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1906 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1907 const struct audio_port_config *source = &patch->mPatch.sources[j];
1908 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1909 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001910 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001911 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001912 }
1913 }
1914 }
1915 return msdPatches;
1916}
1917
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001918bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1919 ssize_t index = mAudioPatches.indexOfKey(handle);
1920 if (index < 0) {
1921 return false;
1922 }
1923 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1924 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1925 if (msdModule == nullptr) {
1926 return false;
1927 }
1928 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1929 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1930 return true;
1931 }
1932 index = getMsdOutputPatches().indexOfKey(handle);
1933 if (index < 0) {
1934 return false;
1935 }
1936 return true;
1937}
1938
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001939status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1940 const InputProfileCollection &inputProfiles,
1941 const OutputProfileCollection &outputProfiles,
1942 const sp<DeviceDescriptor> &sourceDevice,
1943 const sp<DeviceDescriptor> &sinkDevice,
1944 AudioProfileVector& sourceProfiles,
1945 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001946 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001947 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001948 return NO_INIT;
1949 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001950 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001951 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001952 return NO_INIT;
1953 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001954 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001955 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1956 inProfile->supportsDevice(sourceDevice)) {
1957 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001958 }
1959 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001960 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001961 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001962 outProfile->supportsDevice(sinkDevice)) {
1963 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001964 }
1965 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001966 return NO_ERROR;
1967}
1968
1969status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1970 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1971 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1972{
Dean Wheatley16809da2022-12-09 14:55:46 +11001973 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1974 static const std::vector<audio_format_t> formatsOrder = {{
1975 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001976 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1977 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001978 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1979 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1980 // preferred).
1981 std::vector<audio_channel_mask_t> masks = {{
1982 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1983 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1984 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1985 // insert index masks (higher counts most preferred) as preferred over position masks
1986 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1987 masks.insert(
1988 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1989 }
1990 return masks;
1991 }();
1992
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001993 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001994 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1995 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001996 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001997 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1998 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001999 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002000 }
2001 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
2002 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
2003 sinkConfig->format = bestSinkConfig.format;
2004 // For encoded streams force direct flag to prevent downstream mixing.
2005 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2006 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11002007 if (audio_is_iec61937_compatible(sinkConfig->format)) {
2008 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002009 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11002010 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
2011 // raw and IEC61937 framed streams.
2012 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2013 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
2014 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002015 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
2016 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11002017 sourceConfig->channel_mask =
2018 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
2019 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
2020 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002021 sourceConfig->format = bestSinkConfig.format;
2022 // Copy input stream directly without any processing (e.g. resampling).
2023 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2024 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
2025 if (hwAvSync) {
2026 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2027 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
2028 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2029 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
2030 }
2031 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
2032 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
2033 sinkConfig->config_mask |= config_mask;
2034 sourceConfig->config_mask |= config_mask;
2035 return NO_ERROR;
2036}
2037
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002038PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
2039 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002040{
2041 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002042 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
2043 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
2044 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
2045 if (deviceModule == nullptr) {
2046 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
2047 return patchBuilder;
2048 }
2049 const InputProfileCollection inputProfiles = msdIsSource ?
2050 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
2051 const OutputProfileCollection outputProfiles = msdIsSource ?
2052 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2053
2054 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2055 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2056 device : getMsdAudioOutDevices().itemAt(0);
2057 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2058
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002059 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2060 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002061 AudioProfileVector sourceProfiles;
2062 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002063 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2064 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002065 for (auto hwAvSync : { true, false }) {
2066 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2067 sourceProfiles, sinkProfiles) != NO_ERROR) {
2068 continue;
2069 }
2070 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2071 &sinkConfig) == NO_ERROR) {
2072 // Found a matching config. Re-create PatchBuilder with this config.
2073 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2074 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002075 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002076 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002077 " supporting PCM format conversion.", __func__);
2078 return patchBuilder;
2079}
2080
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002081status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002082 DeviceVector devices;
2083 if (outputDevices != nullptr && outputDevices->size() > 0) {
2084 devices.add(*outputDevices);
2085 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002086 // Use media strategy for unspecified output device. This should only
2087 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2088 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002089 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002090 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002091 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002092 }
Michael Chan6fb34492020-12-08 15:44:49 +11002093 std::vector<PatchBuilder> patchesToCreate;
2094 for (auto i = 0u; i < devices.size(); ++i) {
2095 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002096 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002097 }
2098 // Retain only the MSD patches associated with outputDevices request.
2099 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002100 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002101 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2102 auto retainedPatch = false;
2103 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2104 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2105 patchesToRemove.removeItemsAt(i);
2106 retainedPatch = true;
2107 break;
2108 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002109 }
Michael Chan6fb34492020-12-08 15:44:49 +11002110 if (retainedPatch) {
2111 it = patchesToCreate.erase(it);
2112 continue;
2113 }
2114 ++it;
2115 }
2116 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2117 return NO_ERROR;
2118 }
2119 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2120 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002121 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002122 }
Michael Chan6fb34492020-12-08 15:44:49 +11002123 status_t status = NO_ERROR;
2124 for (const auto &p : patchesToCreate) {
2125 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2126 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2127 char message[256];
2128 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2129 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2130 currStatus == NO_ERROR ? "Success" : "Error",
2131 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2132 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2133 if (currStatus == NO_ERROR) {
2134 ALOGD("%s", message);
2135 } else {
2136 ALOGE("%s", message);
2137 if (status == NO_ERROR) {
2138 status = currStatus;
2139 }
2140 }
2141 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002142 return status;
2143}
2144
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002145void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2146 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002147 for (size_t i = 0; i < msdPatches.size(); i++) {
2148 const auto& patch = msdPatches[i];
2149 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2150 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2151 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2152 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2153 releaseAudioPatch(patch->getHandle(), mUidCached);
2154 break;
2155 }
2156 }
2157 }
2158}
2159
Dorin Drimus94d94412022-02-02 09:05:02 +01002160bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002161 DeviceVector devicesToCheck =
2162 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002163 AudioPatchCollection msdPatches = getMsdOutputPatches();
2164 for (size_t i = 0; i < msdPatches.size(); i++) {
2165 const auto& patch = msdPatches[i];
2166 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2167 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2168 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2169 const auto& foundDevice = devicesToCheck.getDevice(
2170 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2171 if (foundDevice != nullptr) {
2172 devicesToCheck.remove(foundDevice);
2173 if (devicesToCheck.isEmpty()) {
2174 return true;
2175 }
2176 }
2177 }
2178 }
2179 }
2180 return false;
2181}
2182
Eric Laurente0720872014-03-11 09:30:41 -07002183audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002184 audio_output_flags_t flags,
2185 audio_format_t format,
2186 audio_channel_mask_t channelMask,
2187 uint32_t samplingRate,
2188 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002189{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002190 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2191 "%s called with format %#x", __func__, format);
2192
jiabinebb6af42020-06-09 17:31:17 -07002193 // Return the output that haptic-generating attached to when 1) session id is specified,
2194 // 2) haptic-generating effect exists for given session id and 3) the output that
2195 // haptic-generating effect attached to is in given outputs.
2196 if (sessionId != AUDIO_SESSION_NONE) {
2197 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2198 sessionId, FX_IID_HAPTICGENERATOR);
2199 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2200 return hapticGeneratingOutput;
2201 }
2202 }
2203
Eric Laurent16c66dd2019-05-01 17:54:10 -07002204 // Flags disqualifying an output: the match must happen before calling selectOutput()
2205 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2206 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2207
2208 // Flags expressing a functional request: must be honored in priority over
2209 // other criteria
2210 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2211 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002212 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2213 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002214 // Flags expressing a performance request: have lower priority than serving
2215 // requested sampling rate or channel mask
2216 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2217 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2218 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2219
2220 const audio_output_flags_t functionalFlags =
2221 (audio_output_flags_t)(flags & kFunctionalFlags);
2222 const audio_output_flags_t performanceFlags =
2223 (audio_output_flags_t)(flags & kPerformanceFlags);
2224
2225 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2226
Eric Laurente552edb2014-03-10 17:42:56 -07002227 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002228 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002229 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002230 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002231 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002232 // with tiebreak preferring the minimum number of extra functional flags
2233 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002234 // 3: the output supporting the exact channel mask
2235 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002236 // 5: the output with the highest sampling rate if the requested sample rate is
2237 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002238 // 6: the output with the highest number of requested performance flags
2239 // 7: the output with the bit depth the closest to the requested one
2240 // 8: the primary output
2241 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002242
Eric Laurent16c66dd2019-05-01 17:54:10 -07002243 // matching criteria values in priority order for best matching output so far
2244 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002245
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002246 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002247 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2248 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2249 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002250
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002251 for (audio_io_handle_t output : outputs) {
2252 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002253 // matching criteria values in priority order for current output
2254 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002255
Eric Laurent16c66dd2019-05-01 17:54:10 -07002256 if (outputDesc->isDuplicated()) {
2257 continue;
2258 }
2259 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2260 continue;
2261 }
Eric Laurent8838a382014-09-08 16:44:28 -07002262
Eric Laurent16c66dd2019-05-01 17:54:10 -07002263 // If haptic channel is specified, use the haptic output if present.
2264 // When using haptic output, same audio format and sample rate are required.
2265 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002266 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002267 // skip if haptic channel specified but output does not support it, or output support haptic
2268 // but there is no haptic channel requested AND no orphan haptic effect exist
2269 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2270 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002271 continue;
2272 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002273 // In the case of audio-coupled-haptic playback, there is no format conversion and
2274 // resampling in the framework, same format/channel/sampleRate for client and the output
2275 // thread is required. In the case of HapticGenerator effect, do not require format
2276 // matching.
2277 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2278 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002279 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002280 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002281 }
2282
2283 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002284 const int matchingFunctionalFlags =
2285 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2286 const int totalFunctionalFlags =
2287 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2288 // Prefer matching functional flags, but subtract unnecessary functional flags.
2289 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002290
2291 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002292 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2293 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002294 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2295 channelCount <= outputChannelCount) {
2296 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002297 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2298 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002299 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002300 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002301 currentMatchCriteria[3] = outputChannelCount;
2302 }
2303
2304 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002305 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002306 int diff; // avoid unsigned integer overflow.
2307 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2308
2309 // prefer the closest output sampling rate greater than or equal to target
2310 // if none exists, prefer the closest output sampling rate less than target.
2311 //
2312 // criteria is offset to make non-negative.
2313 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002314 }
2315
2316 // performance flags match
2317 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2318
2319 // format match
2320 if (format != AUDIO_FORMAT_INVALID) {
2321 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002322 PolicyAudioPort::kFormatDistanceMax -
2323 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002324 }
2325
2326 // primary output match
2327 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2328
2329 // compare match criteria by priority then value
2330 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2331 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2332 bestMatchCriteria = currentMatchCriteria;
2333 bestOutput = output;
2334
2335 std::stringstream result;
2336 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2337 std::ostream_iterator<int>(result, " "));
2338 ALOGV("%s new bestOutput %d criteria %s",
2339 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002340 }
2341 }
2342
Eric Laurent16c66dd2019-05-01 17:54:10 -07002343 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002344}
2345
Eric Laurent8fc147b2018-07-22 19:13:55 -07002346status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002347{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002348 ALOGV("%s portId %d", __FUNCTION__, portId);
2349
2350 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2351 if (outputDesc == 0) {
2352 ALOGW("startOutput() no output for client %d", portId);
Eric Laurent5d837ea2024-11-15 18:56:01 +00002353 return DEAD_OBJECT;
Eric Laurente552edb2014-03-10 17:42:56 -07002354 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002355 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002356
Eric Laurent8fc147b2018-07-22 19:13:55 -07002357 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002358 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002359
jiabin220eea12024-05-17 17:55:20 +00002360 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2361 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2362 && outputDesc->isBitPerfect()) {
2363 // Usually, APM selects bit-perfect output for high priority use cases only when
2364 // bit-perfect output is the only output that can be routed to the selected device.
2365 // However, here is no need to play high priority use cases such as ringtone and alarm
2366 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2367 // can attach to new output.
2368 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2369 __func__, client->stream());
2370 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2371 return DEAD_OBJECT;
2372 }
2373
Eric Laurent733ce942017-12-07 12:18:25 -08002374 status_t status = outputDesc->start();
2375 if (status != NO_ERROR) {
2376 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002377 }
2378
Eric Laurent97ac8712018-07-27 18:59:02 -07002379 uint32_t delayMs;
2380 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002381
2382 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002383 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002384 if (status == DEAD_OBJECT) {
2385 sp<SwAudioOutputDescriptor> desc =
2386 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2387 if (desc == nullptr) {
2388 // This is not common, it may indicate something wrong with the HAL.
2389 ALOGE("%s unable to open output with default config", __func__);
2390 return status;
2391 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002392 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002393 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002394 }
jiabina84c3d32022-12-02 18:59:55 +00002395
2396 // If the client is the first one active on preferred mixer parameters, reopen the output
2397 // if the current mixer parameters doesn't match the preferred one.
2398 if (outputDesc->devices().size() == 1) {
2399 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2400 outputDesc->devices()[0]->getId(), client->strategy());
2401 if (info != nullptr && info->getUid() == client->uid()) {
2402 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2403 info->getConfigBase(), info->getFlags())) {
2404 stopSource(outputDesc, client);
2405 outputDesc->stop();
2406 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2407 config.channel_mask = info->getConfigBase().channel_mask;
2408 config.sample_rate = info->getConfigBase().sample_rate;
2409 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002410 sp<SwAudioOutputDescriptor> desc =
2411 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2412 if (desc == nullptr) {
2413 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002414 }
jiabin220eea12024-05-17 17:55:20 +00002415 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002416 // Intentionally return error to let the client side resending request for
2417 // creating and starting.
2418 return DEAD_OBJECT;
2419 }
2420 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002421 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002422 // If it is first bit-perfect client, reroute all clients that will be routed to
2423 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2424 PortHandleVector clientsToInvalidate;
jiabine6b87492024-09-18 23:36:14 +00002425 std::vector<sp<SwAudioOutputDescriptor>> outputsToResetDevice;
jiabine3d1f552023-06-14 17:42:17 +00002426 for (size_t i = 0; i < mOutputs.size(); i++) {
jiabinfedb92e2024-09-16 21:36:30 +00002427 if (mOutputs[i] == outputDesc || (!mOutputs[i]->devices().isEmpty() &&
2428 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty())) {
jiabine3d1f552023-06-14 17:42:17 +00002429 continue;
2430 }
jiabine6b87492024-09-18 23:36:14 +00002431 if (mOutputs[i]->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
2432 outputsToResetDevice.push_back(mOutputs[i]);
2433 }
jiabine3d1f552023-06-14 17:42:17 +00002434 for (const auto& c : mOutputs[i]->getClientIterable()) {
2435 clientsToInvalidate.push_back(c->portId());
2436 }
2437 }
2438 if (!clientsToInvalidate.empty()) {
2439 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2440 __func__);
2441 mpClientInterface->invalidateTracks(clientsToInvalidate);
2442 }
jiabine6b87492024-09-18 23:36:14 +00002443 for (const auto& output : outputsToResetDevice) {
2444 resetOutputDevice(output, 0 /*delayMs*/, nullptr /*patchHandle*/);
2445 }
jiabine3d1f552023-06-14 17:42:17 +00002446 }
jiabina84c3d32022-12-02 18:59:55 +00002447 }
2448 }
2449
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002450 if (client->hasPreferredDevice()) {
2451 // playback activity with preferred device impacts routing occurred, inform upper layers
2452 mpClientInterface->onRoutingUpdated();
2453 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002454 if (delayMs != 0) {
2455 usleep(delayMs * 1000);
2456 }
2457
jiabin220eea12024-05-17 17:55:20 +00002458 if (status == NO_ERROR &&
2459 outputDesc->mPreferredAttrInfo != nullptr &&
2460 outputDesc->isBitPerfect() &&
2461 com::android::media::audioserver::
2462 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2463 // A new client is started on bit-perfect output, update all clients internal mute.
2464 updateClientsInternalMute(outputDesc);
2465 }
2466
Eric Laurentc75307b2015-03-17 15:29:32 -07002467 return status;
2468}
2469
Eric Laurent96d1dda2022-03-14 17:14:19 +01002470bool AudioPolicyManager::isLeUnicastActive() const {
2471 if (isInCall()) {
2472 return true;
2473 }
2474 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2475}
2476
2477bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2478 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2479 return false;
2480 }
2481 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2482 ALOGV("%s active %d", __func__, active);
2483 return active;
2484}
2485
Eric Laurent97ac8712018-07-27 18:59:02 -07002486status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2487 const sp<TrackClientDescriptor>& client,
2488 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002489{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002490 // cannot start playback of STREAM_TTS if any other output is being used
2491 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002492
2493 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002494 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002495 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002496 auto clientStrategy = client->strategy();
2497 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002498 if (stream == AUDIO_STREAM_TTS) {
2499 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002500 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002501 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002502 return INVALID_OPERATION;
2503 } else {
2504 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2505 }
2506 } else {
2507 // some playback other than beacon starts
2508 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2509 }
2510
Eric Laurent77305a62016-07-25 16:39:22 -07002511 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002512 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002513 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002514
François Gaffie11d30102018-11-02 16:09:09 +01002515 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002516 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002517 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002518 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002519 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002520 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002521 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002522 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002523 } else {
2524 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002525 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002526 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2527 AUDIO_FORMAT_DEFAULT);
2528 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2529 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002530 }
2531
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002532 // requiresMuteCheck is false when we can bypass mute strategy.
2533 // It covers a common case when there is no materially active audio
2534 // and muting would result in unnecessary delay and dropped audio.
2535 const uint32_t outputLatencyMs = outputDesc->latency();
2536 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002537 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002538
Eric Laurente552edb2014-03-10 17:42:56 -07002539 // increment usage count for this stream on the requested output:
2540 // NOTE that the usage count is the same for duplicated output and hardware output which is
2541 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002542 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002543
2544 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002545 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002546 // Preferred device may be exclusive, use only if no other active clients on this output
2547 devices = DeviceVector(
2548 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2549 } else {
2550 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2551 }
François Gaffie11d30102018-11-02 16:09:09 +01002552 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002553 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002554 }
2555 }
Eric Laurente552edb2014-03-10 17:42:56 -07002556
François Gaffiec005e562018-11-06 15:04:49 +01002557 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002558 selectOutputForMusicEffects();
2559 }
2560
François Gaffie1c878552018-11-22 16:53:21 +01002561 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002562 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002563 if (devices.isEmpty()) {
2564 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002565 }
François Gaffiec005e562018-11-06 15:04:49 +01002566 bool shouldWait =
2567 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2568 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2569 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002570 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002571 const bool needToCloseBitPerfectOutput =
2572 (com::android::media::audioserver::
2573 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2574 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2575 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002576 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002577 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002578 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002579 // An output has a shared device if
2580 // - managed by the same hw module
2581 // - supports the currently selected device
2582 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002583 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002584
Eric Laurent77305a62016-07-25 16:39:22 -07002585 // force a device change if any other output is:
2586 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002587 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002588 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002589 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002590 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002591 // change the device currently selected by the other output.
2592 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002593 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002594 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002595 force = true;
2596 }
2597 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002598 // a notification so that audio focus effect can propagate, or that a mute/unmute
2599 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002600 const uint32_t latencyMs = desc->latency();
2601 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2602
2603 if (shouldWait && isActive && (waitMs < latencyMs)) {
2604 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002605 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002606
2607 // Require mute check if another output is on a shared device
2608 // and currently active to have proper drain and avoid pops.
2609 // Note restoring AudioTracks onto this output needs to invoke
2610 // a volume ramp if there is no mute.
2611 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002612
2613 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2614 outputsToReopen.push_back(desc);
2615 }
Eric Laurente552edb2014-03-10 17:42:56 -07002616 }
2617 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002618
jiabin220eea12024-05-17 17:55:20 +00002619 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002620 // If the output is open with preferred mixer attributes, but the routed device is
2621 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2622 // changed.
2623 return DEAD_OBJECT;
2624 }
jiabin220eea12024-05-17 17:55:20 +00002625 for (auto& outputToReopen : outputsToReopen) {
2626 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2627 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002628 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302629 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2630 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002631
Eric Laurente552edb2014-03-10 17:42:56 -07002632 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002633 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002634 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002635 curves.getVolumeIndex(outputDesc->devices().types()),
Vlad Popa1e865e62024-08-15 19:11:42 -07002636 outputDesc, outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002637 outputDesc->useHwGain() /*force*/)) {
2638 // request AudioService to reinitialize the volume curves asynchronously
2639 ALOGE("checkAndSetVolume failed, requesting volume range init");
2640 mpClientInterface->onVolumeRangeInitRequest();
2641 };
Eric Laurente552edb2014-03-10 17:42:56 -07002642
2643 // update the outputs if starting an output with a stream that can affect notification
2644 // routing
2645 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002646
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002647 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002648 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002649 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002650 }
Eric Laurentdc462862016-07-19 12:29:53 -07002651
2652 if (waitMs > muteWaitMs) {
2653 *delayMs = waitMs - muteWaitMs;
2654 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002655
2656 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2657 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2658 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2659 // change occurs after the MixerThread starts and causes a stream volume
2660 // glitch.
2661 //
2662 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002663 }
Eric Laurentdc462862016-07-19 12:29:53 -07002664
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002665 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002666 mEngine->getForceUse(
2667 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002668 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002669 }
2670
Eric Laurent97ac8712018-07-27 18:59:02 -07002671 // Automatically enable the remote submix input when output is started on a re routing mix
2672 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002673 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2674 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002675 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2676 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2677 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002678 "remote-submix",
2679 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002680 }
2681
Eric Laurent96d1dda2022-03-14 17:14:19 +01002682 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2683
Eric Laurente552edb2014-03-10 17:42:56 -07002684 return NO_ERROR;
2685}
2686
Eric Laurent96d1dda2022-03-14 17:14:19 +01002687void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2688 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2689 bool isUnicastActive = isLeUnicastActive();
2690
2691 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002692 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002693 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2694 for (size_t i = 0; i < mOutputs.size(); i++) {
2695 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2696 if (desc != ignoredOutput && desc->isActive()
2697 && ((isUnicastActive &&
2698 !desc->devices().
2699 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2700 || (wasUnicastActive &&
2701 !desc->devices().getDevicesFromTypes(
2702 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2703 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2704 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002705 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002706 // If the device is using preferred mixer attributes, the output need to reopen
2707 // with default configuration when the new selected devices are different from
2708 // current routing devices.
2709 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2710 continue;
2711 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302712 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002713 // re-apply device specific volume if not done by setOutputDevice()
2714 if (!force) {
2715 applyStreamVolumes(desc, newDevices.types(), delayMs);
2716 }
2717 }
2718 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002719 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002720 }
2721}
2722
Eric Laurent8fc147b2018-07-22 19:13:55 -07002723status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002724{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002725 ALOGV("%s portId %d", __FUNCTION__, portId);
2726
2727 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2728 if (outputDesc == 0) {
2729 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurent5d837ea2024-11-15 18:56:01 +00002730 return DEAD_OBJECT;
Eric Laurente552edb2014-03-10 17:42:56 -07002731 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002732 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002733
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002734 if (client->hasPreferredDevice(true)) {
2735 // playback activity with preferred device impacts routing occurred, inform upper layers
2736 mpClientInterface->onRoutingUpdated();
2737 }
2738
Eric Laurent97ac8712018-07-27 18:59:02 -07002739 ALOGV("stopOutput() output %d, stream %d, session %d",
2740 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002741
Eric Laurent97ac8712018-07-27 18:59:02 -07002742 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002743
Eric Laurent733ce942017-12-07 12:18:25 -08002744 if (status == NO_ERROR ) {
2745 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002746 } else {
2747 return status;
2748 }
2749
2750 if (outputDesc->devices().size() == 1) {
2751 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2752 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002753 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002754 if (info != nullptr && info->getUid() == client->uid()) {
2755 info->decreaseActiveClient();
2756 if (info->getActiveClientCount() == 0) {
2757 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002758 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002759 }
2760 }
jiabin220eea12024-05-17 17:55:20 +00002761 if (com::android::media::audioserver::
2762 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2763 !outputReopened && outputDesc->isBitPerfect()) {
2764 // Only need to update the clients' internal mute when the output is bit-perfect and it
2765 // is not reopened.
2766 updateClientsInternalMute(outputDesc);
2767 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002768 }
2769 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002770}
2771
Eric Laurent97ac8712018-07-27 18:59:02 -07002772status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2773 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002774{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002775 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002776 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002777 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002778 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002779
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002780 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2781
François Gaffie1c878552018-11-22 16:53:21 +01002782 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2783 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002784 // Automatically disable the remote submix input when output is stopped on a
2785 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002786 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002787 if (isSingleDeviceType(
2788 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002789 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002790 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002791 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2792 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002793 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002794 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002795 }
2796 }
2797 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002798 if (client->hasPreferredDevice(true) &&
2799 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002800 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002801 forceDeviceUpdate = true;
2802 }
2803
Eric Laurente552edb2014-03-10 17:42:56 -07002804 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002805 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002806
Eric Laurente552edb2014-03-10 17:42:56 -07002807 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002808 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002809 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002810 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002811
2812 // If the routing does not change, if an output is routed on a device using HwGain
2813 // (aka setAudioPortConfig) and there are still active clients following different
2814 // volume group(s), force reapply volume
2815 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2816 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2817
Eric Laurente552edb2014-03-10 17:42:56 -07002818 // delay the device switch by twice the latency because stopOutput() is executed when
2819 // the track stop() command is received and at that time the audio track buffer can
2820 // still contain data that needs to be drained. The latency only covers the audio HAL
2821 // and kernel buffers. Also the latency does not always include additional delay in the
2822 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302823 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002824 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002825
2826 // force restoring the device selection on other active outputs if it differs from the
2827 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002828 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002829 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002830 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002831 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002832 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002833 desc->isActive() &&
2834 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002835 (newDevices != desc->devices())) {
2836 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2837 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002838
jiabin220eea12024-05-17 17:55:20 +00002839 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002840 // If the device is using preferred mixer attributes, the output need to
2841 // reopen with default configuration when the new selected devices are
2842 // different from current routing devices.
2843 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2844 continue;
2845 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302846 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002847
Eric Laurent57de36c2016-09-28 16:59:11 -07002848 // re-apply device specific volume if not done by setOutputDevice()
2849 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002850 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002851 }
Eric Laurente552edb2014-03-10 17:42:56 -07002852 }
2853 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002854 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002855 // update the outputs if stopping one with a stream that can affect notification routing
2856 handleNotificationRoutingForStream(stream);
2857 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002858
2859 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2860 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002861 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002862 }
2863
François Gaffiec005e562018-11-06 15:04:49 +01002864 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002865 selectOutputForMusicEffects();
2866 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002867
2868 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2869
Eric Laurente552edb2014-03-10 17:42:56 -07002870 return NO_ERROR;
2871 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002872 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002873 return INVALID_OPERATION;
2874 }
2875}
2876
jiabinbce0c1d2020-10-05 11:20:18 -07002877bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002878{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002879 ALOGV("%s portId %d", __FUNCTION__, portId);
2880
2881 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2882 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002883 // If an output descriptor is closed due to a device routing change,
2884 // then there are race conditions with releaseOutput from tracks
2885 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2886 // destroyed shortly thereafter.
2887 //
2888 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002889 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002890 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002891 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002892
2893 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002894
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302895 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2896 if (outputDesc->isClientActive(client)) {
2897 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2898 stopOutput(portId);
2899 }
2900
Eric Laurent8fc147b2018-07-22 19:13:55 -07002901 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2902 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002903 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002904 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002905 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002906 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002907 if (--outputDesc->mDirectOpenCount == 0) {
2908 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002909 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002910 }
2911 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302912
Andy Hung39efb7a2018-09-26 15:39:28 -07002913 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002914 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2915 // The output is pending reopened to query dynamic profiles and
2916 // there is no active clients
2917 closeOutput(outputDesc->mIoHandle);
2918 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2919 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2920 if (newOutputDesc == nullptr) {
2921 ALOGE("%s failed to open output", __func__);
2922 }
2923 return true;
2924 }
2925 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002926}
2927
Eric Laurentcaf7f482014-11-25 17:50:47 -08002928status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2929 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002930 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002931 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002932 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002933 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002934 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002935 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002936 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002937 audio_port_handle_t *portId,
2938 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002939{
François Gaffiec005e562018-11-06 15:04:49 +01002940 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002941 "flags %#x attributes=%s requested device ID %d",
2942 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2943 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002944
Eric Laurentad2e7b92017-09-14 20:06:42 -07002945 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002946 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002947 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002948 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002949 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002950 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002951 sp<RecordClientDescriptor> clientDesc;
2952 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002953 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002954 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002955
2956 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2957 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2958 return INVALID_OPERATION;
2959 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002960
Francois Gaffie716e1432019-01-14 16:58:59 +01002961 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2962 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002963 }
2964
Paul McLean466dc8e2015-04-17 13:15:36 -06002965 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002966 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002967 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002968
Eric Laurentad2e7b92017-09-14 20:06:42 -07002969 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2970 // possible
2971 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2972 *input != AUDIO_IO_HANDLE_NONE) {
2973 ssize_t index = mInputs.indexOfKey(*input);
2974 if (index < 0) {
2975 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2976 status = BAD_VALUE;
2977 goto error;
2978 }
2979 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002980 RecordClientVector clients = inputDesc->getClientsForSession(session);
2981 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002982 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2983 status = BAD_VALUE;
2984 goto error;
2985 }
2986 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2987 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002988 // corresponds to a new client and is only permitted from the same UID.
2989 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002990 if (clients.size() > 1) {
2991 for (const auto& client : clients) {
2992 // The client map is ordered by key values (portId) and portIds are allocated
2993 // incrementaly. So the first client in this list is the one opened by audio flinger
2994 // when the mmap stream is created and should be ignored as it does not correspond
2995 // to an actual client
2996 if (client == *clients.cbegin()) {
2997 continue;
2998 }
2999 if (uid != client->uid() && !client->isSilenced()) {
3000 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
3001 uid, client->portId(), client->uid());
3002 status = INVALID_OPERATION;
3003 goto error;
3004 }
Eric Laurent331679c2018-04-16 17:03:16 -07003005 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003006 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003007 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01003008 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07003009
Eric Laurentfecbceb2021-02-09 14:46:43 +01003010 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003011 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003012 }
3013
3014 *input = AUDIO_IO_HANDLE_NONE;
3015 *inputType = API_INPUT_INVALID;
3016
Francois Gaffie716e1432019-01-14 16:58:59 +01003017 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02003018 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003019 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003020 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003021 ALOGW("%s could not find input mix for attr %s",
3022 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07003023 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01003024 }
jiabinc1de2df2019-05-07 14:26:40 -07003025 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
3026 String8(attr->tags + strlen("addr=")),
3027 AUDIO_FORMAT_DEFAULT);
3028 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07003029 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07003030 __func__, attributes.source, attributes.tags);
3031 status = BAD_VALUE;
3032 goto error;
3033 }
3034
Kevin Rocard25f9b052019-02-27 15:08:54 -08003035 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
3036 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
3037 } else {
3038 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
3039 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01003040 if (virtualDeviceId) {
3041 *virtualDeviceId = policyMix->mVirtualDeviceId;
3042 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003043 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003044 if (explicitRoutingDevice != nullptr) {
3045 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07003046 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01003047 // Prevent from storing invalid requested device id in clients
3048 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003049 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08003050 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
3051 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07003052 }
François Gaffie11d30102018-11-02 16:09:09 +01003053 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003054 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003055 status = BAD_VALUE;
3056 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08003057 }
Alden DSouzab7d20782021-02-08 08:51:42 -08003058 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
3059 *inputType = API_INPUT_MIX_CAPTURE;
3060 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01003061 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3062 // there is an external policy, but this input is attached to a mix of recorders,
3063 // meaning it receives audio injected into the framework, so the recorder doesn't
3064 // know about it and is therefore considered "legacy"
3065 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003066
3067 if (virtualDeviceId) {
3068 *virtualDeviceId = policyMix->mVirtualDeviceId;
3069 }
François Gaffie11d30102018-11-02 16:09:09 +01003070 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003071 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003072 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003073 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003074 } else {
3075 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003076 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003077
Eric Laurent599c7582015-12-07 18:05:55 -08003078 }
3079
François Gaffiec005e562018-11-06 15:04:49 +01003080 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003081 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003082 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003083 AudioProfileVector profiles;
3084 status_t ret = getProfilesForDevices(
3085 DeviceVector(device), profiles, flags, true /*isInput*/);
3086 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003087 const auto channels = profiles[0]->getChannels();
3088 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3089 config->channel_mask = *channels.begin();
3090 }
3091 const auto sampleRates = profiles[0]->getSampleRates();
3092 if (!sampleRates.empty() &&
3093 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3094 config->sample_rate = *sampleRates.begin();
3095 }
jiabinf1c73972022-04-14 16:28:52 -07003096 config->format = profiles[0]->getFormat();
3097 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003098 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003099 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003100
Marvin Ramine5a122d2023-12-07 13:57:59 +01003101
3102 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3103 *virtualDeviceId = policyMix->mVirtualDeviceId;
3104 }
3105
Eric Laurent8f42ea12018-08-08 09:08:25 -07003106exit:
3107
François Gaffiec005e562018-11-06 15:04:49 +01003108 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3109 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003110
Francois Gaffie716e1432019-01-14 16:58:59 +01003111 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003112 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003113 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003114
Mikhail Naganov2996f672019-04-18 12:29:59 -07003115 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003116 requestedDeviceId, attributes.source, flags,
3117 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003118 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003119 // Move (if found) effect for the client session to its input
3120 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003121 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003122
3123 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3124 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003125
Eric Laurent599c7582015-12-07 18:05:55 -08003126 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003127
3128error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003129 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003130}
3131
3132
François Gaffie11d30102018-11-02 16:09:09 +01003133audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003134 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003135 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003136 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003137 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003138 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003139{
3140 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003141 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003142 bool isSoundTrigger = false;
3143
François Gaffiec005e562018-11-06 15:04:49 +01003144 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003145 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3146 if (index >= 0) {
3147 input = mSoundTriggerSessions.valueFor(session);
3148 isSoundTrigger = true;
3149 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3150 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3151 } else {
3152 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003153 }
François Gaffiec005e562018-11-06 15:04:49 +01003154 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003155 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003156 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003157 }
3158
Carter Hsua3abb402021-10-26 11:11:20 +08003159 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3160 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3161 }
3162
Eric Laurentfe231122017-11-17 17:48:06 -08003163 // sampling rate and flags may be updated by getInputProfile
3164 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3165 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003166 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003167 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003168 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003169 // find a compatible input profile (not necessarily identical in parameters)
3170 sp<IOProfile> profile = getInputProfile(
3171 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3172 if (profile == nullptr) {
3173 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003174 }
jiabin2fd710d2022-05-02 23:20:22 +00003175
Glenn Kasten05ddca52016-02-11 08:17:12 -08003176 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003177 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003178 if (samplingRate == 0) {
3179 samplingRate = profileSamplingRate;
3180 }
Eric Laurente552edb2014-03-10 17:42:56 -07003181
Eric Laurent322b4d22015-04-03 15:57:54 -07003182 if (profile->getModuleHandle() == 0) {
3183 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003184 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003185 }
3186
Eric Laurentec376dc2021-04-08 20:41:22 +02003187 // Reuse an already opened input if a client with the same session ID already exists
3188 // on that input
3189 for (size_t i = 0; i < mInputs.size(); i++) {
3190 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3191 if (desc->mProfile != profile) {
3192 continue;
3193 }
3194 RecordClientVector clients = desc->clientsList();
3195 for (const auto &client : clients) {
3196 if (session == client->session()) {
3197 return desc->mIoHandle;
3198 }
3199 }
3200 }
3201
Eric Laurentc71b11b2024-06-03 12:54:53 +00003202 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003203 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003204 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3205 // First pick best candidate for preemption (there may not be any):
3206 // - Preempt and input if:
3207 // - It has only strictly lower priority use cases than the new client
3208 // - It has equal priority use cases than the new client, was not
3209 // opened thanks to preemption or has been active since opened.
3210 // - Order the preemption candidates by inactive first and priority second
3211 sp<AudioInputDescriptor> closeCandidate;
3212 int leastCloseRank = INT_MAX;
3213 static const int sCloseActive = 0x100;
3214
3215 for (size_t i = 0; i < mInputs.size(); i++) {
3216 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3217 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003218 continue;
3219 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003220 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3221 if (topPrioClient == nullptr) {
3222 continue;
3223 }
3224 int topPrio = source_priority(topPrioClient->source());
3225 if (topPrio < source_priority(attributes.source)
3226 || (topPrio == source_priority(attributes.source)
3227 && !desc->isPreemptor())) {
3228 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3229 if (closeRank < leastCloseRank) {
3230 leastCloseRank = closeRank;
3231 closeCandidate = desc;
3232 }
3233 }
3234 }
3235
3236 if (closeCandidate != nullptr) {
3237 closeInput(closeCandidate->mIoHandle);
3238 // Mark the new input as being issued from a preemption
3239 // so that is will not be preempted later
3240 isPreemptor = true;
3241 } else {
3242 // Then pick the best reusable input (There is always one)
3243 // The order of preference is:
3244 // 1) active inputs with same use case as the new client
3245 // 2) inactive inputs with same use case
3246 // 3) active inputs with different use cases
3247 // 4) inactive inputs with different use cases
3248 sp<AudioInputDescriptor> reuseCandidate;
3249 int leastReuseRank = INT_MAX;
3250 static const int sReuseDifferentUseCase = 0x100;
3251
3252 for (size_t i = 0; i < mInputs.size(); i++) {
3253 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3254 if (desc->mProfile != profile) {
3255 continue;
3256 }
3257 int reuseRank = sReuseDifferentUseCase;
3258 for (const auto& client: desc->getClientIterable()) {
3259 if (client->source() == attributes.source) {
3260 reuseRank = 0;
3261 break;
3262 }
3263 }
3264 reuseRank += desc->isActive() ? 0 : 1;
3265 if (reuseRank < leastReuseRank) {
3266 leastReuseRank = reuseRank;
3267 reuseCandidate = desc;
3268 }
3269 }
3270 return reuseCandidate->mIoHandle;
3271 }
3272 } else { // fix_input_sharing_logic()
3273 for (size_t i = 0; i < mInputs.size(); ) {
3274 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3275 if (desc->mProfile != profile) {
3276 i++;
3277 continue;
3278 }
3279 // if sound trigger, reuse input if used by other sound trigger on same session
3280 // else
3281 // reuse input if active client app is not in IDLE state
3282 //
3283 RecordClientVector clients = desc->clientsList();
3284 bool doClose = false;
3285 for (const auto& client : clients) {
3286 if (isSoundTrigger != client->isSoundTrigger()) {
3287 continue;
3288 }
3289 if (client->isSoundTrigger()) {
3290 if (session == client->session()) {
3291 return desc->mIoHandle;
3292 }
3293 continue;
3294 }
3295 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003296 return desc->mIoHandle;
3297 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003298 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003299 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003300 if (doClose) {
3301 closeInput(desc->mIoHandle);
3302 } else {
3303 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003304 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003305 }
3306 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003307 }
3308
Eric Laurentc71b11b2024-06-03 12:54:53 +00003309 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3310 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003311
Eric Laurentfe231122017-11-17 17:48:06 -08003312 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3313 lConfig.sample_rate = profileSamplingRate;
3314 lConfig.channel_mask = profileChannelMask;
3315 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003316
François Gaffie11d30102018-11-02 16:09:09 +01003317 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003318
3319 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003320 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003321 (profileSamplingRate != lConfig.sample_rate) ||
3322 !audio_formats_match(profileFormat, lConfig.format) ||
3323 (profileChannelMask != lConfig.channel_mask)) {
3324 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003325 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003326 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003327 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003328 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003329 }
Eric Laurent599c7582015-12-07 18:05:55 -08003330 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003331 }
3332
Eric Laurentc722f302014-12-10 11:21:49 -08003333 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003334
Eric Laurent599c7582015-12-07 18:05:55 -08003335 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003336 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003337
Eric Laurent599c7582015-12-07 18:05:55 -08003338 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003339}
3340
Eric Laurent4eb58f12018-12-07 16:41:02 -08003341status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003342{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003343 ALOGV("%s portId %d", __FUNCTION__, portId);
3344
3345 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3346 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003347 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003348 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003349 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003350 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003351 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003352 if (client->active()) {
3353 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3354 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003355 }
3356
Eric Laurent8f42ea12018-08-08 09:08:25 -07003357 audio_session_t session = client->session();
3358
Eric Laurent4eb58f12018-12-07 16:41:02 -08003359 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003360
Eric Laurent4eb58f12018-12-07 16:41:02 -08003361 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003362
Eric Laurent4eb58f12018-12-07 16:41:02 -08003363 status_t status = inputDesc->start();
3364 if (status != NO_ERROR) {
3365 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003366 }
Eric Laurente552edb2014-03-10 17:42:56 -07003367
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003368 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003369 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003370 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003371
Eric Laurent8f42ea12018-08-08 09:08:25 -07003372 // indicate active capture to sound trigger service if starting capture from a mic on
3373 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003374 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003375 if (device != nullptr) {
3376 status = setInputDevice(input, device, true /* force */);
3377 } else {
3378 ALOGW("%s no new input device can be found for descriptor %d",
3379 __FUNCTION__, inputDesc->getId());
3380 status = BAD_VALUE;
3381 }
Eric Laurente552edb2014-03-10 17:42:56 -07003382
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003383 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003384 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003385 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003386 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003387 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3388 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003389 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003390 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003391
François Gaffie11d30102018-11-02 16:09:09 +01003392 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3393 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003394 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003395 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003396 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003397
Eric Laurent8f42ea12018-08-08 09:08:25 -07003398 // automatically enable the remote submix output when input is started if not
3399 // used by a policy mix of type MIX_TYPE_RECORDERS
3400 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003401 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003402 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003403 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003404 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003405 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3406 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003407 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003408 if (address != "") {
3409 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3410 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003411 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003412 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003413 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003414 } else if (status != NO_ERROR) {
3415 // Restore client activity state.
3416 inputDesc->setClientActive(client, false);
3417 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003418 }
3419
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003420 ALOGV("%s input %d source = %d status = %d exit",
3421 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003422
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003423 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003424}
3425
Eric Laurent8fc147b2018-07-22 19:13:55 -07003426status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003427{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003428 ALOGV("%s portId %d", __FUNCTION__, portId);
3429
3430 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3431 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003432 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent5d837ea2024-11-15 18:56:01 +00003433 return DEAD_OBJECT;
Eric Laurente552edb2014-03-10 17:42:56 -07003434 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003435 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003436 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003437 if (!client->active()) {
3438 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003439 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003440 }
Carter Hsue6139d52021-07-08 10:30:20 +08003441 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003442 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003443
Eric Laurent8f42ea12018-08-08 09:08:25 -07003444 inputDesc->stop();
3445 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003446 auto current_source = inputDesc->source();
3447 setInputDevice(input, getNewInputDevice(inputDesc),
3448 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003449 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003450 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003451 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003452 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003453 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3454 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003455 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003456 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003457
3458 // automatically disable the remote submix output when input is stopped if not
3459 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003460 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003461 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003462 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003463 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003464 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3465 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003466 }
3467 if (address != "") {
3468 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3469 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003470 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003471 }
3472 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003473 resetInputDevice(input);
3474
3475 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3476 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003477 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3478 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003479 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003480 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003481 }
3482 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003483 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003484 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003485}
3486
Eric Laurent8fc147b2018-07-22 19:13:55 -07003487void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003488{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003489 ALOGV("%s portId %d", __FUNCTION__, portId);
3490
3491 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3492 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003493 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003494 return;
3495 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003496 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003497 audio_io_handle_t input = inputDesc->mIoHandle;
3498
Eric Laurent8f42ea12018-08-08 09:08:25 -07003499 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003500
Andy Hung39efb7a2018-09-26 15:39:28 -07003501 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003502
3503 // If no more clients are present in this session, park effects to an orphan chain
3504 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3505 if (clientsOnSession.size() == 0) {
3506 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3507 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003508 if (inputDesc->getClientCount() > 0) {
3509 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003510 return;
3511 }
3512
Eric Laurent05b90f82014-08-27 15:32:29 -07003513 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003514 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003515 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003516}
3517
Eric Laurent8f42ea12018-08-08 09:08:25 -07003518void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003519{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003520 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003521
3522 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003523 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003524 }
3525}
3526
Eric Laurent8f42ea12018-08-08 09:08:25 -07003527void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3528{
3529 stopInput(portId);
3530 releaseInput(portId);
3531}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003532
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003533bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3534 if (input->clientsList().size() == 0
3535 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3536 return true;
3537 }
3538 for (const auto& client : input->clientsList()) {
3539 sp<DeviceDescriptor> device =
3540 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3541 client->session());
3542 if (!input->supportedDevices().contains(device)) {
3543 return true;
3544 }
3545 }
3546 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3547 return false;
3548}
3549
Eric Laurent0dd51852019-04-19 18:18:58 -07003550void AudioPolicyManager::checkCloseInputs() {
3551 // After connecting or disconnecting an input device, close input if:
3552 // - it has no client (was just opened to check profile) OR
3553 // - none of its supported devices are connected anymore OR
3554 // - one of its clients cannot be routed to one of its supported
3555 // devices anymore. Otherwise update device selection
3556 std::vector<audio_io_handle_t> inputsToClose;
3557 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003558 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003559 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003560 }
3561 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003562 for (const audio_io_handle_t handle : inputsToClose) {
3563 ALOGV("%s closing input %d", __func__, handle);
3564 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003565 }
Eric Laurentd4692962014-05-05 18:13:44 -07003566}
3567
Vlad Popa87e0e582024-05-20 18:49:20 -07003568status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3569 const char *address __unused,
3570 bool enabled,
3571 audio_stream_type_t streamToDriveAbs)
3572{
Vlad Popa08502d82024-10-22 20:17:47 -07003573 ALOGI("%s: deviceType 0x%X, enabled %d, streamToDriveAbs %d", __func__, deviceType, enabled,
3574 streamToDriveAbs);
3575
Vlad Popa6319b2d2024-11-15 18:32:13 -08003576 bool changed = false;
Neha Jain7af15132024-11-16 00:47:18 +00003577 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
Vlad Popa6319b2d2024-11-15 18:32:13 -08003578 if (enabled) {
3579 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3580 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3581 toString(streamToDriveAbs).c_str());
3582 return BAD_VALUE;
3583 }
3584
Vlad Popa3d8d8942024-11-19 21:04:31 -08003585 const auto attrIt = mAbsoluteVolumeDrivingStreams.find(deviceType);
3586 if (attrIt == mAbsoluteVolumeDrivingStreams.end() ||
3587 (attrIt->second.usage != attributesToDriveAbs.usage ||
3588 attrIt->second.content_type != attributesToDriveAbs.content_type ||
3589 attrIt->second.flags != attributesToDriveAbs.flags)) {
Vlad Popa6319b2d2024-11-15 18:32:13 -08003590 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3591 changed = true;
3592 }
3593 } else {
Vlad Popa3d8d8942024-11-19 21:04:31 -08003594 if (mAbsoluteVolumeDrivingStreams.erase(deviceType) != 0) {
Vlad Popa6319b2d2024-11-15 18:32:13 -08003595 changed = true;
3596 }
Vlad Popafb0af7c2024-10-29 16:38:37 -07003597 }
3598
Vlad Popa3d8d8942024-11-19 21:04:31 -08003599 const DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3600 attributesToDriveAbs, nullptr /* preferredDevice */, true /* fromCache */);
3601 changed &= devices.types().contains(deviceType);
3602 // if something changed on the output device for the changed attributes, apply the stream
3603 // volumes regarding the new absolute mode to all the outputs without any delay
Vlad Popa6319b2d2024-11-15 18:32:13 -08003604 if (changed) {
3605 for (size_t i = 0; i < mOutputs.size(); i++) {
3606 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Vlad Popa3d8d8942024-11-19 21:04:31 -08003607 ALOGI("%s: apply stream volumes for portId %d and device type %d", __func__,
3608 desc->getId(), deviceType);
Vlad Popa6319b2d2024-11-15 18:32:13 -08003609 applyStreamVolumes(desc, {deviceType});
3610 }
3611 }
3612
Vlad Popa87e0e582024-05-20 18:49:20 -07003613 return NO_ERROR;
3614}
3615
François Gaffie251c7f02018-11-07 10:41:08 +01003616void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003617{
3618 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003619 if (indexMin < 0 || indexMax < 0) {
3620 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3621 return;
3622 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003623 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003624
3625 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003626 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3627 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003628 continue;
3629 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003630 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003631 }
Eric Laurente552edb2014-03-10 17:42:56 -07003632}
3633
Eric Laurente0720872014-03-11 09:30:41 -07003634status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003635 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003636 bool muted,
François Gaffie53615e22015-03-19 09:24:12 +01003637 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003638{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003639 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003640 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3641 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3642 return NO_ERROR;
3643 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303644 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3645 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Vlad Popa1e865e62024-08-15 19:11:42 -07003646 return setVolumeIndexForAttributes(attributes, index, muted, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003647}
3648
Eric Laurente0720872014-03-11 09:30:41 -07003649status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003650 int *index,
3651 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003652{
François Gaffiec005e562018-11-06 15:04:49 +01003653 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3654 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003655 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003656 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003657 deviceTypes = mEngine->getOutputDevicesForStream(
3658 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003659 }
jiabin9a3361e2019-10-01 09:38:30 -07003660 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003661}
3662
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003663status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003664 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003665 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003666 audio_devices_t device)
3667{
3668 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003669 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3670 if (group == VOLUME_GROUP_NONE) {
3671 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003672 return BAD_VALUE;
3673 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003674 ALOGV("%s: group %d matching with %s index %d",
3675 __FUNCTION__, group, toString(attributes).c_str(), index);
Eric Laurentc86a3e12024-10-10 14:26:43 +00003676 if (mEngine->getStreamTypeForAttributes(attributes) == AUDIO_STREAM_PATCH) {
3677 ALOGV("%s: cannot change volume for PATCH stream, attrs: %s",
3678 __FUNCTION__, toString(attributes).c_str());
3679 return NO_ERROR;
3680 }
François Gaffiecfe17322018-11-07 13:41:29 +01003681 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003682 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003683 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003684 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3685 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3686 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3687 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003688 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3689
Vlad Popa1e865e62024-08-15 19:11:42 -07003690
3691 status = setVolumeCurveIndex(index, muted, device, curves);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003692 if (status != NO_ERROR) {
3693 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3694 return status;
3695 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003696
jiabin9a3361e2019-10-01 09:38:30 -07003697 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003698 auto curCurvAttrs = curves.getAttributes();
3699 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3700 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003701 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003702 } else if (!curves.getStreamTypes().empty()) {
3703 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003704 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003705 } else {
3706 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3707 return BAD_VALUE;
3708 }
jiabin9a3361e2019-10-01 09:38:30 -07003709 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3710 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003711
François Gaffiecfe17322018-11-07 13:41:29 +01003712 // update volume on all outputs and streams matching the following:
3713 // - The requested stream (or a stream matching for volume control) is active on the output
3714 // - The device (or devices) selected by the engine for this stream includes
3715 // the requested device
3716 // - For non default requested device, currently selected device on the output is either the
3717 // requested device or one of the devices selected by the engine for this stream
3718 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3719 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003720 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003721 for (size_t i = 0; i < mOutputs.size(); i++) {
3722 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003723 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003724
jiabin9a3361e2019-10-01 09:38:30 -07003725 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3726 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003727 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003728
3729 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003730 continue;
3731 }
3732 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3733 curDevices.find(device) == curDevices.end()) {
3734 continue;
3735 }
3736 bool applyVolume = false;
3737 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3738 curSrcDevices.insert(device);
3739 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003740 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3741 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003742 } else {
3743 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3744 }
3745 if (!applyVolume) {
3746 continue; // next output
3747 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003748 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3749 // If a higher priority strategy is active, and the output is routed to a device with a
3750 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003751 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003752 applyVolume = false;
Vlad Popa1e865e62024-08-15 19:11:42 -07003753 bool swMute = com_android_media_audio_ring_my_car() ? curves.isMuted() : (index == 0);
Francois Gaffie593634d2021-06-22 13:31:31 +02003754 // If the volume source is active with higher priority source, ensure at least Sw Muted
Vlad Popa1e865e62024-08-15 19:11:42 -07003755 desc->setSwMute(swMute, vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003756 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3757 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3758 false /*preferredDevice*/);
3759 if (activeClients.empty()) {
3760 continue;
3761 }
3762 bool isPreempted = false;
3763 bool isHigherPriority = productStrategy < strategy;
3764 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003765 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003766 ALOGV("%s: Strategy=%d (\nrequester:\n"
3767 " group %d, volumeGroup=%d attributes=%s)\n"
3768 " higher priority source active:\n"
3769 " volumeGroup=%d attributes=%s) \n"
3770 " on output %zu, bailing out", __func__, productStrategy,
3771 group, group, toString(attributes).c_str(),
3772 client->volumeSource(), toString(client->attributes()).c_str(), i);
3773 applyVolume = false;
3774 isPreempted = true;
3775 break;
3776 }
3777 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003778 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003779 applyVolume = true;
3780 }
3781 }
3782 if (isPreempted || applyVolume) {
3783 break;
3784 }
3785 }
3786 if (!applyVolume) {
3787 continue; // next output
3788 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003789 }
François Gaffieed91f582020-01-31 10:35:37 +01003790 //FIXME: workaround for truncated touch sounds
3791 // delayed volume change for system stream to be removed when the problem is
3792 // handled by system UI
Vlad Popa1e865e62024-08-15 19:11:42 -07003793 status_t volStatus = checkAndSetVolume(curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003794 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003795 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3796 if (volStatus != NO_ERROR) {
3797 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003798 }
3799 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003800
3801 // update voice volume if the an active call route exists
3802 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3803 && (curSrcDevices.find(
3804 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3805 != curSrcDevices.end())) {
3806 bool isVoiceVolSrc;
3807 bool isBtScoVolSrc;
3808 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3809 isVoiceVolSrc, isBtScoVolSrc, __func__)
3810 && (isVoiceVolSrc || isBtScoVolSrc)) {
Vlad Popad80ed572024-11-06 18:28:17 -08003811 bool voiceVolumeManagedByHost = !isBtScoVolSrc &&
chenxin2095559032024-06-15 13:59:29 +08003812 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3813 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003814 }
3815 }
3816
François Gaffiecfe17322018-11-07 13:41:29 +01003817 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3818 return status;
3819}
3820
François Gaffieaaac0fd2018-11-22 17:56:39 +01003821status_t AudioPolicyManager::setVolumeCurveIndex(int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003822 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003823 audio_devices_t device,
3824 IVolumeCurves &volumeCurves)
3825{
3826 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3827 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003828 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3829 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003830 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303831 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3832 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003833 return BAD_VALUE;
3834 }
3835 if (!audio_is_output_device(device)) {
3836 return BAD_VALUE;
3837 }
3838
3839 // Force max volume if stream cannot be muted
3840 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3841
Vlad Popa1e865e62024-08-15 19:11:42 -07003842 ALOGV("%s device %08x, index %d, muted %d", __FUNCTION__ , device, index, muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003843 volumeCurves.addCurrentVolumeIndex(device, index);
Vlad Popa1e865e62024-08-15 19:11:42 -07003844 volumeCurves.setIsMuted(muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003845 return NO_ERROR;
3846}
3847
3848status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3849 int &index,
3850 audio_devices_t device)
3851{
3852 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3853 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003854 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003855 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003856 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003857 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003858 }
jiabin9a3361e2019-10-01 09:38:30 -07003859 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003860}
3861
3862status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3863 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003864 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003865{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003866 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003867 return BAD_VALUE;
3868 }
jiabin9a3361e2019-10-01 09:38:30 -07003869 index = curves.getVolumeIndex(deviceTypes);
3870 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003871 return NO_ERROR;
3872}
3873
3874status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3875 int &index)
3876{
3877 index = getVolumeCurves(attr).getVolumeIndexMin();
3878 return NO_ERROR;
3879}
3880
3881status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3882 int &index)
3883{
3884 index = getVolumeCurves(attr).getVolumeIndexMax();
3885 return NO_ERROR;
3886}
3887
Eric Laurent36829f92017-04-07 19:04:42 -07003888audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003889{
3890 // select one output among several suitable for global effects.
3891 // The priority is as follows:
3892 // 1: An offloaded output. If the effect ends up not being offloadable,
3893 // AudioFlinger will invalidate the track and the offloaded output
3894 // will be closed causing the effect to be moved to a PCM output.
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003895 // 2: Spatializer output if the stereo spatializer feature enabled
3896 // 3: A deep buffer output
3897 // 4: The primary output
3898 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003899
François Gaffiec005e562018-11-06 15:04:49 +01003900 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3901 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003902 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003903
Eric Laurent36829f92017-04-07 19:04:42 -07003904 if (outputs.size() == 0) {
3905 return AUDIO_IO_HANDLE_NONE;
3906 }
Eric Laurente552edb2014-03-10 17:42:56 -07003907
Eric Laurent36829f92017-04-07 19:04:42 -07003908 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3909 bool activeOnly = true;
3910
3911 while (output == AUDIO_IO_HANDLE_NONE) {
3912 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003913 audio_io_handle_t outputSpatializer = AUDIO_IO_HANDLE_NONE;
Eric Laurent36829f92017-04-07 19:04:42 -07003914 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3915 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3916
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003917 for (audio_io_handle_t outputLoop : outputs) {
3918 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputLoop);
Eric Laurent83d17c22019-04-02 17:10:01 -07003919 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003920 continue;
3921 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003922 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003923 activeOnly, outputLoop, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003924 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003925 outputOffloaded = outputLoop;
3926 }
3927 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
3928 if (SpatializerHelper::isStereoSpatializationFeatureEnabled()) {
3929 outputSpatializer = outputLoop;
3930 }
Eric Laurent36829f92017-04-07 19:04:42 -07003931 }
3932 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003933 outputDeepBuffer = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003934 }
3935 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003936 outputPrimary = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003937 }
3938 }
3939 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3940 output = outputOffloaded;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003941 } else if (outputSpatializer != AUDIO_IO_HANDLE_NONE) {
3942 output = outputSpatializer;
Eric Laurent36829f92017-04-07 19:04:42 -07003943 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3944 output = outputDeepBuffer;
3945 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3946 output = outputPrimary;
3947 } else {
3948 output = outputs[0];
3949 }
3950 activeOnly = false;
3951 }
3952
3953 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003954 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3955 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003956 mMusicEffectOutput = output;
3957 }
3958
3959 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003960 return output;
3961}
3962
Eric Laurent36829f92017-04-07 19:04:42 -07003963audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3964{
3965 return selectOutputForMusicEffects();
3966}
3967
Eric Laurente0720872014-03-11 09:30:41 -07003968status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003969 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003970 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003971 int session,
3972 int id)
3973{
Shunkai Yao29d10572024-03-19 04:31:47 +00003974 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003975 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003976 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003977 index = mInputs.indexOfKey(io);
3978 if (index < 0) {
3979 ALOGW("registerEffect() unknown io %d", io);
3980 return INVALID_OPERATION;
3981 }
Eric Laurente552edb2014-03-10 17:42:56 -07003982 }
3983 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003984 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3985 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3986 || strategy == PRODUCT_STRATEGY_NONE));
3987 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003988}
3989
Eric Laurentc241b0d2018-11-28 09:08:49 -08003990status_t AudioPolicyManager::unregisterEffect(int id)
3991{
3992 if (mEffects.getEffect(id) == nullptr) {
3993 return INVALID_OPERATION;
3994 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003995 if (mEffects.isEffectEnabled(id)) {
3996 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3997 setEffectEnabled(id, false);
3998 }
3999 return mEffects.unregisterEffect(id);
4000}
4001
4002status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
4003{
4004 sp<EffectDescriptor> effect = mEffects.getEffect(id);
4005 if (effect == nullptr) {
4006 return INVALID_OPERATION;
4007 }
4008
4009 status_t status = mEffects.setEffectEnabled(id, enabled);
4010 if (status == NO_ERROR) {
4011 mInputs.trackEffectEnabled(effect, enabled);
4012 }
4013 return status;
4014}
4015
Eric Laurent6c796322019-04-09 14:13:17 -07004016
4017status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
4018{
4019 mEffects.moveEffects(ids, io);
4020 return NO_ERROR;
4021}
4022
Eric Laurentc75307b2015-03-17 15:29:32 -07004023bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
4024{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01004025 auto vs = toVolumeSource(stream, false);
4026 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07004027}
4028
4029bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
4030{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01004031 auto vs = toVolumeSource(stream, false);
4032 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07004033}
4034
Eric Laurente0720872014-03-11 09:30:41 -07004035bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07004036{
4037 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004038 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08004039 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004040 return true;
4041 }
4042 }
4043 return false;
4044}
4045
Eric Laurent275e8e92014-11-30 15:14:47 -08004046// Register a list of custom mixes with their attributes and format.
4047// When a mix is registered, corresponding input and output profiles are
4048// added to the remote submix hw module. The profile contains only the
4049// parameters (sampling rate, format...) specified by the mix.
4050// The corresponding input remote submix device is also connected.
4051//
4052// When a remote submix device is connected, the address is checked to select the
4053// appropriate profile and the corresponding input or output stream is opened.
4054//
4055// When capture starts, getInputForAttr() will:
4056// - 1 look for a mix matching the address passed in attribtutes tags if any
4057// - 2 if none found, getDeviceForInputSource() will:
4058// - 2.1 look for a mix matching the attributes source
4059// - 2.2 if none found, default to device selection by policy rules
4060// At this time, the corresponding output remote submix device is also connected
4061// and active playback use cases can be transferred to this mix if needed when reconnecting
4062// after AudioTracks are invalidated
4063//
4064// When playback starts, getOutputForAttr() will:
4065// - 1 look for a mix matching the address passed in attribtutes tags if any
4066// - 2 if none found, look for a mix matching the attributes usage
4067// - 3 if none found, default to device and output selection by policy rules.
4068
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004069status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08004070{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004071 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
4072 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004073 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004074 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01004075 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004076 // examine each mix's route type
4077 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004078 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08004079 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
4080 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
4081 ALOGE("Unsupported Policy Mix %zu of %zu: "
4082 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
4083 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004084 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08004085 break;
4086 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08004087 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
4088 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07004089 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004090 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
4091 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004092 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004093 rSubmixModule = mHwModules.getModuleFromName(
4094 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4095 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004096 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08004097 i);
4098 res = INVALID_OPERATION;
4099 break;
4100 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004101 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004102
Eric Laurent97ac8712018-07-27 18:59:02 -07004103 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004104 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004105 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004106 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004107 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4108 } else {
4109 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4110 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004111 }
François Gaffie036e1e92015-03-19 10:16:24 +01004112
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004113 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004114 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004115 res = INVALID_OPERATION;
4116 break;
4117 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004118 audio_config_t outputConfig = mix.mFormat;
4119 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004120 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4121 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004122 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4123 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004124 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004125 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4126 audio_is_linear_pcm(outputConfig.format)
4127 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004128 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004129 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4130 audio_is_linear_pcm(inputConfig.format)
4131 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004132
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004133 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004134 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004135 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004136 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004137 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004138 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004139 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004140 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4141 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004142 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004143 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004144 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004145
4146 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4147 mix.mDeviceType, mix.mDeviceAddress,
4148 String8(), AUDIO_FORMAT_DEFAULT);
4149 if (device == nullptr) {
4150 res = INVALID_OPERATION;
4151 break;
4152 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004153
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004154 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004155 // First try to find an already opened output supporting the device
4156 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004157 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004158
Eric Laurentc529cf62020-04-17 18:19:10 -07004159 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004160 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004161 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004162 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004163 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004164 } else {
4165 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004166 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004167 }
4168 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004169 // If no output found, try to find a direct output profile supporting the device
4170 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4171 sp<HwModule> module = mHwModules[i];
4172 for (size_t j = 0;
4173 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4174 j++) {
4175 sp<IOProfile> profile = module->getOutputProfiles()[j];
4176 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4177 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4178 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004179 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004180 res = INVALID_OPERATION;
4181 } else {
4182 foundOutput = true;
4183 }
4184 }
4185 }
4186 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004187 if (res != NO_ERROR) {
4188 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004189 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004190 res = INVALID_OPERATION;
4191 break;
4192 } else if (!foundOutput) {
4193 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004194 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004195 res = INVALID_OPERATION;
4196 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004197 } else {
4198 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004199 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004200 }
Eric Laurentc722f302014-12-10 11:21:49 -08004201 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004202 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004203 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004204 if (audio_flags::audio_mix_ownership()) {
4205 // Only unregister mixes that were actually registered to not accidentally unregister
4206 // mixes that already existed previously.
4207 unregisterPolicyMixes(registeredMixes);
4208 registeredMixes.clear();
4209 } else {
4210 unregisterPolicyMixes(mixes);
4211 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004212 } else if (checkOutputs) {
4213 checkForDeviceAndOutputChanges();
4214 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004215 }
4216 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004217}
4218
4219status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4220{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004221 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004222 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004223 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004224 sp<HwModule> rSubmixModule;
4225 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004226 for (const auto& mix : mixes) {
4227 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004228
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004229 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004230 rSubmixModule = mHwModules.getModuleFromName(
4231 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4232 if (rSubmixModule == 0) {
4233 res = INVALID_OPERATION;
4234 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004235 }
4236 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004237
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004238 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004239
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004240 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004241 res = INVALID_OPERATION;
4242 continue;
4243 }
4244
Marvin Ramin0783e202024-03-05 12:45:50 +01004245 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004246 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004247 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4248 status_t currentRes =
4249 setDeviceConnectionStateInt(device,
4250 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4251 address.c_str(),
4252 "remote-submix",
4253 AUDIO_FORMAT_DEFAULT);
4254 if (!audio_flags::audio_mix_ownership()) {
4255 res = currentRes;
4256 }
4257 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004258 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004259 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004260 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004261 }
4262 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004263 }
jiabin5740f082019-08-19 15:08:30 -07004264 rSubmixModule->removeOutputProfile(address.c_str());
4265 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004266
Kevin Rocard153f92d2018-12-18 18:33:28 -08004267 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004268 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004269 res = INVALID_OPERATION;
4270 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004271 } else {
4272 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004273 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004274 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004275 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004276
4277 if (res == NO_ERROR && checkOutputs) {
4278 checkForDeviceAndOutputChanges();
4279 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004280 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004281 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004282}
4283
Marvin Raminbdefaf02023-11-01 09:10:32 +01004284status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4285 if (!audio_flags::audio_mix_test_api()) {
4286 return INVALID_OPERATION;
4287 }
4288
4289 _aidl_return.clear();
4290 _aidl_return.reserve(mPolicyMixes.size());
4291 for (const auto &policyMix: mPolicyMixes) {
4292 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4293 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4294 policyMix->mCbFlags);
4295 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004296 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004297 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004298 }
4299
Vlad Popaa5d73f32024-03-08 16:05:38 -08004300 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004301 return OK;
4302}
4303
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004304status_t AudioPolicyManager::updatePolicyMix(
4305 const AudioMix& mix,
4306 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4307 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4308 if (res == NO_ERROR) {
4309 checkForDeviceAndOutputChanges();
4310 updateCallAndOutputRouting();
4311 }
4312 return res;
4313}
4314
Mikhail Naganov100f0122018-11-29 11:22:16 -08004315void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4316{
4317 size_t i = 0;
4318 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4319 for (const auto& fmt : mManualSurroundFormats) {
4320 if (i++ != 0) dst->append(", ");
4321 std::string sfmt;
4322 FormatConverter::toString(fmt, sfmt);
4323 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4324 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4325 }
4326}
4327
Eric Laurentc529cf62020-04-17 18:19:10 -07004328// Returns true if all devices types match the predicate and are supported by one HW module
4329bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004330 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004331 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004332 const char *context,
4333 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004334 for (size_t i = 0; i < devices.size(); i++) {
4335 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004336 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004337 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004338 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004339 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004340 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004341 return false;
4342 }
4343 }
4344 return true;
4345}
4346
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004347void AudioPolicyManager::changeOutputDevicesMuteState(
4348 const AudioDeviceTypeAddrVector& devices) {
4349 ALOGVV("%s() num devices %zu", __func__, devices.size());
4350
4351 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4352 getSoftwareOutputsForDevices(devices);
4353
4354 for (size_t i = 0; i < outputs.size(); i++) {
4355 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4356 DeviceVector prevDevices = outputDesc->devices();
4357 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4358 }
4359}
4360
4361std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4362 const AudioDeviceTypeAddrVector& devices) const
4363{
4364 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4365 DeviceVector deviceDescriptors;
4366 for (size_t j = 0; j < devices.size(); j++) {
4367 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4368 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4369 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4370 ALOGE("%s: device type %#x address %s not supported or not an output device",
4371 __func__, devices[j].mType, devices[j].getAddress());
4372 continue;
4373 }
4374 deviceDescriptors.add(desc);
4375 }
4376 for (size_t i = 0; i < mOutputs.size(); i++) {
4377 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4378 continue;
4379 }
4380 outputs.push_back(mOutputs.valueAt(i));
4381 }
4382 return outputs;
4383}
4384
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004385status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004386 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004387 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004388 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4389 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004390 }
4391 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004392 if (res != NO_ERROR) {
4393 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4394 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004395 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004396
4397 checkForDeviceAndOutputChanges();
4398 updateCallAndOutputRouting();
4399
4400 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004401}
4402
4403status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4404 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004405 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4406 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004407 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004408 __FUNCTION__, uid);
4409 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004410 }
4411
Eric Laurentc529cf62020-04-17 18:19:10 -07004412 checkForDeviceAndOutputChanges();
4413 updateCallAndOutputRouting();
4414
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004415 return res;
4416}
4417
Eric Laurent2517af32020-11-25 15:31:27 +01004418
jiabin0a488932020-08-07 17:32:40 -07004419status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4420 device_role_t role,
4421 const AudioDeviceTypeAddrVector &devices) {
4422 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4423 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004424
Eric Laurentc529cf62020-04-17 18:19:10 -07004425 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004426 return BAD_VALUE;
4427 }
jiabin0a488932020-08-07 17:32:40 -07004428 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004429 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004430 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4431 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004432 return status;
4433 }
4434
4435 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004436
4437 bool forceVolumeReeval = false;
4438 // FIXME: workaround for truncated touch sounds
4439 // to be removed when the problem is handled by system UI
4440 uint32_t delayMs = 0;
4441 if (strategy == mCommunnicationStrategy) {
4442 forceVolumeReeval = true;
4443 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4444 updateInputRouting();
4445 }
4446 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004447
4448 return NO_ERROR;
4449}
4450
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004451void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4452 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004453{
4454 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004455 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004456 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004457 // Only apply special touch sound delay once
4458 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004459 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004460 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004461 for (size_t i = 0; i < mOutputs.size(); i++) {
4462 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4463 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004464 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4465 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004466 // As done in setDeviceConnectionState, we could also fix default device issue by
4467 // preventing the force re-routing in case of default dev that distinguishes on address.
4468 // Let's give back to engine full device choice decision however.
jiabin2361ed82024-09-20 17:36:31 +00004469 bool newDevicesNotEmpty = !newDevices.isEmpty();
4470 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()
4471 && newDevicesNotEmpty) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004472 // If the device is using preferred mixer attributes, the output need to reopen
4473 // with default configuration when the new selected devices are different from
4474 // current routing devices.
4475 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4476 continue;
4477 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304478
jiabin2361ed82024-09-20 17:36:31 +00004479 waitMs = setOutputDevices(__func__, outputDesc, newDevices,
4480 newDevicesNotEmpty /*force*/, delayMs,
4481 nullptr /*patchHandle*/, !skipDelays /*requiresMuteCheck*/,
4482 !newDevicesNotEmpty /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004483 // Only apply special touch sound delay once
4484 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004485 }
4486 if (forceVolumeReeval && !newDevices.isEmpty()) {
4487 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4488 }
4489 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004490 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004491 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004492}
4493
Eric Laurent2517af32020-11-25 15:31:27 +01004494void AudioPolicyManager::updateInputRouting() {
4495 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304496 // Skip for hotword recording as the input device switch
4497 // is handled within sound trigger HAL
4498 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4499 continue;
4500 }
Eric Laurent2517af32020-11-25 15:31:27 +01004501 auto newDevice = getNewInputDevice(activeDesc);
4502 // Force new input selection if the new device can not be reached via current input
4503 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4504 setInputDevice(activeDesc->mIoHandle, newDevice);
4505 } else {
4506 closeInput(activeDesc->mIoHandle);
4507 }
4508 }
4509}
4510
Paul Wang5d7cdb52022-11-22 09:45:06 +00004511status_t
4512AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4513 device_role_t role,
4514 const AudioDeviceTypeAddrVector &devices) {
4515 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4516 dumpAudioDeviceTypeAddrVector(devices).c_str());
4517
Eric Laurent78fedbf2023-03-09 14:40:44 +01004518 if (!areAllDevicesSupported(
4519 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004520 return BAD_VALUE;
4521 }
4522 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4523 if (status != NO_ERROR) {
4524 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4525 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4526 return status;
4527 }
4528
4529 checkForDeviceAndOutputChanges();
4530
4531 bool forceVolumeReeval = false;
4532 // TODO(b/263479999): workaround for truncated touch sounds
4533 // to be removed when the problem is handled by system UI
4534 uint32_t delayMs = 0;
4535 if (strategy == mCommunnicationStrategy) {
4536 forceVolumeReeval = true;
4537 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4538 updateInputRouting();
4539 }
4540 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4541
4542 return NO_ERROR;
4543}
4544
4545status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4546 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004547{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004548 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004549
Paul Wang5d7cdb52022-11-22 09:45:06 +00004550 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004551 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004552 ALOGW_IF(status != NAME_NOT_FOUND,
4553 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004554 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004555 return status;
4556 }
4557
4558 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004559
4560 bool forceVolumeReeval = false;
4561 // FIXME: workaround for truncated touch sounds
4562 // to be removed when the problem is handled by system UI
4563 uint32_t delayMs = 0;
4564 if (strategy == mCommunnicationStrategy) {
4565 forceVolumeReeval = true;
4566 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4567 updateInputRouting();
4568 }
4569 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004570
4571 return NO_ERROR;
4572}
4573
jiabin0a488932020-08-07 17:32:40 -07004574status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4575 device_role_t role,
4576 AudioDeviceTypeAddrVector &devices) {
4577 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004578}
4579
Jiabin Huang3b98d322020-09-03 17:54:16 +00004580status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4581 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4582 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4583 dumpAudioDeviceTypeAddrVector(devices).c_str());
4584
Mikhail Naganov55773032020-10-01 15:08:13 -07004585 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004586 return BAD_VALUE;
4587 }
4588 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4589 ALOGW_IF(status != NO_ERROR,
4590 "Engine could not set preferred devices %s for audio source %d role %d",
4591 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4592
Wenyu Zhang47655d22024-10-01 12:24:53 +00004593 if (status == NO_ERROR) {
4594 updateInputRouting();
4595 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004596 return status;
4597}
4598
4599status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4600 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4601 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4602 dumpAudioDeviceTypeAddrVector(devices).c_str());
4603
Mikhail Naganov55773032020-10-01 15:08:13 -07004604 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004605 return BAD_VALUE;
4606 }
4607 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4608 ALOGW_IF(status != NO_ERROR,
4609 "Engine could not add preferred devices %s for audio source %d role %d",
4610 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4611
Eric Laurent2517af32020-11-25 15:31:27 +01004612 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004613 return status;
4614}
4615
4616status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4617 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4618{
4619 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4620 dumpAudioDeviceTypeAddrVector(devices).c_str());
4621
Eric Laurent78fedbf2023-03-09 14:40:44 +01004622 if (!areAllDevicesSupported(
4623 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004624 return BAD_VALUE;
4625 }
4626
4627 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4628 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004629 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004630 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004631 if (status == NO_ERROR) {
4632 updateInputRouting();
4633 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004634 return status;
4635}
4636
4637status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4638 device_role_t role) {
4639 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4640
4641 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004642 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004643 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004644 if (status == NO_ERROR) {
4645 updateInputRouting();
4646 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004647 return status;
4648}
4649
4650status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4651 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4652 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4653}
4654
Oscar Azucena90e77632019-11-27 17:12:28 -08004655status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004656 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004657 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004658 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4659 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004660 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004661 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4662 if (status != NO_ERROR) {
4663 ALOGE("%s() could not set device affinity for userId %d",
4664 __FUNCTION__, userId);
4665 return status;
4666 }
4667
4668 // reevaluate outputs for all devices
4669 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004670 changeOutputDevicesMuteState(devices);
4671 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4672 true /* skipDelays */);
4673 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004674
4675 return NO_ERROR;
4676}
4677
4678status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004679 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004680 AudioDeviceTypeAddrVector devices;
4681 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004682 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4683 if (status != NO_ERROR) {
4684 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4685 __FUNCTION__, userId);
4686 return status;
4687 }
4688
4689 // reevaluate outputs for all devices
4690 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004691 changeOutputDevicesMuteState(devices);
4692 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4693 true /* skipDelays */);
4694 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004695
4696 return NO_ERROR;
4697}
4698
Andy Hungc29d82b2018-10-05 12:23:17 -07004699void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004700{
Andy Hungc29d82b2018-10-05 12:23:17 -07004701 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004702 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004703 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004704 std::string stateLiteral;
4705 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004706 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004707 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4708 "communications", "media", "record", "dock", "system",
4709 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4710 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4711 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004712 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4713 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4714 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4715 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4716 dst->append(" (MANUAL: ");
4717 dumpManualSurroundFormats(dst);
4718 dst->append(")");
4719 }
4720 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004721 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004722 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4723 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004724 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004725 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004726
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004727 dst->append("\n");
4728 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4729 dst->append("\n");
4730 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004731 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004732 mOutputs.dump(dst);
4733 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004734 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004735 mAudioPatches.dump(dst);
4736 mPolicyMixes.dump(dst);
4737 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004738
Kevin Rocardb99cc752019-03-21 20:52:24 -07004739 dst->appendFormat(" AllowedCapturePolicies:\n");
4740 for (auto& policy : mAllowedCapturePolicies) {
4741 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4742 }
4743
jiabina84c3d32022-12-02 18:59:55 +00004744 dst->appendFormat(" Preferred mixer audio configuration:\n");
4745 for (const auto it : mPreferredMixerAttrInfos) {
4746 dst->appendFormat(" - device port id: %d\n", it.first);
4747 for (const auto preferredMixerInfoIt : it.second) {
4748 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4749 preferredMixerInfoIt.second->dump(dst);
4750 }
4751 }
4752
François Gaffiec005e562018-11-06 15:04:49 +01004753 dst->appendFormat("\nPolicy Engine dump:\n");
4754 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004755
4756 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4757 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4758 dst->appendFormat(" - device type: %s, driving stream %d\n",
4759 dumpDeviceTypes({it.first}).c_str(),
4760 mEngine->getVolumeGroupForAttributes(it.second));
4761 }
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00004762
4763 // dump mmap policy by device
4764 dst->appendFormat("\nMmap policy:\n");
4765 for (const auto& [policyType, policyByDevice] : mMmapPolicyByDeviceType) {
4766 std::stringstream ss;
4767 ss << '{';
4768 for (const auto& [deviceType, policy] : policyByDevice) {
4769 ss << deviceType.toString() << ":" << toString(policy) << " ";
4770 }
4771 ss << '}';
4772 dst->appendFormat(" - %s: %s\n", toString(policyType).c_str(), ss.str().c_str());
4773 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004774}
4775
4776status_t AudioPolicyManager::dump(int fd)
4777{
4778 String8 result;
4779 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004780 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004781 return NO_ERROR;
4782}
4783
Kevin Rocardb99cc752019-03-21 20:52:24 -07004784status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4785{
4786 mAllowedCapturePolicies[uid] = capturePolicy;
4787 return NO_ERROR;
4788}
4789
Eric Laurente552edb2014-03-10 17:42:56 -07004790// This function checks for the parameters which can be offloaded.
4791// This can be enhanced depending on the capability of the DSP and policy
4792// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004793audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004794{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004795 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004796 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004797 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004798 offloadInfo.format,
4799 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4800 offloadInfo.has_video);
4801
jiabin2b9d5a12021-12-10 01:06:29 +00004802 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004803 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004804 }
4805
4806 // See if there is a profile to support this.
4807 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004808 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004809 offloadInfo.sample_rate,
4810 offloadInfo.format,
4811 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004812 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4813 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004814 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4815 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4816 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004817 if (profile == nullptr) {
4818 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4819 }
4820 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4821 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4822 }
4823 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004824}
4825
Michael Chana94fbb22018-04-24 14:31:19 +10004826bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4827 const audio_attributes_t& attributes) {
4828 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004829 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004830 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4831 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004832 config.sample_rate,
4833 config.format,
4834 config.channel_mask,
4835 output_flags,
4836 true /* directOnly */);
4837 ALOGV("%s() profile %sfound with name: %s, "
4838 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4839 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004840 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004841 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004842
4843 // also try the MSD module if compatible profile not found
4844 if (profile == nullptr) {
4845 profile = getMsdProfileForOutput(outputDevices,
4846 config.sample_rate,
4847 config.format,
4848 config.channel_mask,
4849 output_flags,
4850 true /* directOnly */);
4851 ALOGV("%s() MSD profile %sfound with name: %s, "
4852 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4853 __FUNCTION__, profile != 0 ? "" : "NOT ",
4854 (profile != 0 ? profile->getTagName().c_str() : "null"),
4855 config.sample_rate, config.format, config.channel_mask, output_flags);
4856 }
4857 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004858}
4859
jiabin2b9d5a12021-12-10 01:06:29 +00004860bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4861 bool durationIgnored) {
4862 if (mMasterMono) {
4863 return false; // no offloading if mono is set.
4864 }
4865
4866 // Check if offload has been disabled
4867 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4868 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4869 return false;
4870 }
4871
4872 // Check if stream type is music, then only allow offload as of now.
4873 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4874 {
4875 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4876 return false;
4877 }
4878
4879 //TODO: enable audio offloading with video when ready
4880 const bool allowOffloadWithVideo =
4881 property_get_bool("audio.offload.video", false /* default_value */);
4882 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4883 ALOGV("%s: has_video == true, returning false", __func__);
4884 return false;
4885 }
4886
4887 //If duration is less than minimum value defined in property, return false
4888 const int min_duration_secs = property_get_int32(
4889 "audio.offload.min.duration.secs", -1 /* default_value */);
4890 if (!durationIgnored) {
4891 if (min_duration_secs >= 0) {
4892 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4893 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4894 __func__, min_duration_secs);
4895 return false;
4896 }
4897 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4898 ALOGV("%s: Offload denied by duration < default min(=%u)",
4899 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4900 return false;
4901 }
4902 }
4903
4904 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4905 // creating an offloaded track and tearing it down immediately after start when audioflinger
4906 // detects there is an active non offloadable effect.
4907 // FIXME: We should check the audio session here but we do not have it in this context.
4908 // This may prevent offloading in rare situations where effects are left active by apps
4909 // in the background.
4910 if (mEffects.isNonOffloadableEffectEnabled()) {
4911 return false;
4912 }
4913
4914 return true;
4915}
4916
4917audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4918 const audio_config_t *config) {
4919 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4920 offloadInfo.format = config->format;
4921 offloadInfo.sample_rate = config->sample_rate;
4922 offloadInfo.channel_mask = config->channel_mask;
4923 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4924 offloadInfo.has_video = false;
4925 offloadInfo.is_streaming = false;
4926 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4927
4928 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4929 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4930 audio_flags_to_audio_output_flags(attr->flags, &flags);
4931 // only retain flags that will drive compressed offload or passthrough
4932 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4933 if (offloadPossible) {
4934 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4935 }
4936 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4937
Dorin Drimusfae3c642022-03-17 18:36:30 +01004938 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin8a096672024-09-18 18:20:24 +00004939 if (std::any_of(engineOutputDevices.begin(), engineOutputDevices.end(),
4940 [this, attr](sp<DeviceDescriptor> device) {
4941 return getPreferredMixerAttributesInfo(
4942 device->getId(),
4943 mEngine->getProductStrategyForAttributes(*attr),
4944 true /*activeBitPerfectPreferred*/) != nullptr;
4945 })) {
4946 // Bit-perfect playback is active on one of the selected devices, direct output will
4947 // be rejected at this instant.
4948 return AUDIO_DIRECT_NOT_SUPPORTED;
4949 }
jiabin2b9d5a12021-12-10 01:06:29 +00004950 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004951 DeviceVector outputDevices = engineOutputDevices;
4952 // the MSD module checks for different conditions and output devices
4953 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4954 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4955 continue;
4956 }
4957 outputDevices = getMsdAudioOutDevices();
4958 }
jiabin2b9d5a12021-12-10 01:06:29 +00004959 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004960 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004961 config->sample_rate, nullptr /*updatedSamplingRate*/,
4962 config->format, nullptr /*updatedFormat*/,
4963 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004964 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004965 continue;
4966 }
4967 // reject profiles not corresponding to a device currently available
4968 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4969 continue;
4970 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004971 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4972 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004973 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004974 != AUDIO_DIRECT_NOT_SUPPORTED) {
4975 // Already reports offload gapless supported. No need to report offload support.
4976 continue;
4977 }
4978 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4979 != AUDIO_OUTPUT_FLAG_NONE) {
4980 // If offload gapless is reported, no need to report offload support.
4981 directMode = (audio_direct_mode_t) ((directMode &
4982 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4983 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4984 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004985 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004986 }
4987 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004988 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004989 }
4990 }
4991 }
4992 return directMode;
4993}
4994
Dorin Drimusf2196d82022-01-03 12:11:18 +01004995status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4996 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004997 if (mEffects.isNonOffloadableEffectEnabled()) {
4998 return OK;
4999 }
jiabinf1c73972022-04-14 16:28:52 -07005000 DeviceVector devices;
5001 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01005002 if (status != OK) {
5003 return status;
5004 }
5005 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
5006 if (devices.empty()) {
5007 return OK; // no output devices for the attributes
5008 }
jiabinf1c73972022-04-14 16:28:52 -07005009 return getProfilesForDevices(devices, audioProfilesVector,
5010 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01005011}
5012
jiabina84c3d32022-12-02 18:59:55 +00005013status_t AudioPolicyManager::getSupportedMixerAttributes(
5014 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
5015 ALOGV("%s, portId=%d", __func__, portId);
5016 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5017 if (deviceDescriptor == nullptr) {
5018 ALOGE("%s the requested device is currently unavailable", __func__);
5019 return BAD_VALUE;
5020 }
jiabin96daffc2023-05-11 17:51:55 +00005021 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5022 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
5023 deviceDescriptor->type());
5024 return BAD_VALUE;
5025 }
jiabina84c3d32022-12-02 18:59:55 +00005026 for (const auto& hwModule : mHwModules) {
5027 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5028 if (curProfile->supportsDevice(deviceDescriptor)) {
5029 curProfile->toSupportedMixerAttributes(&mixerAttrs);
5030 }
5031 }
5032 }
5033 return NO_ERROR;
5034}
5035
5036status_t AudioPolicyManager::setPreferredMixerAttributes(
5037 const audio_attributes_t *attr,
5038 audio_port_handle_t portId,
5039 uid_t uid,
5040 const audio_mixer_attributes_t *mixerAttributes) {
5041 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
5042 "mixerBehavior=%d}, uid=%d, portId=%u",
5043 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
5044 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
5045 mixerAttributes->mixer_behavior, uid, portId);
5046 if (attr->usage != AUDIO_USAGE_MEDIA) {
5047 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
5048 return BAD_VALUE;
5049 }
5050 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5051 if (deviceDescriptor == nullptr) {
5052 ALOGE("%s the requested device is currently unavailable", __func__);
5053 return BAD_VALUE;
5054 }
5055 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5056 ALOGE("%s(%d), type=%d, is not a usb output device",
5057 __func__, portId, deviceDescriptor->type());
5058 return BAD_VALUE;
5059 }
5060
5061 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5062 audio_flags_to_audio_output_flags(attr->flags, &flags);
5063 flags = (audio_output_flags_t) (flags |
5064 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
5065 sp<IOProfile> profile = nullptr;
5066 DeviceVector devices(deviceDescriptor);
5067 for (const auto& hwModule : mHwModules) {
5068 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5069 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00005070 && curProfile->getCompatibilityScore(
5071 devices,
5072 mixerAttributes->config.sample_rate,
5073 nullptr /*updatedSamplingRate*/,
5074 mixerAttributes->config.format,
5075 nullptr /*updatedFormat*/,
5076 mixerAttributes->config.channel_mask,
5077 nullptr /*updatedChannelMask*/,
jiabin91beb492024-10-16 21:53:36 +00005078 flags)
jiabin66acc432024-02-06 00:57:36 +00005079 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00005080 profile = curProfile;
5081 break;
5082 }
5083 }
5084 }
5085 if (profile == nullptr) {
5086 ALOGE("%s, there is no compatible profile found", __func__);
5087 return BAD_VALUE;
5088 }
5089
5090 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
5091 sp<PreferredMixerAttributesInfo>::make(
5092 uid, portId, profile, flags, *mixerAttributes);
5093 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5094 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
5095
5096 // If 1) there is any client from the preferred mixer configuration owner that is currently
5097 // active and matches the strategy and 2) current output is on the preferred device and the
5098 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
5099 // configuration.
5100 std::vector<audio_io_handle_t> outputsToReopen;
5101 for (size_t i = 0; i < mOutputs.size(); i++) {
5102 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00005103 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
5104 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00005105 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00005106 } else {
5107 for (const auto &client: output->getActiveClients()) {
5108 if (client->uid() == uid && client->strategy() == strategy) {
5109 client->setIsInvalid();
5110 outputsToReopen.push_back(output->mIoHandle);
5111 }
jiabina84c3d32022-12-02 18:59:55 +00005112 }
5113 }
5114 }
5115 }
5116 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5117 config.sample_rate = mixerAttributes->config.sample_rate;
5118 config.channel_mask = mixerAttributes->config.channel_mask;
5119 config.format = mixerAttributes->config.format;
5120 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005121 sp<SwAudioOutputDescriptor> desc =
5122 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5123 if (desc == nullptr) {
5124 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5125 continue;
5126 }
jiabin220eea12024-05-17 17:55:20 +00005127 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005128 }
5129
5130 return NO_ERROR;
5131}
5132
5133sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005134 audio_port_handle_t devicePortId,
5135 product_strategy_t strategy,
5136 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005137 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5138 if (it == mPreferredMixerAttrInfos.end()) {
5139 return nullptr;
5140 }
jiabind9a58d32023-06-01 17:57:30 +00005141 if (activeBitPerfectPreferred) {
5142 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005143 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005144 return info;
5145 }
5146 }
jiabina84c3d32022-12-02 18:59:55 +00005147 }
jiabind9a58d32023-06-01 17:57:30 +00005148 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5149 return strategyMatchedMixerAttrInfoIt == it->second.end()
5150 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005151}
5152
5153status_t AudioPolicyManager::getPreferredMixerAttributes(
5154 const audio_attributes_t *attr,
5155 audio_port_handle_t portId,
5156 audio_mixer_attributes_t* mixerAttributes) {
5157 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5158 portId, mEngine->getProductStrategyForAttributes(*attr));
5159 if (info == nullptr) {
5160 return NAME_NOT_FOUND;
5161 }
5162 *mixerAttributes = info->getMixerAttributes();
5163 return NO_ERROR;
5164}
5165
5166status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5167 audio_port_handle_t portId,
5168 uid_t uid) {
5169 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5170 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5171 if (preferredMixerAttrInfo == nullptr) {
5172 return NAME_NOT_FOUND;
5173 }
5174 if (preferredMixerAttrInfo->getUid() != uid) {
5175 ALOGE("%s, requested uid=%d, owned uid=%d",
5176 __func__, uid, preferredMixerAttrInfo->getUid());
5177 return PERMISSION_DENIED;
5178 }
5179 mPreferredMixerAttrInfos[portId].erase(strategy);
5180 if (mPreferredMixerAttrInfos[portId].empty()) {
5181 mPreferredMixerAttrInfos.erase(portId);
5182 }
5183
5184 // Reconfig existing output
5185 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5186 for (size_t i = 0; i < mOutputs.size(); i++) {
5187 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5188 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5189 }
5190 }
5191 for (const auto output : potentialOutputsToReopen) {
5192 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5193 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5194 preferredMixerAttrInfo->getFlags())) {
5195 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5196 }
5197 }
5198 return NO_ERROR;
5199}
5200
Eric Laurent6a94d692014-05-20 11:18:06 -07005201status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5202 audio_port_type_t type,
5203 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005204 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005205 unsigned int *generation)
5206{
jiabin19cdba52020-11-24 11:28:58 -08005207 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5208 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005209 return BAD_VALUE;
5210 }
5211 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005212 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005213 *num_ports = 0;
5214 }
5215
5216 size_t portsWritten = 0;
5217 size_t portsMax = *num_ports;
5218 *num_ports = 0;
5219 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005220 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5221 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005222 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005223 for (const auto& dev : mAvailableOutputDevices) {
5224 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005225 continue;
5226 }
5227 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005228 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005229 }
5230 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005232 }
5233 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005234 for (const auto& dev : mAvailableInputDevices) {
5235 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005236 continue;
5237 }
5238 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005239 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005240 }
5241 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005242 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005243 }
5244 }
5245 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5246 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5247 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5248 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5249 }
5250 *num_ports += mInputs.size();
5251 }
5252 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005253 size_t numOutputs = 0;
5254 for (size_t i = 0; i < mOutputs.size(); i++) {
5255 if (!mOutputs[i]->isDuplicated()) {
5256 numOutputs++;
5257 if (portsWritten < portsMax) {
5258 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5259 }
5260 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005261 }
Eric Laurent84c70242014-06-23 08:46:27 -07005262 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005263 }
5264 }
jiabina84c3d32022-12-02 18:59:55 +00005265
Eric Laurent6a94d692014-05-20 11:18:06 -07005266 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005267 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005268 return NO_ERROR;
5269}
5270
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005271status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5272 std::vector<media::AudioPortFw>* _aidl_return) {
5273 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5274 audio_port_v7 port;
5275 dev->toAudioPort(&port);
5276 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5277 _aidl_return->push_back(std::move(aidlPort));
5278 return OK;
5279 };
5280
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005281 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005282 for (const auto& dev : module->getDeclaredDevices()) {
5283 if (role == media::AudioPortRole::NONE ||
5284 ((role == media::AudioPortRole::SOURCE)
5285 == audio_is_input_device(dev->type()))) {
5286 RETURN_STATUS_IF_ERROR(pushPort(dev));
5287 }
5288 }
5289 }
5290 return OK;
5291}
5292
jiabin19cdba52020-11-24 11:28:58 -08005293status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005294{
Eric Laurent99fcae42018-05-17 16:59:18 -07005295 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5296 return BAD_VALUE;
5297 }
5298 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5299 if (dev != 0) {
5300 dev->toAudioPort(port);
5301 return NO_ERROR;
5302 }
5303 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5304 if (dev != 0) {
5305 dev->toAudioPort(port);
5306 return NO_ERROR;
5307 }
5308 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5309 if (out != 0) {
5310 out->toAudioPort(port);
5311 return NO_ERROR;
5312 }
5313 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5314 if (in != 0) {
5315 in->toAudioPort(port);
5316 return NO_ERROR;
5317 }
5318 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005319}
5320
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005321status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5322 audio_patch_handle_t *handle,
5323 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005324{
François Gaffieafd4cea2019-11-18 15:50:22 +01005325 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005326 if (handle == NULL || patch == NULL) {
5327 return BAD_VALUE;
5328 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005329 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005330 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005331 return BAD_VALUE;
5332 }
5333 // only one source per audio patch supported for now
5334 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005335 return INVALID_OPERATION;
5336 }
Eric Laurent874c42872014-08-08 15:13:39 -07005337 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005338 return INVALID_OPERATION;
5339 }
Eric Laurent874c42872014-08-08 15:13:39 -07005340 for (size_t i = 0; i < patch->num_sinks; i++) {
5341 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5342 return INVALID_OPERATION;
5343 }
5344 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005345
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005346 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5347 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5348 if (srcDevice == nullptr || sinkDevice == nullptr) {
5349 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5350 return BAD_VALUE;
5351 }
5352 ALOGV("%s between source %s and sink %s", __func__,
5353 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5354 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5355 // Default attributes, default volume priority, not to infer with non raw audio patches.
5356 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5357 const struct audio_port_config *source = &patch->sources[0];
5358 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005359 new SourceClientDescriptor(
5360 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5361 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005362 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005363 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005364
5365 status_t status =
5366 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5367
5368 if (status != NO_ERROR) {
5369 return INVALID_OPERATION;
5370 }
5371 mAudioSources.add(portId, sourceDesc);
5372 return NO_ERROR;
5373}
5374
5375status_t AudioPolicyManager::connectAudioSourceToSink(
5376 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5377 const struct audio_patch *patch,
5378 audio_patch_handle_t &handle,
5379 uid_t uid, uint32_t delayMs)
5380{
5381 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5382 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5383 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5384 return INVALID_OPERATION;
5385 }
5386 sourceDesc->connect(handle, sinkDevice);
5387 if (isMsdPatch(handle)) {
5388 return NO_ERROR;
5389 }
5390 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5391 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5392 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5393 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5394 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5395 goto FailurePatchAdded;
5396 }
5397 status = swOutput->start();
5398 if (status != NO_ERROR) {
5399 goto FailureSourceAdded;
5400 }
5401 swOutput->addClient(sourceDesc);
5402 status = startSource(swOutput, sourceDesc, &delayMs);
5403 if (status != NO_ERROR) {
5404 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5405 goto FailureSourceActive;
5406 }
5407 if (delayMs != 0) {
5408 usleep(delayMs * 1000);
5409 }
5410 return NO_ERROR;
5411
5412FailureSourceActive:
5413 swOutput->stop();
5414 releaseOutput(sourceDesc->portId());
5415FailureSourceAdded:
5416 sourceDesc->setSwOutput(nullptr);
5417FailurePatchAdded:
5418 releaseAudioPatchInternal(handle);
5419 return INVALID_OPERATION;
5420}
5421
5422status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5423 audio_patch_handle_t *handle,
5424 uid_t uid, uint32_t delayMs,
5425 const sp<SourceClientDescriptor>& sourceDesc)
5426{
5427 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005428 sp<AudioPatch> patchDesc;
5429 ssize_t index = mAudioPatches.indexOfKey(*handle);
5430
François Gaffieafd4cea2019-11-18 15:50:22 +01005431 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5432 patch->sources[0].role,
5433 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005434#if LOG_NDEBUG == 0
5435 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005436 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5437 patch->sinks[i].role,
5438 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005439 }
5440#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005441
5442 if (index >= 0) {
5443 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005444 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5445 __func__, mUidCached, patchDesc->getUid(), uid);
5446 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005447 return INVALID_OPERATION;
5448 }
5449 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005450 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005451 }
5452
5453 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005454 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005455 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005456 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005457 return BAD_VALUE;
5458 }
Eric Laurent84c70242014-06-23 08:46:27 -07005459 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5460 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005461 if (patchDesc != 0) {
5462 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005463 ALOGV("%s source id differs for patch current id %d new id %d",
5464 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005465 return BAD_VALUE;
5466 }
5467 }
Eric Laurent874c42872014-08-08 15:13:39 -07005468 DeviceVector devices;
5469 for (size_t i = 0; i < patch->num_sinks; i++) {
5470 // Only support mix to devices connection
5471 // TODO add support for mix to mix connection
5472 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005473 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005474 return INVALID_OPERATION;
5475 }
5476 sp<DeviceDescriptor> devDesc =
5477 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5478 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005479 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005480 return BAD_VALUE;
5481 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005482
jiabin66acc432024-02-06 00:57:36 +00005483 if (outputDesc->mProfile->getCompatibilityScore(
5484 DeviceVector(devDesc),
5485 patch->sources[0].sample_rate,
5486 nullptr, // updatedSamplingRate
5487 patch->sources[0].format,
5488 nullptr, // updatedFormat
5489 patch->sources[0].channel_mask,
5490 nullptr, // updatedChannelMask
5491 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005492 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005493 return INVALID_OPERATION;
5494 }
5495 devices.add(devDesc);
5496 }
5497 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005498 return INVALID_OPERATION;
5499 }
Eric Laurent874c42872014-08-08 15:13:39 -07005500
Eric Laurent6a94d692014-05-20 11:18:06 -07005501 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005502 ALOGV("%s setting device %s on output %d",
5503 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305504 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005505 index = mAudioPatches.indexOfKey(*handle);
5506 if (index >= 0) {
5507 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005508 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005509 }
5510 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005511 patchDesc->setUid(uid);
5512 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005513 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005514 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005515 return INVALID_OPERATION;
5516 }
5517 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5518 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5519 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005520 // only one sink supported when connecting an input device to a mix
5521 if (patch->num_sinks > 1) {
5522 return INVALID_OPERATION;
5523 }
François Gaffie53615e22015-03-19 09:24:12 +01005524 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005525 if (inputDesc == NULL) {
5526 return BAD_VALUE;
5527 }
5528 if (patchDesc != 0) {
5529 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5530 return BAD_VALUE;
5531 }
5532 }
François Gaffie11d30102018-11-02 16:09:09 +01005533 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005534 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005535 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005536 return BAD_VALUE;
5537 }
5538
jiabin66acc432024-02-06 00:57:36 +00005539 if (inputDesc->mProfile->getCompatibilityScore(
5540 DeviceVector(device),
5541 patch->sinks[0].sample_rate,
5542 nullptr, /*updatedSampleRate*/
5543 patch->sinks[0].format,
5544 nullptr, /*updatedFormat*/
5545 patch->sinks[0].channel_mask,
5546 nullptr, /*updatedChannelMask*/
5547 // FIXME for the parameter type,
5548 // and the NONE
5549 (audio_output_flags_t)
5550 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005551 return INVALID_OPERATION;
5552 }
5553 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005554 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005555 device->toString().c_str(), inputDesc->mIoHandle);
5556 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005557 index = mAudioPatches.indexOfKey(*handle);
5558 if (index >= 0) {
5559 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005560 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005561 }
5562 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005563 patchDesc->setUid(uid);
5564 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005565 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005566 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005567 return INVALID_OPERATION;
5568 }
5569 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5570 // device to device connection
5571 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005572 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005573 return BAD_VALUE;
5574 }
5575 }
François Gaffie11d30102018-11-02 16:09:09 +01005576 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005577 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005578 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005579 return BAD_VALUE;
5580 }
Eric Laurent874c42872014-08-08 15:13:39 -07005581
Eric Laurent6a94d692014-05-20 11:18:06 -07005582 //update source and sink with our own data as the data passed in the patch may
5583 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005584 PatchBuilder patchBuilder;
5585 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005586
5587 // if first sink is to MSD, establish single MSD patch
5588 if (getMsdAudioOutDevices().contains(
5589 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5590 ALOGV("%s patching to MSD", __FUNCTION__);
5591 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5592 goto installPatch;
5593 }
5594
François Gaffieafd4cea2019-11-18 15:50:22 +01005595 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5596 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005597
Eric Laurent874c42872014-08-08 15:13:39 -07005598 for (size_t i = 0; i < patch->num_sinks; i++) {
5599 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005600 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005601 return INVALID_OPERATION;
5602 }
François Gaffie11d30102018-11-02 16:09:09 +01005603 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005604 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005605 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005606 return BAD_VALUE;
5607 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005608 audio_port_config sinkPortConfig = {};
5609 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5610 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005611
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005612 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5613 // volume management purpose (tracking activity)
5614 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5615 // in config XML to reach the sink so that is can be declared as available.
5616 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005617 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005618 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005619 // take care of dynamic routing for SwOutput selection,
5620 audio_attributes_t attributes = sourceDesc->attributes();
5621 audio_stream_type_t stream = sourceDesc->stream();
5622 audio_attributes_t resultAttr;
5623 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5624 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005625 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5626 config.channel_mask =
5627 (audio_channel_mask_get_representation(sourceMask)
5628 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5629 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005630 config.format = sourceDesc->config().format;
5631 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Robert Wufb971192024-10-30 21:54:35 +00005632 DeviceIdVector selectedDeviceIds;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005633 bool isRequestedDeviceForExclusiveUse = false;
5634 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005635 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005636 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005637 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5638 &stream, sourceDesc->uid(), &config, &flags,
Robert Wufb971192024-10-30 21:54:35 +00005639 &selectedDeviceIds, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005640 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005641 if (output == AUDIO_IO_HANDLE_NONE) {
5642 ALOGV("%s no output for device %s",
5643 __FUNCTION__, sinkDevice->toString().c_str());
5644 return INVALID_OPERATION;
5645 }
5646 outputDesc = mOutputs.valueFor(output);
5647 if (outputDesc->isDuplicated()) {
5648 ALOGE("%s output is duplicated", __func__);
5649 return INVALID_OPERATION;
5650 }
François Gaffie7e39df22022-04-26 12:48:49 +02005651 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5652 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005653 } else {
5654 // Same for "raw patches" aka created from createAudioPatch API
5655 SortedVector<audio_io_handle_t> outputs =
5656 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5657 // if the sink device is reachable via an opened output stream, request to
5658 // go via this output stream by adding a second source to the patch
5659 // description
5660 output = selectOutput(outputs);
5661 if (output == AUDIO_IO_HANDLE_NONE) {
5662 ALOGE("%s no output available for internal patch sink", __func__);
5663 return INVALID_OPERATION;
5664 }
5665 outputDesc = mOutputs.valueFor(output);
5666 if (outputDesc->isDuplicated()) {
5667 ALOGV("%s output for device %s is duplicated",
5668 __func__, sinkDevice->toString().c_str());
5669 return INVALID_OPERATION;
5670 }
François Gaffie7e39df22022-04-26 12:48:49 +02005671 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005672 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005673 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005674 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005675 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005676 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005677 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5678 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005679 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5680 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005681 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005682 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005683 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005684 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005685 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005686 return INVALID_OPERATION;
5687 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005688 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005689 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005690 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005691 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005692 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005693 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005694 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005695 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5696 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005697 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005698 }
Eric Laurent83b88082014-06-20 18:31:16 -07005699 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005700 }
5701 // TODO: check from routing capabilities in config file and other conflicting patches
5702
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005703installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005704 status_t status = installPatch(
5705 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005706 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005707 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005708 return INVALID_OPERATION;
5709 }
5710 } else {
5711 return BAD_VALUE;
5712 }
5713 } else {
5714 return BAD_VALUE;
5715 }
5716 return NO_ERROR;
5717}
5718
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005719status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005720{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005721 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005722 ssize_t index = mAudioPatches.indexOfKey(handle);
5723
5724 if (index < 0) {
5725 return BAD_VALUE;
5726 }
5727 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005728 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5729 __func__, mUidCached, patchDesc->getUid(), uid);
5730 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005731 return INVALID_OPERATION;
5732 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005733 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5734 for (size_t i = 0; i < mAudioSources.size(); i++) {
5735 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5736 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5737 portId = sourceDesc->portId();
5738 break;
5739 }
5740 }
5741 return portId != AUDIO_PORT_HANDLE_NONE ?
5742 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005743}
Eric Laurent6a94d692014-05-20 11:18:06 -07005744
François Gaffieafd4cea2019-11-18 15:50:22 +01005745status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005746 uint32_t delayMs,
5747 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005748{
5749 ALOGV("%s patch %d", __func__, handle);
5750 if (mAudioPatches.indexOfKey(handle) < 0) {
5751 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5752 return BAD_VALUE;
5753 }
5754 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005755 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005756 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005757 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005758 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005759 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005760 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005761 return BAD_VALUE;
5762 }
5763
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305764 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005765 getNewOutputDevices(outputDesc, true /*fromCache*/),
5766 true,
5767 0,
5768 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005769 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5770 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005771 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005772 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005773 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005774 return BAD_VALUE;
5775 }
5776 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005777 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005778 true,
5779 NULL);
5780 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005781 status_t status =
5782 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5783 ALOGV("%s patch panel returned %d patchHandle %d",
5784 __func__, status, patchDesc->getAfHandle());
5785 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005786 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005787 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005788 // SW or HW Bridge
5789 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5790 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005791 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005792 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5793 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5794 outputDesc = sourceDesc->swOutput().promote();
5795 }
5796 if (outputDesc == nullptr) {
5797 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5798 // releaseOutput has already called closeOutput in case of direct output
5799 return NO_ERROR;
5800 }
François Gaffie7e39df22022-04-26 12:48:49 +02005801 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005802 // While using a HwBridge, force reconsidering device only if not reusing an existing
5803 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005804 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005805 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5806 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5807 // Reconsider device only for cases:
5808 // 1 / Active Output
5809 // 2 / Inactive Output previously hosting HwBridge
5810 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5811 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5812 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305813 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005814 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5815 outputDesc->devices(),
5816 force,
5817 0,
5818 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005819 } else {
5820 return BAD_VALUE;
5821 }
5822 } else {
5823 return BAD_VALUE;
5824 }
5825 return NO_ERROR;
5826}
5827
5828status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5829 struct audio_patch *patches,
5830 unsigned int *generation)
5831{
François Gaffie53615e22015-03-19 09:24:12 +01005832 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005833 return BAD_VALUE;
5834 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005835 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005836 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005837}
5838
Eric Laurente1715a42014-05-20 11:30:42 -07005839status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005840{
Eric Laurente1715a42014-05-20 11:30:42 -07005841 ALOGV("setAudioPortConfig()");
5842
5843 if (config == NULL) {
5844 return BAD_VALUE;
5845 }
5846 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5847 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005848 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5849 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005850 }
5851
Eric Laurenta121f902014-06-03 13:32:54 -07005852 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005853 if (config->type == AUDIO_PORT_TYPE_MIX) {
5854 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005855 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005856 if (outputDesc == NULL) {
5857 return BAD_VALUE;
5858 }
Eric Laurent84c70242014-06-23 08:46:27 -07005859 ALOG_ASSERT(!outputDesc->isDuplicated(),
5860 "setAudioPortConfig() called on duplicated output %d",
5861 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005862 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005863 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005864 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005865 if (inputDesc == NULL) {
5866 return BAD_VALUE;
5867 }
Eric Laurenta121f902014-06-03 13:32:54 -07005868 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005869 } else {
5870 return BAD_VALUE;
5871 }
5872 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5873 sp<DeviceDescriptor> deviceDesc;
5874 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5875 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5876 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5877 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5878 } else {
5879 return BAD_VALUE;
5880 }
5881 if (deviceDesc == NULL) {
5882 return BAD_VALUE;
5883 }
Eric Laurenta121f902014-06-03 13:32:54 -07005884 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005885 } else {
5886 return BAD_VALUE;
5887 }
5888
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005889 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005890 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5891 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005892 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005893 audioPortConfig->toAudioPortConfig(&newConfig, config);
5894 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005895 }
Eric Laurenta121f902014-06-03 13:32:54 -07005896 if (status != NO_ERROR) {
5897 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005898 }
Eric Laurente1715a42014-05-20 11:30:42 -07005899
5900 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005901}
5902
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005903void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5904{
Eric Laurentd60560a2015-04-10 11:31:20 -07005905 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005906 clearAudioPatches(uid);
5907 clearSessionRoutes(uid);
5908}
5909
Eric Laurent6a94d692014-05-20 11:18:06 -07005910void AudioPolicyManager::clearAudioPatches(uid_t uid)
5911{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005912 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005913 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005914 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005915 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005916 }
5917 }
5918}
5919
François Gaffiec005e562018-11-06 15:04:49 +01005920void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005921{
François Gaffiec005e562018-11-06 15:04:49 +01005922 // Take the first attributes following the product strategy as it is used to retrieve the routed
5923 // device. All attributes wihin a strategy follows the same "routing strategy"
5924 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5925 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005926 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005927 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005928 for (size_t j = 0; j < mOutputs.size(); j++) {
5929 if (mOutputs.keyAt(j) == ouptutToSkip) {
5930 continue;
5931 }
5932 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005933 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005934 continue;
5935 }
5936 // If the default device for this strategy is on another output mix,
5937 // invalidate all tracks in this strategy to force re connection.
5938 // Otherwise select new device on the output mix.
5939 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005940 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005941 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005942 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005943 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005944 // If the device is using preferred mixer attributes, the output need to reopen
5945 // with default configuration when the new selected devices are different from
5946 // current routing devices.
5947 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5948 continue;
5949 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305950 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005951 }
5952 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005953 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005954}
5955
5956void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5957{
5958 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005959 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005960 for (size_t i = 0; i < mOutputs.size(); i++) {
5961 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005962 for (const auto& client : outputDesc->getClientIterable()) {
5963 if (client->hasPreferredDevice() && client->uid() == uid) {
5964 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005965 auto clientStrategy = client->strategy();
5966 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5967 end(affectedStrategies)) {
5968 continue;
5969 }
5970 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005971 }
5972 }
5973 }
5974 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005975 for (const auto& strategy : affectedStrategies) {
5976 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005977 }
5978
5979 // remove input routes associated with this uid
5980 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005981 for (size_t i = 0; i < mInputs.size(); i++) {
5982 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005983 for (const auto& client : inputDesc->getClientIterable()) {
5984 if (client->hasPreferredDevice() && client->uid() == uid) {
5985 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5986 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005987 }
5988 }
5989 }
5990 // reroute inputs if necessary
5991 SortedVector<audio_io_handle_t> inputsToClose;
5992 for (size_t i = 0; i < mInputs.size(); i++) {
5993 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005994 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005995 inputsToClose.add(inputDesc->mIoHandle);
5996 }
5997 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005998 for (const auto& input : inputsToClose) {
5999 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006000 }
6001}
6002
Eric Laurentd60560a2015-04-10 11:31:20 -07006003void AudioPolicyManager::clearAudioSources(uid_t uid)
6004{
6005 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006006 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6007 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006008 stopAudioSource(mAudioSources.keyAt(i));
6009 }
6010 }
6011}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006012
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006013status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
6014 audio_io_handle_t *ioHandle,
6015 audio_devices_t *device)
6016{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08006017 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
6018 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01006019 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00006020 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
6021 if (deviceDesc == nullptr) {
6022 return INVALID_OPERATION;
6023 }
6024 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006025
François Gaffiedf372692015-03-19 10:43:27 +01006026 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006027}
6028
Eric Laurentd60560a2015-04-10 11:31:20 -07006029status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006030 const audio_attributes_t *attributes,
6031 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00006032 uid_t uid) {
6033 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00006034 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00006035}
6036
6037status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
6038 const audio_attributes_t *attributes,
6039 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00006040 uid_t uid, bool internal, bool isCallRx,
6041 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07006042{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006043 ALOGV("%s", __FUNCTION__);
6044 *portId = AUDIO_PORT_HANDLE_NONE;
6045
6046 if (source == NULL || attributes == NULL || portId == NULL) {
6047 ALOGW("%s invalid argument: source %p attributes %p handle %p",
6048 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006049 return BAD_VALUE;
6050 }
6051
Eric Laurentd60560a2015-04-10 11:31:20 -07006052 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
6053 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006054 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
6055 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006056 return INVALID_OPERATION;
6057 }
6058
François Gaffie11d30102018-11-02 16:09:09 +01006059 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07006060 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006061 String8(source->ext.device.address),
6062 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01006063 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006064 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006065 return BAD_VALUE;
6066 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006067
jiabin4ef93452019-09-10 14:29:54 -07006068 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07006069
François Gaffieaaac0fd2018-11-22 17:56:39 +01006070 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01006071 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006072 mEngine->getStreamTypeForAttributes(*attributes),
6073 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00006074 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07006075
David Lif85c5e32024-07-01 13:14:10 +00006076 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07006077 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006078 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006079 }
6080 return status;
6081}
6082
David Lif85c5e32024-07-01 13:14:10 +00006083status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
6084 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07006085{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006086 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006087
6088 // make sure we only have one patch per source.
6089 disconnectAudioSource(sourceDesc);
6090
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006091 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006092 // May the device (dynamic) have been disconnected/reconnected, id has changed.
6093 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
6094 sourceDesc->srcDevice()->type(),
6095 String8(sourceDesc->srcDevice()->address().c_str()),
6096 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01006097 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02006098 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01006099 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01006100 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006101 if (!mAvailableOutputDevices.contains(sinkDevice)) {
6102 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
6103 return INVALID_OPERATION;
6104 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006105 PatchBuilder patchBuilder;
6106 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
6107 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01006108
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006109 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00006110 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07006111}
6112
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006113status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07006114{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006115 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6116 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006117 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006118 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006119 return BAD_VALUE;
6120 }
6121 status_t status = disconnectAudioSource(sourceDesc);
6122
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006123 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006124 return status;
6125}
6126
Andy Hung2ddee192015-12-18 17:34:44 -08006127status_t AudioPolicyManager::setMasterMono(bool mono)
6128{
6129 if (mMasterMono == mono) {
6130 return NO_ERROR;
6131 }
6132 mMasterMono = mono;
6133 // if enabling mono we close all offloaded devices, which will invalidate the
6134 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6135 // for recreating the new AudioTrack as non-offloaded PCM.
6136 //
6137 // If disabling mono, we leave all tracks as is: we don't know which clients
6138 // and tracks are able to be recreated as offloaded. The next "song" should
6139 // play back offloaded.
6140 if (mMasterMono) {
6141 Vector<audio_io_handle_t> offloaded;
6142 for (size_t i = 0; i < mOutputs.size(); ++i) {
6143 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6144 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6145 offloaded.push(desc->mIoHandle);
6146 }
6147 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006148 for (const auto& handle : offloaded) {
6149 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006150 }
6151 }
6152 // update master mono for all remaining outputs
6153 for (size_t i = 0; i < mOutputs.size(); ++i) {
6154 updateMono(mOutputs.keyAt(i));
6155 }
6156 return NO_ERROR;
6157}
6158
6159status_t AudioPolicyManager::getMasterMono(bool *mono)
6160{
6161 *mono = mMasterMono;
6162 return NO_ERROR;
6163}
6164
Eric Laurentac9cef52017-06-09 15:46:26 -07006165float AudioPolicyManager::getStreamVolumeDB(
6166 audio_stream_type_t stream, int index, audio_devices_t device)
6167{
Vlad Popa9d482762024-06-21 16:40:23 -07006168 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6169 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006170}
6171
jiabin81772902018-04-02 17:52:27 -07006172status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6173 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006174 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006175{
Kriti Dang6537def2021-03-02 13:46:59 +01006176 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6177 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006178 return BAD_VALUE;
6179 }
Kriti Dang6537def2021-03-02 13:46:59 +01006180 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6181 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006182
6183 size_t formatsWritten = 0;
6184 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006185
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006186 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006187 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6188 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006189 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006190 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006191 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006192 bool formatEnabled = true;
6193 switch (forceUse) {
6194 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006195 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006196 break;
6197 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6198 formatEnabled = false;
6199 break;
6200 default: // AUTO or ALWAYS => true
6201 break;
jiabin81772902018-04-02 17:52:27 -07006202 }
6203 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6204 }
jiabin81772902018-04-02 17:52:27 -07006205 }
6206 return NO_ERROR;
6207}
6208
Kriti Dang6537def2021-03-02 13:46:59 +01006209status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6210 audio_format_t *surroundFormats) {
6211 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6212 return BAD_VALUE;
6213 }
6214 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6215 __func__, *numSurroundFormats, surroundFormats);
6216
6217 size_t formatsWritten = 0;
6218 size_t formatsMax = *numSurroundFormats;
6219 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6220
6221 // Return formats from all device profiles that have already been resolved by
6222 // checkOutputsForDevice().
6223 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6224 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6225 audio_devices_t deviceType = device->type();
6226 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6227 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006228 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6229 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006230 continue;
6231 }
6232 // Formats reported by sink devices
6233 std::unordered_set<audio_format_t> formatset;
6234 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6235 formatset.insert(it->second.begin(), it->second.end());
6236 }
6237
6238 // Formats hard-coded in the in policy configuration file (if any).
6239 FormatVector encodedFormats = device->encodedFormats();
6240 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6241 // Filter the formats which are supported by the vendor hardware.
6242 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006243 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006244 formats.insert(*it);
6245 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006246 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006247 if (pair.second.count(*it) != 0) {
6248 formats.insert(pair.first);
6249 break;
6250 }
6251 }
6252 }
6253 }
6254 }
6255 *numSurroundFormats = formats.size();
6256 for (const auto& format: formats) {
6257 if (formatsWritten < formatsMax) {
6258 surroundFormats[formatsWritten++] = format;
6259 }
6260 }
6261 return NO_ERROR;
6262}
6263
jiabin81772902018-04-02 17:52:27 -07006264status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6265{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006266 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006267 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6268 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006269 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006270 return BAD_VALUE;
6271 }
6272
Mikhail Naganov100f0122018-11-29 11:22:16 -08006273 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6274 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006275 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006276 return INVALID_OPERATION;
6277 }
6278
Mikhail Naganov100f0122018-11-29 11:22:16 -08006279 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006280 return NO_ERROR;
6281 }
6282
Mikhail Naganov100f0122018-11-29 11:22:16 -08006283 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006284 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006285 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006286 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006287 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006288 }
6289 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006290 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006291 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006292 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006293 }
6294 }
6295
6296 sp<SwAudioOutputDescriptor> outputDesc;
6297 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006298 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6299 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006300 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6301 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006302 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006303 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006304 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006305 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6306 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006307 name.c_str(),
6308 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006309 if (status != NO_ERROR) {
6310 continue;
6311 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006312 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006313 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6314 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006315 name.c_str(),
6316 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006317 profileUpdated |= (status == NO_ERROR);
6318 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006319 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006320 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006321 AUDIO_DEVICE_IN_HDMI);
6322 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6323 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006324 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006325 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006326 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6327 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6328 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006329 name.c_str(),
6330 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006331 if (status != NO_ERROR) {
6332 continue;
6333 }
6334 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6335 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6336 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006337 name.c_str(),
6338 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006339 profileUpdated |= (status == NO_ERROR);
6340 }
6341
jiabin81772902018-04-02 17:52:27 -07006342 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006343 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006344 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006345 }
6346
6347 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6348}
6349
Eric Laurent5ada82e2019-08-29 17:53:54 -07006350void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006351{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006352 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006353 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006354 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006355 }
6356}
6357
jiabin6012f912018-11-02 17:06:30 -07006358bool AudioPolicyManager::isHapticPlaybackSupported()
6359{
6360 for (const auto& hwModule : mHwModules) {
6361 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6362 for (const auto &outProfile : outputProfiles) {
6363 struct audio_port audioPort;
6364 outProfile->toAudioPort(&audioPort);
6365 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6366 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6367 return true;
6368 }
6369 }
6370 }
6371 }
6372 return false;
6373}
6374
Carter Hsu325a8eb2022-01-19 19:56:51 +08006375bool AudioPolicyManager::isUltrasoundSupported()
6376{
6377 bool hasUltrasoundOutput = false;
6378 bool hasUltrasoundInput = false;
6379 for (const auto& hwModule : mHwModules) {
6380 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6381 if (!hasUltrasoundOutput) {
6382 for (const auto &outProfile : outputProfiles) {
6383 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6384 hasUltrasoundOutput = true;
6385 break;
6386 }
6387 }
6388 }
6389
6390 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6391 if (!hasUltrasoundInput) {
6392 for (const auto &inputProfile : inputProfiles) {
6393 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6394 hasUltrasoundInput = true;
6395 break;
6396 }
6397 }
6398 }
6399
6400 if (hasUltrasoundOutput && hasUltrasoundInput)
6401 return true;
6402 }
6403 return false;
6404}
6405
Atneya Nair698f5ef2022-12-15 16:15:09 -08006406bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6407{
6408 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6409 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6410 for (const auto& hwModule : mHwModules) {
6411 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6412 for (const auto &inputProfile : inputProfiles) {
6413 if ((inputProfile->getFlags() & mask) == mask) {
6414 return true;
6415 }
6416 }
6417 }
6418 return false;
6419}
6420
Eric Laurent8340e672019-11-06 11:01:08 -08006421bool AudioPolicyManager::isCallScreenModeSupported()
6422{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006423 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006424}
6425
6426
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006427status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006428{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006429 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006430 if (!sourceDesc->isConnected()) {
6431 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6432 return NO_ERROR;
6433 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006434 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6435 if (swOutput != 0) {
6436 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006437 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006438 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006439 }
jiabinbce0c1d2020-10-05 11:20:18 -07006440 if (releaseOutput(sourceDesc->portId())) {
6441 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6442 // no need to release audio patch here but just return NO_ERROR.
6443 return NO_ERROR;
6444 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006445 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006446 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006447 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006448 // close Hwoutput and remove from mHwOutputs
6449 } else {
6450 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6451 }
6452 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006453 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006454 sourceDesc->disconnect();
6455 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006456}
6457
François Gaffiec005e562018-11-06 15:04:49 +01006458sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6459 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006460{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006461 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006462 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006463 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006464 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006465 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6466 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006467 source = sourceDesc;
6468 break;
6469 }
6470 }
6471 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006472}
6473
Eric Laurentb4f42a92022-01-17 17:37:31 +01006474bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006475 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006476 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006477{
6478 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6479 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006480 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006481 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006482 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6483 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6484 return false;
6485 }
6486 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6487 return false;
6488 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006489 }
6490
Eric Laurentd332bc82023-08-04 11:45:23 +02006491 // The caller can have the audio config criteria ignored by either passing a null ptr or
6492 // the AUDIO_CONFIG_INITIALIZER value.
6493 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006494 // some positional channel masks and PCM format and for stereo if low latency performance
6495 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006496
6497 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006498 const bool channel_mask_spatialized =
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00006499 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6500 ? audio_channel_mask_contains_stereo(config->channel_mask)
6501 : audio_is_channel_mask_spatialized(config->channel_mask);
Andy Hung481bfe32023-12-18 14:00:29 -08006502 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006503 return false;
6504 }
6505 if (!audio_is_linear_pcm(config->format)) {
6506 return false;
6507 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006508 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6509 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6510 return false;
6511 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006512 }
6513
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006514 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006515 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006516 if (profile == nullptr) {
6517 return false;
6518 }
6519
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006520 return true;
6521}
6522
Shunkai Yao4c3af932024-04-26 04:12:21 +00006523// The Spatializer output is compatible with Haptic use cases if:
6524// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6525// with client if client haptic channel bits were set, or
6526// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6527// including the haptic bits or creating the HapticGenerator effect for same session.
6528bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6529 const audio_config_t* config, audio_session_t sessionId) const {
6530 const auto clientHapticChannel =
6531 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6532 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6533 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6534
6535 if (threadOutputHapticChannel) {
6536 // check format and sampleRate match if client haptic channel mask exist
6537 if (clientHapticChannel) {
6538 return mSpatializerOutput->getFormat() == config->format &&
6539 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6540 }
6541 return true;
6542 } else {
6543 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6544 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6545 // HapticGenerator effect for this session) are not supported.
6546 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006547 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006548 }
6549}
6550
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006551void AudioPolicyManager::checkVirtualizerClientRoutes() {
6552 std::set<audio_stream_type_t> streamsToInvalidate;
6553 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006554 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6555 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006556 audio_attributes_t attr = client->attributes();
6557 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6558 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6559 audio_config_base_t clientConfig = client->config();
6560 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006561 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006562 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006563 streamsToInvalidate.insert(client->stream());
6564 }
6565 }
6566 }
6567
jiabinc44b3462022-12-08 12:52:31 -08006568 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006569}
6570
Eric Laurente191d1b2022-04-15 11:59:25 +02006571
6572bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6573 const sp<SwAudioOutputDescriptor>& outputDesc) {
6574 if (outputDesc->isDuplicated()) {
6575 return false;
6576 }
6577 DeviceVector devices = outputDesc->supportedDevices();
6578 for (size_t i = 0; i < mOutputs.size(); i++) {
6579 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6580 if (desc == outputDesc || desc->isDuplicated()) {
6581 continue;
6582 }
6583 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6584 if (!sharedDevices.isEmpty()
6585 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6586 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6587 return false;
6588 }
6589 }
6590 return true;
6591}
6592
6593
Eric Laurentfa0f6742021-08-17 18:39:44 +02006594status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006595 const audio_attributes_t *attr,
6596 audio_io_handle_t *output) {
6597 *output = AUDIO_IO_HANDLE_NONE;
6598
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006599 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6600 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6601 audio_config_t *configPtr = nullptr;
6602 audio_config_t config;
6603 if (mixerConfig != nullptr) {
6604 config = audio_config_initializer(mixerConfig);
6605 configPtr = &config;
6606 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006607 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006608 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006609 return BAD_VALUE;
6610 }
6611
6612 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006613 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006614 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006615 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006616 return BAD_VALUE;
6617 }
6618
Eric Laurente191d1b2022-04-15 11:59:25 +02006619 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006620 for (size_t i = 0; i < mOutputs.size(); i++) {
6621 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006622 if (!desc->isDuplicated()
6623 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6624 spatializerOutputs.push_back(desc);
6625 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006626 }
6627 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006628 mSpatializerOutput.clear();
6629 bool outputsChanged = false;
6630 for (const auto& desc : spatializerOutputs) {
6631 if (desc->mProfile == profile
6632 && (configPtr == nullptr
6633 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6634 mSpatializerOutput = desc;
6635 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6636 } else {
6637 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6638 " and devices %s", __func__, desc->mIoHandle,
6639 configPtr != nullptr ? configPtr->channel_mask : 0,
6640 devices.toString().c_str());
6641 closeOutput(desc->mIoHandle);
6642 outputsChanged = true;
6643 }
Eric Laurent39095982021-08-24 18:29:27 +02006644 }
6645
Eric Laurente191d1b2022-04-15 11:59:25 +02006646 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006647 sp<SwAudioOutputDescriptor> desc =
6648 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006649 if (desc != nullptr) {
6650 mSpatializerOutput = desc;
6651 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006652 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006653 }
6654
6655 checkVirtualizerClientRoutes();
6656
Eric Laurente191d1b2022-04-15 11:59:25 +02006657 if (outputsChanged) {
6658 mPreviousOutputs = mOutputs;
6659 mpClientInterface->onAudioPortListUpdate();
6660 }
6661
6662 if (mSpatializerOutput == nullptr) {
6663 ALOGV("%s could not open spatializer output with requested config", __func__);
6664 return BAD_VALUE;
6665 }
Eric Laurent39095982021-08-24 18:29:27 +02006666 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006667 ALOGV("%s returning new spatializer output %d", __func__, *output);
6668 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006669}
6670
Eric Laurentfa0f6742021-08-17 18:39:44 +02006671status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6672 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006673 return INVALID_OPERATION;
6674 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006675 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006676 return BAD_VALUE;
6677 }
Eric Laurent39095982021-08-24 18:29:27 +02006678
Eric Laurente191d1b2022-04-15 11:59:25 +02006679 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6680 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6681 closeOutput(mSpatializerOutput->mIoHandle);
6682 //from now on mSpatializerOutput is null
6683 checkVirtualizerClientRoutes();
6684 }
Eric Laurent39095982021-08-24 18:29:27 +02006685
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006686 return NO_ERROR;
6687}
6688
Eric Laurente552edb2014-03-10 17:42:56 -07006689// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006690// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006691// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006692uint32_t AudioPolicyManager::nextAudioPortGeneration()
6693{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006694 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006695}
6696
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006697AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006698 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006699 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006700 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006701 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006702 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006703 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006704 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006705 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006706 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006707 mAudioPortGeneration(1),
6708 mBeaconMuteRefCount(0),
6709 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006710 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006711 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006712 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006713 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006714{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006715}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006716
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006717status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006718 if (mEngine == nullptr) {
6719 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006720 }
6721 mEngine->setObserver(this);
6722 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006723 if (status != NO_ERROR) {
6724 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6725 return status;
6726 }
François Gaffie2110e042015-03-24 08:41:51 +01006727
jiabin29230182023-04-04 21:02:36 +00006728 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6729 // at the end of this function.
6730 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006731 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6732 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6733
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006734 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006735 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006736 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006737
Eric Laurent3a4311c2014-03-17 12:00:47 -07006738 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006739 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6740 defaultOutputDevice == nullptr ||
6741 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6742 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6743 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006744 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006745 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006746 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006747
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006748 // Silence ALOGV statements
6749 property_set("log.tag." LOG_TAG, "D");
6750
Eric Laurente552edb2014-03-10 17:42:56 -07006751 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006752 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006753}
6754
Eric Laurente0720872014-03-11 09:30:41 -07006755AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006756{
Eric Laurente552edb2014-03-10 17:42:56 -07006757 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006758 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006759 }
6760 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006761 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006762 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006763 mAvailableOutputDevices.clear();
6764 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006765 mOutputs.clear();
6766 mInputs.clear();
6767 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006768 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006769 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006770}
6771
Eric Laurente0720872014-03-11 09:30:41 -07006772status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006773{
Eric Laurent87ffa392015-05-22 10:32:38 -07006774 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006775}
6776
Eric Laurente552edb2014-03-10 17:42:56 -07006777// ---
6778
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006779void AudioPolicyManager::onNewAudioModulesAvailable()
6780{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006781 DeviceVector newDevices;
6782 onNewAudioModulesAvailableInt(&newDevices);
6783 if (!newDevices.empty()) {
6784 nextAudioPortGeneration();
6785 mpClientInterface->onAudioPortListUpdate();
6786 }
6787}
6788
6789void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6790{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006791 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006792 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6793 continue;
6794 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006795 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006796 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6797 handle != AUDIO_MODULE_HANDLE_NONE) {
6798 hwModule->setHandle(handle);
6799 } else {
6800 ALOGW("could not load HW module %s", hwModule->getName());
6801 continue;
6802 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006803 }
6804 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006805 // open all output streams needed to access attached devices.
6806 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006807 // This also validates mAvailableOutputDevices list
6808 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6809 if (!outProfile->canOpenNewIo()) {
6810 ALOGE("Invalid Output profile max open count %u for profile %s",
6811 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6812 continue;
6813 }
6814 if (!outProfile->hasSupportedDevices()) {
6815 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6816 continue;
6817 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006818 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6819 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006820 mTtsOutputAvailable = true;
6821 }
6822
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006823 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006824 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006825 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006826 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6827 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006828 } else {
6829 // choose first device present in profile's SupportedDevices also part of
6830 // mAvailableOutputDevices.
6831 if (availProfileDevices.isEmpty()) {
6832 continue;
6833 }
6834 supportedDevice = availProfileDevices.itemAt(0);
6835 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006836 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006837 continue;
6838 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306839
6840 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6841 && availProfileDevices.areAllDevicesAttached()) {
6842 ALOGV("%s skip opening output for mmap profile %s", __func__,
6843 outProfile->getTagName().c_str());
6844 continue;
6845 }
6846
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006847 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6848 mpClientInterface);
6849 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006850 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006851 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006852 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6853 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006854 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006855 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006856 if (status != NO_ERROR) {
6857 ALOGW("Cannot open output stream for devices %s on hw module %s",
6858 supportedDevice->toString().c_str(), hwModule->getName());
6859 continue;
6860 }
6861 for (const auto &device : availProfileDevices) {
6862 // give a valid ID to an attached device once confirmed it is reachable
6863 if (!device->isAttached()) {
6864 device->attach(hwModule);
6865 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006866 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006867 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006868 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6869 }
6870 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006871 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006872 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6873 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006874 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006875 }
Eric Laurent39095982021-08-24 18:29:27 +02006876 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006877 outputDesc->close();
6878 } else {
6879 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306880 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006881 DeviceVector(supportedDevice),
6882 true,
6883 0,
6884 NULL);
6885 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006886 }
6887 // open input streams needed to access attached devices to validate
6888 // mAvailableInputDevices list
6889 for (const auto& inProfile : hwModule->getInputProfiles()) {
6890 if (!inProfile->canOpenNewIo()) {
6891 ALOGE("Invalid Input profile max open count %u for profile %s",
6892 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6893 continue;
6894 }
6895 if (!inProfile->hasSupportedDevices()) {
6896 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6897 continue;
6898 }
6899 // chose first device present in profile's SupportedDevices also part of
6900 // available input devices
6901 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006902 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006903 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006904 ALOGV("%s: Input device list is empty! for profile %s",
6905 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006906 continue;
6907 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306908
6909 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6910 && availProfileDevices.areAllDevicesAttached()) {
6911 ALOGV("%s skip opening input for mmap profile %s", __func__,
6912 inProfile->getTagName().c_str());
6913 continue;
6914 }
6915
Eric Laurentc71b11b2024-06-03 12:54:53 +00006916 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6917 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006918
6919 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6920 status_t status = inputDesc->open(nullptr,
6921 availProfileDevices.itemAt(0),
6922 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306923 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006924 &input);
6925 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306926 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6927 __func__, availProfileDevices.toString().c_str(),
6928 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006929 continue;
6930 }
6931 for (const auto &device : availProfileDevices) {
6932 // give a valid ID to an attached device once confirmed it is reachable
6933 if (!device->isAttached()) {
6934 device->attach(hwModule);
6935 device->importAudioPortAndPickAudioProfile(inProfile, true);
6936 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006937 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006938 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6939 }
6940 }
6941 inputDesc->close();
6942 }
6943 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006944
6945 // Check if spatializer outputs can be closed until used.
6946 // mOutputs vector never contains duplicated outputs at this point.
6947 std::vector<audio_io_handle_t> outputsClosed;
6948 for (size_t i = 0; i < mOutputs.size(); i++) {
6949 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6950 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6951 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6952 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006953 nextAudioPortGeneration();
6954 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6955 if (index >= 0) {
6956 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6957 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6958 patchDesc->getAfHandle(), 0);
6959 mAudioPatches.removeItemsAt(index);
6960 mpClientInterface->onAudioPatchListUpdate();
6961 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006962 desc->close();
6963 }
6964 }
6965 for (auto output : outputsClosed) {
6966 removeOutput(output);
6967 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006968}
6969
Eric Laurent98e38192018-02-15 18:31:53 -08006970void AudioPolicyManager::addOutput(audio_io_handle_t output,
6971 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006972{
Eric Laurent1c333e22014-05-20 10:48:17 -07006973 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006974 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006975 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006976 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006977 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006978}
6979
François Gaffie53615e22015-03-19 09:24:12 +01006980void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6981{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006982 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6983 ALOGV("%s: removing primary output", __func__);
6984 mPrimaryOutput = nullptr;
6985 }
François Gaffie53615e22015-03-19 09:24:12 +01006986 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006987 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006988}
6989
Eric Laurent98e38192018-02-15 18:31:53 -08006990void AudioPolicyManager::addInput(audio_io_handle_t input,
6991 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006992{
Eric Laurent1c333e22014-05-20 10:48:17 -07006993 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006994 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006995}
Eric Laurente552edb2014-03-10 17:42:56 -07006996
François Gaffie11d30102018-11-02 16:09:09 +01006997status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006998 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006999 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007000{
François Gaffie11d30102018-11-02 16:09:09 +01007001 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07007002 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07007003 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07007004
François Gaffie11d30102018-11-02 16:09:09 +01007005 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007006 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007007 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007008 }
Eric Laurente552edb2014-03-10 17:42:56 -07007009
Eric Laurent3b73df72014-03-11 09:06:29 -07007010 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07007011 // first call getAudioPort to get the supported attributes from the HAL
7012 struct audio_port_v7 port = {};
7013 device->toAudioPort(&port);
7014 status_t status = mpClientInterface->getAudioPort(&port);
7015 if (status == NO_ERROR) {
7016 device->importAudioPort(port);
7017 }
7018
7019 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07007020 for (size_t i = 0; i < mOutputs.size(); i++) {
7021 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007022 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07007023 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01007024 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
7025 mOutputs.keyAt(i), device->toString().c_str());
7026 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007027 }
7028 }
7029 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007030 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007031 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007032 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7033 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01007034 if (profile->supportsDevice(device)) {
7035 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307036 ALOGV("%s(): adding profile %s from module %s",
7037 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07007038 }
7039 }
7040 }
7041
Eric Laurent7b279bb2015-12-14 10:18:23 -08007042 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007043
Eric Laurente552edb2014-03-10 17:42:56 -07007044 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007045 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007046 return BAD_VALUE;
7047 }
7048
7049 // open outputs for matching profiles if needed. Direct outputs are also opened to
7050 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7051 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007052 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07007053
7054 // nothing to do if one output is already opened for this profile
7055 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007056 for (j = 0; j < outputs.size(); j++) {
7057 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07007058 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007059 // matching profile: save the sample rates, format and channel masks supported
7060 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01007061 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07007062 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007063 }
Eric Laurente552edb2014-03-10 17:42:56 -07007064 break;
7065 }
7066 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007067 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07007068 continue;
7069 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307070 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7071 ALOGV("%s skip opening output for mmap profile %s",
7072 __func__, profile->getTagName().c_str());
7073 continue;
7074 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007075 if (!profile->canOpenNewIo()) {
7076 ALOGW("Max Output number %u already opened for this profile %s",
7077 profile->maxOpenCount, profile->getTagName().c_str());
7078 continue;
7079 }
7080
Eric Laurent83efe1c2017-07-09 16:51:08 -07007081 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00007082 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07007083 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
7084 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07007085 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01007086 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007087 profiles.removeAt(profile_index);
7088 profile_index--;
7089 } else {
7090 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07007091 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01007092 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07007093 // TODO: when getAudioPort is ready, it may not be needed to import the audio
7094 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07007095 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007096 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007097
François Gaffie11d30102018-11-02 16:09:09 +01007098 if (device_distinguishes_on_address(deviceType)) {
7099 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
7100 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307101 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
7102 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007103 }
Eric Laurente552edb2014-03-10 17:42:56 -07007104 ALOGV("checkOutputsForDevice(): adding output %d", output);
7105 }
7106 }
7107
7108 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007109 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007110 return BAD_VALUE;
7111 }
Eric Laurentd4692962014-05-05 18:13:44 -07007112 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07007113 // check if one opened output is not needed any more after disconnecting one device
7114 for (size_t i = 0; i < mOutputs.size(); i++) {
7115 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007116 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007117 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007118 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01007119 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01007120 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01007121 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007122 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7123 mOutputs.keyAt(i));
7124 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007125 }
Eric Laurente552edb2014-03-10 17:42:56 -07007126 }
7127 }
Eric Laurentd4692962014-05-05 18:13:44 -07007128 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007129 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007130 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7131 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007132 if (!profile->supportsDevice(device)) {
7133 continue;
7134 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307135 ALOGV("%s(): clearing direct output profile %s on module %s",
7136 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007137 profile->clearAudioProfiles();
7138 if (!profile->hasDynamicAudioProfile()) {
7139 continue;
7140 }
7141 // When a device is disconnected, if there is an IOProfile that contains dynamic
7142 // profiles and supports the disconnected device, call getAudioPort to repopulate
7143 // the capabilities of the devices that is supported by the IOProfile.
7144 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7145 if (supportedDevice == device ||
7146 !mAvailableOutputDevices.contains(supportedDevice)) {
7147 continue;
7148 }
7149 struct audio_port_v7 port;
7150 supportedDevice->toAudioPort(&port);
7151 status_t status = mpClientInterface->getAudioPort(&port);
7152 if (status == NO_ERROR) {
7153 supportedDevice->importAudioPort(port);
7154 }
Eric Laurente552edb2014-03-10 17:42:56 -07007155 }
7156 }
7157 }
7158 }
7159 return NO_ERROR;
7160}
7161
François Gaffie11d30102018-11-02 16:09:09 +01007162status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007163 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007164{
François Gaffie11d30102018-11-02 16:09:09 +01007165 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007166 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007167 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007168 }
7169
Eric Laurentd4692962014-05-05 18:13:44 -07007170 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007171 sp<AudioInputDescriptor> desc;
7172
jiabinbf5f4262023-04-12 21:48:34 +00007173 // first call getAudioPort to get the supported attributes from the HAL
7174 struct audio_port_v7 port = {};
7175 device->toAudioPort(&port);
7176 status_t status = mpClientInterface->getAudioPort(&port);
7177 if (status == NO_ERROR) {
7178 device->importAudioPort(port);
7179 }
7180
Eric Laurent0dd51852019-04-19 18:18:58 -07007181 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007182 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007183 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007184 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007185 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007186 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007187 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007188
François Gaffie11d30102018-11-02 16:09:09 +01007189 if (profile->supportsDevice(device)) {
7190 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307191 ALOGV("%s : adding profile %s from module %s", __func__,
7192 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007193 }
7194 }
7195 }
7196
Eric Laurent0dd51852019-04-19 18:18:58 -07007197 if (profiles.isEmpty()) {
7198 ALOGW("%s: No input profile available for device %s",
7199 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007200 return BAD_VALUE;
7201 }
7202
7203 // open inputs for matching profiles if needed. Direct inputs are also opened to
7204 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7205 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7206
Eric Laurent1c333e22014-05-20 10:48:17 -07007207 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007208
Eric Laurentd4692962014-05-05 18:13:44 -07007209 // nothing to do if one input is already opened for this profile
7210 size_t input_index;
7211 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7212 desc = mInputs.valueAt(input_index);
7213 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007214 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007215 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007216 }
Eric Laurentd4692962014-05-05 18:13:44 -07007217 break;
7218 }
7219 }
7220 if (input_index != mInputs.size()) {
7221 continue;
7222 }
7223
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307224 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7225 ALOGV("%s skip opening input for mmap profile %s",
7226 __func__, profile->getTagName().c_str());
7227 continue;
7228 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007229 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307230 ALOGW("%s Max Input number %u already opened for this profile %s",
7231 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007232 continue;
7233 }
7234
Eric Laurentc71b11b2024-06-03 12:54:53 +00007235 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007236 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307237 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307238 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7239 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007240
Eric Laurentcf2c0212014-07-25 16:20:43 -07007241 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007242 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007243 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007244 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007245 mpClientInterface->setParameters(input, String8(param));
7246 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007247 }
jiabin12537fc2023-10-12 17:56:08 +00007248 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007249 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307250 ALOGW("%s direct input missing param for profile %s", __func__,
7251 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007252 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007253 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007254 }
7255
Eric Laurent0dd51852019-04-19 18:18:58 -07007256 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007257 addInput(input, desc);
7258 }
7259 } // endif input != 0
7260
Eric Laurentcf2c0212014-07-25 16:20:43 -07007261 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307262 ALOGW("%s could not open input for device %s on profile %s", __func__,
7263 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007264 profiles.removeAt(profile_index);
7265 profile_index--;
7266 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007267 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007268 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007269 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307270 ALOGV("%s: adding input %d for profile %s", __func__,
7271 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007272
7273 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307274 ALOGV("%s: closing input %d for profile %s", __func__,
7275 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007276 closeInput(input);
7277 }
Eric Laurentd4692962014-05-05 18:13:44 -07007278 }
7279 } // end scan profiles
7280
7281 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007282 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007283 return BAD_VALUE;
7284 }
7285 } else {
7286 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007287 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007288 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007289 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007290 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007291 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007292 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007293 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307294 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7295 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007296 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007297 }
7298 }
7299 }
7300 } // end disconnect
7301
7302 return NO_ERROR;
7303}
7304
7305
Eric Laurente0720872014-03-11 09:30:41 -07007306void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007307{
7308 ALOGV("closeOutput(%d)", output);
7309
François Gaffie1c878552018-11-22 16:53:21 +01007310 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7311 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007312 ALOGW("closeOutput() unknown output %d", output);
7313 return;
7314 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007315 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007316 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007317
Eric Laurente552edb2014-03-10 17:42:56 -07007318 // look for duplicated outputs connected to the output being removed.
7319 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007320 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7321 if (dupOutput->isDuplicated() &&
7322 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7323 sp<SwAudioOutputDescriptor> remainingOutput =
7324 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007325 // As all active tracks on duplicated output will be deleted,
7326 // and as they were also referenced on the other output, the reference
7327 // count for their stream type must be adjusted accordingly on
7328 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007329 const bool wasActive = remainingOutput->isActive();
7330 // Note: no-op on the closing output where all clients has already been set inactive
7331 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007332 // stop() will be a no op if the output is still active but is needed in case all
7333 // active streams refcounts where cleared above
7334 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007335 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007336 }
Eric Laurente552edb2014-03-10 17:42:56 -07007337 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7338 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7339
7340 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007341 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007342 }
7343 }
7344
Eric Laurent05b90f82014-08-27 15:32:29 -07007345 nextAudioPortGeneration();
7346
François Gaffie1c878552018-11-22 16:53:21 +01007347 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007348 if (index >= 0) {
7349 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007350 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7351 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007352 mAudioPatches.removeItemsAt(index);
7353 mpClientInterface->onAudioPatchListUpdate();
7354 }
7355
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007356 if (closingOutputWasActive) {
7357 closingOutput->stop();
7358 }
François Gaffie1c878552018-11-22 16:53:21 +01007359 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007360 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007361 for (const auto device : closingOutput->devices()) {
7362 device->setPreferredConfig(nullptr);
7363 }
7364 }
Eric Laurente552edb2014-03-10 17:42:56 -07007365
François Gaffie53615e22015-03-19 09:24:12 +01007366 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007367 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007368 if (closingOutput == mSpatializerOutput) {
7369 mSpatializerOutput.clear();
7370 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007371
7372 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7373 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007374 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007375 bool directOutputOpen = false;
7376 for (size_t i = 0; i < mOutputs.size(); i++) {
7377 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7378 directOutputOpen = true;
7379 break;
7380 }
7381 }
7382 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007383 ALOGV("no direct outputs open, reset MSD patches");
7384 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7385 // how output devices for patching are resolved. Avoid by caching and reusing the
7386 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7387 // devices to patch to. This may be complicated by the fact that devices may become
7388 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007389 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007390 }
7391 }
jiabin220eea12024-05-17 17:55:20 +00007392
7393 if (closingOutput->mPreferredAttrInfo != nullptr) {
7394 closingOutput->mPreferredAttrInfo->resetActiveClient();
7395 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007396}
7397
7398void AudioPolicyManager::closeInput(audio_io_handle_t input)
7399{
7400 ALOGV("closeInput(%d)", input);
7401
7402 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7403 if (inputDesc == NULL) {
7404 ALOGW("closeInput() unknown input %d", input);
7405 return;
7406 }
7407
Eric Laurent6a94d692014-05-20 11:18:06 -07007408 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007409
François Gaffie11d30102018-11-02 16:09:09 +01007410 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007411 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007412 if (index >= 0) {
7413 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007414 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7415 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007416 mAudioPatches.removeItemsAt(index);
7417 mpClientInterface->onAudioPatchListUpdate();
7418 }
7419
François Gaffie6ebbce02023-07-19 13:27:53 +02007420 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007421 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007422 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007423
François Gaffie11d30102018-11-02 16:09:09 +01007424 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7425 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007426 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007427 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007428 }
Eric Laurente552edb2014-03-10 17:42:56 -07007429}
7430
François Gaffie11d30102018-11-02 16:09:09 +01007431SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7432 const DeviceVector &devices,
7433 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007434{
7435 SortedVector<audio_io_handle_t> outputs;
7436
François Gaffie11d30102018-11-02 16:09:09 +01007437 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007438 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007439 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007440 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007441 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007442 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007443 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007444 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007445 outputs.add(openOutputs.keyAt(i));
7446 }
7447 }
7448 return outputs;
7449}
7450
Mikhail Naganov37977152018-07-11 15:54:44 -07007451void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7452{
7453 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7454 // output is suspended before any tracks are moved to it
7455 checkA2dpSuspend();
7456 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007457 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007458 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007459 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007460 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007461 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7462 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7463 // configuration changes will ultimately be rerouted correctly. We can still avoid
7464 // unnecessary rerouting by caching and reusing the arguments to
7465 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7466 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007467 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007468 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007469 // an event that changed routing likely occurred, inform upper layers
7470 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007471}
7472
François Gaffiec005e562018-11-06 15:04:49 +01007473bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7474 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007475{
François Gaffiec005e562018-11-06 15:04:49 +01007476 return mEngine->getProductStrategyForAttributes(lAttr) ==
7477 mEngine->getProductStrategyForAttributes(rAttr);
7478}
7479
Francois Gaffieff1eb522020-05-06 18:37:04 +02007480void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7481{
7482 for (size_t i = 0; i < mAudioSources.size(); i++) {
7483 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7484 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007485 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007486 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007487 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007488 }
7489 }
7490}
7491
7492void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7493{
7494 for (size_t i = 0; i < mAudioSources.size(); i++) {
7495 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7496 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7497 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7498 disconnectAudioSource(sourceDesc);
7499 }
7500 }
7501}
7502
François Gaffiec005e562018-11-06 15:04:49 +01007503void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7504{
7505 auto psId = mEngine->getProductStrategyForAttributes(attr);
7506
7507 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7508 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007509
François Gaffie11d30102018-11-02 16:09:09 +01007510 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7511 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007512
Eric Laurentc209fe42020-06-05 18:11:23 -07007513 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007514 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007515 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007516 // take into account dynamic audio policies related changes: if a client is now associated
7517 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007518 // invalidate clients on outputs that do not support all the newly selected devices for the
7519 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007520 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007521 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007522 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007523 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007524 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007525
Eric Laurentc209fe42020-06-05 18:11:23 -07007526 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7527 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7528 continue;
7529 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007530 if (!desc->supportsAllDevices(newDevices)) {
7531 invalidatedOutputs.push_back(desc);
7532 break;
7533 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007534 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007535 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007536 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7537 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7538 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007539 if (status == OK) {
7540 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7541 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7542 maxLatency = desc->latency();
7543 }
7544 invalidatedOutputs.push_back(desc);
7545 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007546 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007547 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007548 }
7549 }
7550
Eric Laurent56ed8842022-11-15 16:04:41 +01007551 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007552 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7553 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007554 for (audio_io_handle_t srcOut : srcOutputs) {
7555 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007556 if (desc == nullptr) continue;
7557
7558 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007559 maxLatency = desc->latency();
7560 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007561
Eric Laurent56ed8842022-11-15 16:04:41 +01007562 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007563 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007564 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007565 // a client on a non direct outputs has necessarily a linear PCM format
7566 // so we can call selectOutput() safely
7567 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7568 client->flags(),
7569 client->config().format,
7570 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007571 client->config().sample_rate,
7572 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007573 if (newOutput != srcOut) {
7574 invalidate = true;
7575 break;
7576 }
7577 } else {
7578 sp<IOProfile> profile = getProfileForOutput(newDevices,
7579 client->config().sample_rate,
7580 client->config().format,
7581 client->config().channel_mask,
7582 client->flags(),
7583 true /* directOnly */);
7584 if (profile != desc->mProfile) {
7585 invalidate = true;
7586 break;
7587 }
7588 }
7589 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007590 // mute strategy while moving tracks from one output to another
7591 if (invalidate) {
7592 invalidatedOutputs.push_back(desc);
7593 if (desc->isStrategyActive(psId)) {
7594 setStrategyMute(psId, true, desc);
7595 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7596 newDevices.types());
7597 }
Eric Laurente552edb2014-03-10 17:42:56 -07007598 }
François Gaffiec005e562018-11-06 15:04:49 +01007599 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007600 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007601 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007602 }
Eric Laurente552edb2014-03-10 17:42:56 -07007603 }
7604
Eric Laurent56ed8842022-11-15 16:04:41 +01007605 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7606 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7607 std::to_string(srcOutputs[0]).c_str(),
7608 std::to_string(dstOutputs[0]).c_str());
7609
François Gaffiec005e562018-11-06 15:04:49 +01007610 // Move effects associated to this stream from previous output to new output
7611 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007612 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007613 }
François Gaffiec005e562018-11-06 15:04:49 +01007614 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007615 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007616 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007617 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007618 desc->setTracksInvalidatedStatusByStrategy(psId);
7619 }
Eric Laurente552edb2014-03-10 17:42:56 -07007620 }
7621 }
7622}
7623
Eric Laurente0720872014-03-11 09:30:41 -07007624void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007625{
François Gaffiec005e562018-11-06 15:04:49 +01007626 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7627 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7628 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007629 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007630 }
Eric Laurente552edb2014-03-10 17:42:56 -07007631}
7632
Kevin Rocard153f92d2018-12-18 18:33:28 -08007633void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007634 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007635 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007636 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007637 for (size_t i = 0; i < mOutputs.size(); i++) {
7638 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7639 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007640 sp<AudioPolicyMix> primaryMix;
7641 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007642 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007643 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7644 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7645 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007646 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7647 for (auto &secondaryMix : secondaryMixes) {
7648 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7649 if (outputDesc != nullptr &&
7650 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7651 secondaryDescs.push_back(outputDesc);
7652 }
7653 }
7654
jiabinc44b3462022-12-08 12:52:31 -08007655 if (status != OK &&
7656 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7657 // When it failed to query secondary output, only invalidate the client that is not
7658 // MMAP. The reason is that MMAP stream will not support secondary output.
7659 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007660 } else if (!std::equal(
7661 client->getSecondaryOutputs().begin(),
7662 client->getSecondaryOutputs().end(),
7663 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007664 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7665 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007666 // If the format is not PCM, the tracks should be invalidated to get correct
7667 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007668 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007669 } else {
7670 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7671 std::vector<audio_io_handle_t> secondaryOutputIds;
7672 for (const auto &secondaryDesc: secondaryDescs) {
7673 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7674 weakSecondaryDescs.push_back(secondaryDesc);
7675 }
7676 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7677 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007678 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007679 }
7680 }
7681 }
jiabin10a03f12021-05-07 23:46:28 +00007682 if (!trackSecondaryOutputs.empty()) {
7683 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7684 }
jiabinc44b3462022-12-08 12:52:31 -08007685 if (!clientsToInvalidate.empty()) {
7686 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7687 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007688 }
7689}
7690
Eric Laurent2517af32020-11-25 15:31:27 +01007691bool AudioPolicyManager::isScoRequestedForComm() const {
7692 AudioDeviceTypeAddrVector devices;
7693 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7694 for (const auto &device : devices) {
7695 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7696 return true;
7697 }
7698 }
7699 return false;
7700}
7701
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007702bool AudioPolicyManager::isHearingAidUsedForComm() const {
7703 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7704 true /*fromCache*/);
7705 for (const auto &device : devices) {
7706 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7707 return true;
7708 }
7709 }
7710 return false;
7711}
7712
7713
Eric Laurente0720872014-03-11 09:30:41 -07007714void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007715{
François Gaffie53615e22015-03-19 09:24:12 +01007716 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007717 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007718 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007719 return;
7720 }
7721
Eric Laurent3a4311c2014-03-17 12:00:47 -07007722 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007723 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7724 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007725 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007726
7727 // if suspended, restore A2DP output if:
7728 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007729 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007730 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007731 //
Eric Laurentf732e072016-08-03 19:30:28 -07007732 // if not suspended, suspend A2DP output if:
7733 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007734 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007735 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007736 //
7737 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007738 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007739 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007740 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007741 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007742
7743 mpClientInterface->restoreOutput(a2dpOutput);
7744 mA2dpSuspended = false;
7745 }
7746 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007747 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007748 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007749 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007750 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007751
7752 mpClientInterface->suspendOutput(a2dpOutput);
7753 mA2dpSuspended = true;
7754 }
7755 }
7756}
7757
François Gaffie11d30102018-11-02 16:09:09 +01007758DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7759 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007760{
François Gaffiedb1755b2023-09-01 11:50:35 +02007761 if (outputDesc == nullptr) {
7762 return DeviceVector{};
7763 }
François Gaffie11d30102018-11-02 16:09:09 +01007764
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007765 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007766 if (index >= 0) {
7767 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007768 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007769 ALOGV("%s device %s forced by patch %d", __func__,
7770 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7771 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007772 }
7773 }
7774
Dean Wheatley514b4312020-06-17 21:45:00 +10007775 // Do not retrieve engine device for outputs through MSD
7776 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7777 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7778 return outputDesc->devices();
7779 }
7780
Eric Laurent97ac8712018-07-27 18:59:02 -07007781 // Honor explicit routing requests only if no client using default routing is active on this
7782 // input: a specific app can not force routing for other apps by setting a preferred device.
7783 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007784 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007785 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007786 if (device != nullptr) {
7787 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007788 }
7789
François Gaffiea807ef92018-11-05 10:44:33 +01007790 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7791 // of setForceUse / Default Bus device here
7792 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7793 if (device != nullptr) {
7794 return DeviceVector(device);
7795 }
7796
François Gaffiedb1755b2023-09-01 11:50:35 +02007797 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007798 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7799 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307800 auto hasStreamActive = [&](auto stream) {
7801 return hasStream(streams, stream) && isStreamActive(stream, 0);
7802 };
Eric Laurent484e9272018-06-07 17:29:23 -07007803
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307804 auto doGetOutputDevicesForVoice = [&]() {
7805 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007806 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307807 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007808 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7809 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307810 };
7811
7812 // With low-latency playing on speaker, music on WFD, when the first low-latency
7813 // output is stopped, getNewOutputDevices checks for a product strategy
7814 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007815 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307816 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7817 // stream is associated to the output descriptor.
7818 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7819 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7820 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7821 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007822 // Retrieval of devices for voice DL is done on primary output profile, cannot
7823 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007824 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007825 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7826 break;
7827 }
Eric Laurente552edb2014-03-10 17:42:56 -07007828 }
François Gaffiec005e562018-11-06 15:04:49 +01007829 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007830 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007831}
7832
François Gaffie11d30102018-11-02 16:09:09 +01007833sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7834 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007835{
François Gaffie11d30102018-11-02 16:09:09 +01007836 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007837
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007838 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007839 if (index >= 0) {
7840 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007841 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007842 ALOGV("getNewInputDevice() device %s forced by patch %d",
7843 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7844 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007845 }
7846 }
7847
Eric Laurent97ac8712018-07-27 18:59:02 -07007848 // Honor explicit routing requests only if no client using default routing is active on this
7849 // input: a specific app can not force routing for other apps by setting a preferred device.
7850 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007851 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7852 if (device != nullptr) {
7853 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007854 }
7855
Eric Laurentdc95a252018-04-12 12:46:56 -07007856 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007857 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007858 audio_attributes_t attributes;
7859 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007860 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007861 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7862 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007863 attributes = topClient->attributes();
7864 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007865 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007866 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007867 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7868 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007869 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007870 }
7871
Francois Gaffie716e1432019-01-14 16:58:59 +01007872 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7873 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007874 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007875 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007876 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007877 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007878
Eric Laurente552edb2014-03-10 17:42:56 -07007879 return device;
7880}
7881
Eric Laurent794fde22016-03-11 09:50:45 -08007882bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7883 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007884 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007885}
7886
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007887status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007888 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007889 if (devices == nullptr) {
7890 return BAD_VALUE;
7891 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007892
Andy Hung6d23c0f2022-02-16 09:37:15 -08007893 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007894 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7895 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007896 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007897 for (const auto& device : curDevices) {
7898 devices->push_back(device->getDeviceTypeAddr());
7899 }
7900 return NO_ERROR;
7901}
7902
Eric Laurente0720872014-03-11 09:30:41 -07007903void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007904 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007905 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007906 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007907 updateDevicesAndOutputs();
7908 break;
7909 default:
7910 break;
7911 }
7912}
7913
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007914uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007915
7916 // skip beacon mute management if a dedicated TTS output is available
7917 if (mTtsOutputAvailable) {
7918 return 0;
7919 }
7920
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007921 switch(event) {
7922 case STARTING_OUTPUT:
7923 mBeaconMuteRefCount++;
7924 break;
7925 case STOPPING_OUTPUT:
7926 if (mBeaconMuteRefCount > 0) {
7927 mBeaconMuteRefCount--;
7928 }
7929 break;
7930 case STARTING_BEACON:
7931 mBeaconPlayingRefCount++;
7932 break;
7933 case STOPPING_BEACON:
7934 if (mBeaconPlayingRefCount > 0) {
7935 mBeaconPlayingRefCount--;
7936 }
7937 break;
7938 }
7939
7940 if (mBeaconMuteRefCount > 0) {
7941 // any playback causes beacon to be muted
7942 return setBeaconMute(true);
7943 } else {
7944 // no other playback: unmute when beacon starts playing, mute when it stops
7945 return setBeaconMute(mBeaconPlayingRefCount == 0);
7946 }
7947}
7948
7949uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7950 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7951 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7952 // keep track of muted state to avoid repeating mute/unmute operations
7953 if (mBeaconMuted != mute) {
7954 // mute/unmute AUDIO_STREAM_TTS on all outputs
7955 ALOGV("\t muting %d", mute);
7956 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007957 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7958 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7959 ALOGV("\t no tts volume source available");
7960 return 0;
7961 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007962 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007963 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Vlad Popa1e865e62024-08-15 19:11:42 -07007964 setVolumeSourceMutedInternally(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/,
7965 DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007966 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007967 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007968 maxLatency = latency;
7969 }
7970 }
7971 mBeaconMuted = mute;
7972 return maxLatency;
7973 }
7974 return 0;
7975}
7976
Eric Laurente0720872014-03-11 09:30:41 -07007977void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007978{
François Gaffiec005e562018-11-06 15:04:49 +01007979 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007980 mPreviousOutputs = mOutputs;
7981}
7982
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007983uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007984 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007985 uint32_t delayMs)
7986{
7987 // mute/unmute strategies using an incompatible device combination
7988 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7989 // if unmuting, unmute only after the specified delay
7990 if (outputDesc->isDuplicated()) {
7991 return 0;
7992 }
7993
7994 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007995 DeviceVector devices = outputDesc->devices();
7996 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007997
François Gaffiec005e562018-11-06 15:04:49 +01007998 auto productStrategies = mEngine->getOrderedProductStrategies();
7999 for (const auto &productStrategy : productStrategies) {
8000 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
8001 DeviceVector curDevices =
8002 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
8003 curDevices = curDevices.filter(outputDesc->supportedDevices());
8004 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07008005 bool doMute = false;
8006
François Gaffiec005e562018-11-06 15:04:49 +01008007 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07008008 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01008009 outputDesc->setStrategyMutedByDevice(productStrategy, true);
8010 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07008011 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01008012 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07008013 }
Eric Laurent99401132014-05-07 19:48:15 -07008014 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07008015 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07008016 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07008017 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01008018 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07008019 continue;
8020 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308021 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01008022 mute ? "muting" : "unmuting", curDevices.toString().c_str());
8023 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
8024 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07008025 if (mute) {
8026 // FIXME: should not need to double latency if volume could be applied
8027 // immediately by the audioflinger mixer. We must account for the delay
8028 // between now and the next time the audioflinger thread for this output
8029 // will process a buffer (which corresponds to one buffer size,
8030 // usually 1/2 or 1/4 of the latency).
8031 if (muteWaitMs < desc->latency() * 2) {
8032 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07008033 }
8034 }
8035 }
8036 }
8037 }
8038 }
8039
Eric Laurent99401132014-05-07 19:48:15 -07008040 // temporary mute output if device selection changes to avoid volume bursts due to
8041 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01008042 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07008043 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008044
Eric Laurentdc462862016-07-19 12:29:53 -07008045 if (muteWaitMs < tempMuteWaitMs) {
8046 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07008047 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008048
8049 // If recommended duration is defined, replace temporary mute duration to avoid
8050 // truncated notifications at beginning, which depends on duration of changing path in HAL.
8051 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
8052 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
8053 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
8054 tempRecommendedMuteDuration : outputDesc->latency() * 4;
8055
François Gaffieaaac0fd2018-11-22 17:56:39 +01008056 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
8057 // make sure that we do not start the temporary mute period too early in case of
8058 // delayed device change
Vlad Popa1e865e62024-08-15 19:11:42 -07008059 setVolumeSourceMutedInternally(activeVs, true, outputDesc, delayMs);
8060 setVolumeSourceMutedInternally(activeVs, false, outputDesc,
8061 delayMs + tempMuteDurationMs,
8062 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07008063 }
8064 }
8065
Eric Laurente552edb2014-03-10 17:42:56 -07008066 // wait for the PCM output buffers to empty before proceeding with the rest of the command
8067 if (muteWaitMs > delayMs) {
8068 muteWaitMs -= delayMs;
8069 usleep(muteWaitMs * 1000);
8070 return muteWaitMs;
8071 }
8072 return 0;
8073}
8074
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308075uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
8076 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01008077 const DeviceVector &devices,
8078 bool force,
8079 int delayMs,
8080 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008081 bool requiresMuteCheck, bool requiresVolumeCheck,
8082 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07008083{
jiabin3ff8d7d2022-12-13 06:27:44 +00008084 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308085 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
8086 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
8087 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008088 uint32_t muteWaitMs;
8089
8090 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308091 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008092 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308093 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008094 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07008095 return muteWaitMs;
8096 }
Eric Laurente552edb2014-03-10 17:42:56 -07008097
8098 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01008099 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008100 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02008101 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008102
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308103 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
8104 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01008105
8106 if (!filteredDevices.isEmpty()) {
8107 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008108 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008109
8110 // if the outputs are not materially active, there is no need to mute.
8111 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01008112 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008113 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308114 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
8115 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008116 muteWaitMs = 0;
8117 }
Eric Laurente552edb2014-03-10 17:42:56 -07008118
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008119 bool outputRouted = outputDesc->isRouted();
8120
Eric Laurent79ea9582020-06-11 18:49:24 -07008121 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8122 // output profile or if new device is not supported AND previous device(s) is(are) still
8123 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02008124 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308125 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8126 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07008127 // restore previous device after evaluating strategy mute state
8128 outputDesc->setDevices(prevDevices);
8129 return muteWaitMs;
8130 }
8131
Eric Laurente552edb2014-03-10 17:42:56 -07008132 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008133 // the requested device is AUDIO_DEVICE_NONE
8134 // OR the requested device is the same as current device
8135 // AND force is not specified
8136 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008137 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008138 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308139 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8140 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8141 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008142 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308143 ALOGV("%s %s setting same device on routed output, force apply volumes",
8144 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008145 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8146 }
Eric Laurente552edb2014-03-10 17:42:56 -07008147 return muteWaitMs;
8148 }
8149
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308150 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8151 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008152
Eric Laurente552edb2014-03-10 17:42:56 -07008153 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008154 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008155 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008156 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008157 PatchBuilder patchBuilder;
8158 patchBuilder.addSource(outputDesc);
8159 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8160 for (const auto &filteredDevice : filteredDevices) {
8161 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008162 }
8163
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008164 // Add half reported latency to delayMs when muteWaitMs is null in order
8165 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008166 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8167 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8168 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008169 }
Eric Laurente552edb2014-03-10 17:42:56 -07008170
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008171 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8172 if (!skipMuteDelay) {
8173 // update stream volumes according to new device
8174 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8175 }
Eric Laurente552edb2014-03-10 17:42:56 -07008176
8177 return muteWaitMs;
8178}
8179
Eric Laurentc75307b2015-03-17 15:29:32 -07008180status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008181 int delayMs,
8182 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008183{
Eric Laurent6a94d692014-05-20 11:18:06 -07008184 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008185 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8186 return INVALID_OPERATION;
8187 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008188 if (patchHandle) {
8189 index = mAudioPatches.indexOfKey(*patchHandle);
8190 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008191 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008192 }
8193 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008194 return INVALID_OPERATION;
8195 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008196 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008197 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008198 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008199 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008200 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008201 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008202 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008203 return status;
8204}
8205
8206status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008207 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008208 bool force,
8209 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008210{
8211 status_t status = NO_ERROR;
8212
Eric Laurent1f2f2232014-06-02 12:01:23 -07008213 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008214 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8215 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008216
François Gaffie11d30102018-11-02 16:09:09 +01008217 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008218 PatchBuilder patchBuilder;
8219 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008220 // AUDIO_SOURCE_HOTWORD is for internal use only:
8221 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008222 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8223 auto result = usecase;
8224 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8225 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8226 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008227 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008228 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008229 if (audio_is_remote_submix_device(device->type())) {
8230 // remote submix HAL does not support audio conversion, need source device
8231 // audio config to match the sink input descriptor audio config, otherwise AIDL
8232 // HAL patching will fail
8233 audio_port_config srcDevicePortConfig = {};
8234 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8235 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8236 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8237 srcDevicePortConfig.format = inputDesc->getFormat();
8238 patchBuilder.addSource(srcDevicePortConfig);
8239 } else {
8240 patchBuilder.addSource(device);
8241 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008242 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008243 }
8244 }
8245 return status;
8246}
8247
Eric Laurent6a94d692014-05-20 11:18:06 -07008248status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8249 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008250{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008251 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008252 ssize_t index;
8253 if (patchHandle) {
8254 index = mAudioPatches.indexOfKey(*patchHandle);
8255 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008256 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008257 }
8258 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008259 return INVALID_OPERATION;
8260 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008261 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008262 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008263 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008264 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008265 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008266 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008267 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008268 return status;
8269}
8270
François Gaffie11d30102018-11-02 16:09:09 +01008271sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008272 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008273 audio_format_t& format,
8274 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008275 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008276{
8277 // Choose an input profile based on the requested capture parameters: select the first available
8278 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008279 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008280
Atneya Nair0f0a8032022-12-12 16:20:12 -08008281 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8282 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8283 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8284
8285 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008286
jiabin2fd710d2022-05-02 23:20:22 +00008287 for (;;) {
jiabin91beb492024-10-16 21:53:36 +00008288 sp<IOProfile> inexact = nullptr;
jiabin5e02d2b2024-09-23 19:26:19 +00008289 uint32_t inexactSamplingRate = 0;
8290 audio_format_t inexactFormat = AUDIO_FORMAT_INVALID;
8291 audio_channel_mask_t inexactChannelMask = AUDIO_CHANNEL_INVALID;
jiabin2fd710d2022-05-02 23:20:22 +00008292 uint32_t updatedSamplingRate = 0;
8293 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8294 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8295 for (const auto& hwModule : mHwModules) {
8296 for (const auto& profile : hwModule->getInputProfiles()) {
8297 // profile->log();
8298 //updatedFormat = format;
jiabin91beb492024-10-16 21:53:36 +00008299 auto compatibleScore = profile->getCompatibilityScore(
jiabin66acc432024-02-06 00:57:36 +00008300 DeviceVector(device),
8301 samplingRate,
8302 &updatedSamplingRate,
8303 format,
8304 &updatedFormat,
8305 channelMask,
8306 &updatedChannelMask,
8307 // FIXME ugly cast
jiabin91beb492024-10-16 21:53:36 +00008308 (audio_output_flags_t) flags);
8309 if (compatibleScore == IOProfile::EXACT_MATCH) {
jiabin66acc432024-02-06 00:57:36 +00008310 samplingRate = updatedSamplingRate;
8311 format = updatedFormat;
8312 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008313 return profile;
jiabin91beb492024-10-16 21:53:36 +00008314 } else if ((flags != AUDIO_INPUT_FLAG_NONE
8315 && compatibleScore == IOProfile::PARTIAL_MATCH_WITH_FLAG)
8316 || (inexact == nullptr && compatibleScore != IOProfile::NO_MATCH)) {
8317 inexact = profile;
jiabin5e02d2b2024-09-23 19:26:19 +00008318 inexactSamplingRate = updatedSamplingRate;
8319 inexactFormat = updatedFormat;
8320 inexactChannelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008321 }
8322 }
8323 }
8324
jiabin91beb492024-10-16 21:53:36 +00008325 if (inexact != nullptr) {
jiabin5e02d2b2024-09-23 19:26:19 +00008326 samplingRate = inexactSamplingRate;
8327 format = inexactFormat;
8328 channelMask = inexactChannelMask;
jiabin91beb492024-10-16 21:53:36 +00008329 return inexact;
jiabin2fd710d2022-05-02 23:20:22 +00008330 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8331 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8332 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8333 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8334 flags = AUDIO_INPUT_FLAG_NONE;
8335 } else { // fail
8336 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8337 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8338 samplingRate, format, channelMask, oriFlags);
8339 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008340 }
8341 }
jiabin2fd710d2022-05-02 23:20:22 +00008342
8343 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008344}
8345
Vlad Popa87e0e582024-05-20 18:49:20 -07008346float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8347 VolumeSource volumeSource,
8348 int index,
8349 const DeviceTypeSet &deviceTypes)
8350{
8351 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8352 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8353 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8354
8355 if (com_android_media_audio_abs_volume_index_fix()) {
Vlad Popa08502d82024-10-22 20:17:47 -07008356 const auto it = mAbsoluteVolumeDrivingStreams.find(volumeDevice);
8357 if (it != mAbsoluteVolumeDrivingStreams.end()) {
8358 audio_attributes_t attributesToDriveAbs = it->second;
Vlad Popa87e0e582024-05-20 18:49:20 -07008359 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8360 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8361 ALOGD("%s: no group matching with %s", __FUNCTION__,
8362 toString(attributesToDriveAbs).c_str());
8363 return volumeDb;
8364 }
8365
8366 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8367 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8368 if (vsToDriveAbs == volumeSource) {
8369 // attenuation is applied by the abs volume controller
Vlad Popa444e95e2024-11-07 18:26:20 -08008370 // do not mute LE broadcast to allow the secondary device to continue playing
8371 return (index != 0 || volumeDevice == AUDIO_DEVICE_OUT_BLE_BROADCAST) ? volumeDbMax
8372 : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008373 } else {
8374 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8375 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8376 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8377 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8378 curvesAbs.getVolumeIndexMax());
8379 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8380 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8381 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8382 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8383 return newVolumeDb;
8384 }
8385 }
8386 return volumeDb;
8387 } else {
8388 return volumeDb;
8389 }
8390}
8391
François Gaffieaaac0fd2018-11-22 17:56:39 +01008392float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8393 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008394 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008395 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008396 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008397 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008398{
Vlad Popa9d482762024-06-21 16:40:23 -07008399 float volumeDb;
8400 if (adjustAttenuation) {
8401 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8402 } else {
8403 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8404 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008405 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8406 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8407
8408 if (!computeInternalInteraction) {
8409 return volumeDb;
8410 }
8411
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008412 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8413 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8414 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8415 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008416 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8417 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8418 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8419 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8420 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008421 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008422 mOutputs.isActive(ringVolumeSrc, 0)) {
8423 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008424 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008425 adjustAttenuation,
8426 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008427 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008428 }
8429
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008430 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008431 if ((volumeSource != callVolumeSrc && (isInCall() ||
8432 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008433 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008434 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8435 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008436 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8437 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8438 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008439 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008440 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008441 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008442 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008443 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008444 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008445 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008446 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8447 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8448 // programmatically muted.
8449 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8450 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8451 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008452 bool exemptFromCapping =
8453 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8454 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008455 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8456 volumeSource, volumeDb);
8457 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008458 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8459 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8460 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008461 }
8462 }
Eric Laurente552edb2014-03-10 17:42:56 -07008463 // if a headset is connected, apply the following rules to ring tones and notifications
8464 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008465 // - always attenuate notifications volume by 6dB
8466 // - attenuate ring tones volume by 6dB unless music is not playing and
8467 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008468 // - if music is playing, always limit the volume to current music volume,
8469 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008470 if (!Intersection(deviceTypes,
8471 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8472 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008473 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8474 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008475 ((volumeSource == alarmVolumeSrc ||
8476 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008477 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8478 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8479 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008480 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8481 curves.canBeMuted()) {
8482
Eric Laurente552edb2014-03-10 17:42:56 -07008483 // when the phone is ringing we must consider that music could have been paused just before
8484 // by the music application and behave as if music was active if the last music track was
8485 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008486 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8487 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008488 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008489 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008490 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8491 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008492 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008493 float musicVolDb = computeVolume(musicCurves,
8494 musicVolumeSrc,
8495 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008496 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008497 adjustAttenuation,
8498 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008499 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8500 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8501 if (volumeDb > minVolDb) {
8502 volumeDb = minVolDb;
8503 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008504 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008505 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8506 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008507 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8508 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8509 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8510 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008511 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008512 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008513 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8514 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008515 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8516 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008517 }
8518 }
jiabin9a3361e2019-10-01 09:38:30 -07008519 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008520 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008521 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008522 }
8523 }
8524
François Gaffie43c73442018-11-08 08:21:55 +01008525 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008526}
8527
Eric Laurent3839bc02018-07-10 18:33:34 -07008528int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008529 VolumeSource fromVolumeSource,
8530 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008531{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008532 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008533 return srcIndex;
8534 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008535 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8536 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008537 float minSrc = (float)srcCurves.getVolumeIndexMin();
8538 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8539 float minDst = (float)dstCurves.getVolumeIndexMin();
8540 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008541
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008542 // preserve mute request or correct range
8543 if (srcIndex < minSrc) {
8544 if (srcIndex == 0) {
8545 return 0;
8546 }
8547 srcIndex = minSrc;
8548 } else if (srcIndex > maxSrc) {
8549 srcIndex = maxSrc;
8550 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008551 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8552}
8553
François Gaffieaaac0fd2018-11-22 17:56:39 +01008554status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8555 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008556 int index,
8557 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008558 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008559 int delayMs,
8560 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008561{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008562 // APM is single threaded, and single instance.
8563 static std::set<IVolumeCurves*> invalidCurvesReported;
8564
François Gaffieaaac0fd2018-11-22 17:56:39 +01008565 // do not change actual attributes volume if the attributes is muted
Vlad Popa1e865e62024-08-15 19:11:42 -07008566 if (!com_android_media_audio_ring_my_car() && outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008567 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8568 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008569 return NO_ERROR;
8570 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008571
Eric Laurentae6e88c2024-01-10 14:42:57 +01008572 bool isVoiceVolSrc;
8573 bool isBtScoVolSrc;
8574 if (!isVolumeConsistentForCalls(
8575 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008576 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008577 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008578 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008579 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008580
jiabin9a3361e2019-10-01 09:38:30 -07008581 if (deviceTypes.empty()) {
8582 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008583 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008584 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008585 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008586 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008587
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008588 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008589 if (!invalidCurvesReported.count(&curves)) {
8590 invalidCurvesReported.insert(&curves);
8591 String8 dump;
8592 curves.dump(&dump);
8593 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8594 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008595 return BAD_VALUE;
8596 }
8597
jiabin9a3361e2019-10-01 09:38:30 -07008598 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
Eric Laurentc32e6692024-10-04 14:32:28 +00008599 const VolumeSource dtmfVolSrc = toVolumeSource(AUDIO_STREAM_DTMF, false);
jiabin9a3361e2019-10-01 09:38:30 -07008600 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008601 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurentc32e6692024-10-04 14:32:28 +00008602 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc
8603 || (isInCall() && (dtmfVolSrc == volumeSource))) &&
chenxin2095559032024-06-15 13:59:29 +08008604 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8605 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008606 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008607 }
Vlad Popa1e865e62024-08-15 19:11:42 -07008608
8609 bool muted;
8610 if (!com_android_media_audio_ring_my_car()) {
8611 muted = (index == 0) && (volumeDb != 0.0f);
8612 } else {
8613 muted = curves.isMuted();
8614 }
Eric Laurent31a428a2023-08-11 12:16:28 +02008615 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8616 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008617
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008618 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Vlad Popad80ed572024-11-06 18:28:17 -08008619 bool voiceVolumeManagedByHost = !isBtScoVolSrc &&
chenxin2095559032024-06-15 13:59:29 +08008620 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8621 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008622 }
Eric Laurente552edb2014-03-10 17:42:56 -07008623 return NO_ERROR;
8624}
8625
Eric Laurentae6e88c2024-01-10 14:42:57 +01008626void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008627 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008628 float voiceVolume;
Vlad Popa1e865e62024-08-15 19:11:42 -07008629
8630 if (com_android_media_audio_ring_my_car() && curves.isMuted()) {
8631 index = 0;
8632 }
8633
chenxin2095559032024-06-15 13:59:29 +08008634 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008635 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008636 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008637 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8638 } else {
8639 voiceVolume = index == 0 ? 0.0 : 1.0;
8640 }
8641 if (voiceVolume != mLastVoiceVolume) {
8642 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8643 mLastVoiceVolume = voiceVolume;
8644 }
8645}
8646
8647bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8648 const DeviceTypeSet& deviceTypes,
8649 bool& isVoiceVolSrc,
8650 bool& isBtScoVolSrc,
8651 const char* caller) {
8652 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008653 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8654
Eric Laurentae6e88c2024-01-10 14:42:57 +01008655 const bool isScoRequested = isScoRequestedForComm();
8656 const bool isHAUsed = isHearingAidUsedForComm();
8657
Vlad Popa695b76b2024-06-14 16:49:25 -07008658 if (com_android_media_audio_replace_stream_bt_sco()) {
Vlad Popa695b76b2024-06-14 16:49:25 -07008659 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8660 (isScoRequested || isHAUsed);
8661 return true;
8662 }
8663
8664 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008665 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8666
8667 if ((callVolSrc != btScoVolSrc) &&
8668 ((isVoiceVolSrc && isScoRequested) ||
8669 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8670 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8671 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8672 volumeSource, isScoRequested ? " " : " not ");
8673 return false;
8674 }
8675 return true;
8676}
8677
Eric Laurentc75307b2015-03-17 15:29:32 -07008678void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008679 const DeviceTypeSet& deviceTypes,
8680 int delayMs,
8681 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008682{
jiabincd510522020-01-22 09:40:55 -08008683 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008684 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8685 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
Vlad Popa1e865e62024-08-15 19:11:42 -07008686 checkAndSetVolume(curves, toVolumeSource(volumeGroup), curves.getVolumeIndex(deviceTypes),
jiabin9a3361e2019-10-01 09:38:30 -07008687 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008688 }
8689}
8690
François Gaffiec005e562018-11-06 15:04:49 +01008691void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8692 bool on,
8693 const sp<AudioOutputDescriptor>& outputDesc,
8694 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008695 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008696{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008697 std::vector<VolumeSource> sourcesToMute;
8698 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8699 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8700 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008701 VolumeSource source = toVolumeSource(attributes, false);
8702 if ((source != VOLUME_SOURCE_NONE) &&
8703 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8704 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008705 sourcesToMute.push_back(source);
8706 }
Eric Laurente552edb2014-03-10 17:42:56 -07008707 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008708 for (auto source : sourcesToMute) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008709 setVolumeSourceMutedInternally(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008710 }
8711
Eric Laurente552edb2014-03-10 17:42:56 -07008712}
8713
Vlad Popa1e865e62024-08-15 19:11:42 -07008714void AudioPolicyManager::setVolumeSourceMutedInternally(VolumeSource volumeSource,
8715 bool on,
8716 const sp<AudioOutputDescriptor>& outputDesc,
8717 int delayMs,
8718 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008719{
jiabin9a3361e2019-10-01 09:38:30 -07008720 if (deviceTypes.empty()) {
8721 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008722 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008723 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008724 if (on) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008725 if (!outputDesc->isMutedInternally(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008726 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008727 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008728 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8729 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008730 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008731 }
8732 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008733 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8734 // ignored
8735 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008736 } else {
Vlad Popa1e865e62024-08-15 19:11:42 -07008737 if (!outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008738 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008739 return;
8740 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008741 if (outputDesc->decMuteCount(volumeSource) == 0) {
8742 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008743 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008744 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008745 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008746 delayMs);
8747 }
8748 }
8749}
8750
François Gaffie53615e22015-03-19 09:24:12 +01008751bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8752{
Vlad Popa7f1823b2024-11-05 15:37:52 -08008753 if ((paa->flags & AUDIO_FLAG_SCO) != 0) {
8754 ALOGW("%s: deprecated use of AUDIO_FLAG_SCO in attributes flags %d", __func__, paa->flags);
8755 }
8756
François Gaffiec005e562018-11-06 15:04:49 +01008757 // has flags that map to a stream type?
Vlad Popa7f1823b2024-11-05 15:37:52 -08008758 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_BEACON)) != 0) {
Eric Laurente83b55d2014-11-14 10:06:21 -08008759 return true;
8760 }
8761
8762 // has known usage?
8763 switch (paa->usage) {
8764 case AUDIO_USAGE_UNKNOWN:
8765 case AUDIO_USAGE_MEDIA:
8766 case AUDIO_USAGE_VOICE_COMMUNICATION:
8767 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8768 case AUDIO_USAGE_ALARM:
8769 case AUDIO_USAGE_NOTIFICATION:
8770 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8771 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8772 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8773 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8774 case AUDIO_USAGE_NOTIFICATION_EVENT:
8775 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8776 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8777 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8778 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008779 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008780 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008781 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008782 case AUDIO_USAGE_EMERGENCY:
8783 case AUDIO_USAGE_SAFETY:
8784 case AUDIO_USAGE_VEHICLE_STATUS:
8785 case AUDIO_USAGE_ANNOUNCEMENT:
Jean-Michel Trivid9add572024-11-05 14:48:40 -08008786 case AUDIO_USAGE_SPEAKER_CLEANUP:
Eric Laurente83b55d2014-11-14 10:06:21 -08008787 break;
8788 default:
8789 return false;
8790 }
8791 return true;
8792}
8793
François Gaffie2110e042015-03-24 08:41:51 +01008794audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8795{
8796 return mEngine->getForceUse(usage);
8797}
8798
Eric Laurent96d1dda2022-03-14 17:14:19 +01008799bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008800 return isStateInCall(mEngine->getPhoneState());
8801}
8802
Eric Laurent96d1dda2022-03-14 17:14:19 +01008803bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008804 return is_state_in_call(state);
8805}
8806
Eric Laurentf9cccec2022-11-16 19:12:00 +01008807bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008808 audio_mode_t mode = mEngine->getPhoneState();
8809 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008810 || (mode == AUDIO_MODE_CALL_SCREEN)
8811 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008812}
8813
Eric Laurentf9cccec2022-11-16 19:12:00 +01008814bool AudioPolicyManager::isInCallOrScreening() const {
8815 audio_mode_t mode = mEngine->getPhoneState();
8816 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8817}
8818
Eric Laurentd60560a2015-04-10 11:31:20 -07008819void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8820{
8821 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008822 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008823 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008824 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008825 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008826 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008827 }
8828 }
8829
8830 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8831 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8832 bool release = false;
8833 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8834 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8835 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8836 source->ext.device.type == deviceDesc->type()) {
8837 release = true;
8838 }
8839 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008840 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008841 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8842 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8843 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008844 sink->ext.device.type == deviceDesc->type() &&
8845 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8846 || strncmp(sink->ext.device.address, address,
8847 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008848 release = true;
8849 }
8850 }
8851 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008852 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8853 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008854 }
8855 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008856
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008857 mInputs.clearSessionRoutesForDevice(deviceDesc);
8858
Francois Gaffie716e1432019-01-14 16:58:59 +01008859 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008860}
8861
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008862void AudioPolicyManager::modifySurroundFormats(
8863 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008864 std::unordered_set<audio_format_t> enforcedSurround(
8865 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008866 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008867 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008868 allSurround.insert(pair.first);
8869 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8870 }
Phil Burk09bc4612016-02-24 15:58:15 -08008871
8872 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8873 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008874 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008875 // This is the resulting set of formats depending on the surround mode:
8876 // 'all surround' = allSurround
8877 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8878 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8879 // 'manual surround' = mManualSurroundFormats
8880 // AUTO: formats v 'enforced surround'
8881 // ALWAYS: formats v 'all surround' v 'enforced surround'
8882 // NEVER: formats ^ 'non-surround'
8883 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008884
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008885 std::unordered_set<audio_format_t> formatSet;
8886 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8887 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008888 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008889 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008890 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008891 formatSet.insert(*formatIter);
8892 }
8893 }
8894 } else {
8895 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8896 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008897 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008898
jiabin81772902018-04-02 17:52:27 -07008899 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008900 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008901 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8902 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8903 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008904 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008905 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8906 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8907 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008908 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008909 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008910 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008911 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008912 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008913 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008914}
8915
jiabin06e4bab2019-07-29 10:13:34 -07008916void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8917 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008918 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8919 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8920
8921 // If NEVER, then remove support for channelMasks > stereo.
8922 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008923 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8924 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008925 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008926 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008927 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008928 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008929 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008930 }
8931 }
jiabin81772902018-04-02 17:52:27 -07008932 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8933 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8934 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008935 bool supports5dot1 = false;
8936 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008937 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008938 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8939 supports5dot1 = true;
8940 break;
8941 }
8942 }
8943 // If not then add 5.1 support.
8944 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008945 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008946 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008947 }
Phil Burk09bc4612016-02-24 15:58:15 -08008948 }
8949}
8950
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008951void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008952 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008953 const sp<IOProfile>& profile) {
8954 if (!profile->hasDynamicAudioProfile()) {
8955 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008956 }
François Gaffie112b0af2015-11-19 16:13:25 +01008957
jiabin12537fc2023-10-12 17:56:08 +00008958 audio_port_v7 devicePort;
8959 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008960
jiabin12537fc2023-10-12 17:56:08 +00008961 audio_port_v7 mixPort;
8962 profile->toAudioPort(&mixPort);
8963 mixPort.ext.mix.handle = ioHandle;
8964
8965 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8966 if (status != NO_ERROR) {
8967 ALOGE("%s failed to query the attributes of the mix port", __func__);
8968 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008969 }
jiabin12537fc2023-10-12 17:56:08 +00008970
8971 std::set<audio_format_t> supportedFormats;
8972 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8973 supportedFormats.insert(mixPort.audio_profiles[i].format);
8974 }
8975 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8976 mReportedFormatsMap[devDesc] = formats;
8977
8978 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008979 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8980 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008981 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8982 modifySurroundFormats(devDesc, &formats);
8983 size_t modifiedNumProfiles = 0;
8984 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8985 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8986 formats.end()) {
8987 // Skip the format that is not present after modifying surround formats.
8988 continue;
8989 }
8990 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8991 sizeof(struct audio_profile));
8992 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8993 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8994 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8995 modifySurroundChannelMasks(&channels);
8996 std::copy(channels.begin(), channels.end(),
8997 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8998 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8999 }
9000 mixPort.num_audio_profiles = modifiedNumProfiles;
9001 }
9002 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01009003}
Eric Laurentd60560a2015-04-10 11:31:20 -07009004
Mikhail Naganovdc769682018-05-04 15:34:08 -07009005status_t AudioPolicyManager::installPatch(const char *caller,
9006 audio_patch_handle_t *patchHandle,
9007 AudioIODescriptorInterface *ioDescriptor,
9008 const struct audio_patch *patch,
9009 int delayMs)
9010{
9011 ssize_t index = mAudioPatches.indexOfKey(
9012 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
9013 *patchHandle : ioDescriptor->getPatchHandle());
9014 sp<AudioPatch> patchDesc;
9015 status_t status = installPatch(
9016 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
9017 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01009018 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07009019 }
9020 return status;
9021}
9022
9023status_t AudioPolicyManager::installPatch(const char *caller,
9024 ssize_t index,
9025 audio_patch_handle_t *patchHandle,
9026 const struct audio_patch *patch,
9027 int delayMs,
9028 uid_t uid,
9029 sp<AudioPatch> *patchDescPtr)
9030{
9031 sp<AudioPatch> patchDesc;
9032 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
9033 if (index >= 0) {
9034 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01009035 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009036 }
9037
9038 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
9039 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
9040 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
9041 if (status == NO_ERROR) {
9042 if (index < 0) {
9043 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01009044 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009045 } else {
9046 patchDesc->mPatch = *patch;
9047 }
François Gaffieafd4cea2019-11-18 15:50:22 +01009048 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009049 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01009050 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009051 }
9052 nextAudioPortGeneration();
9053 mpClientInterface->onAudioPatchListUpdate();
9054 }
9055 if (patchDescPtr) *patchDescPtr = patchDesc;
9056 return status;
9057}
9058
jiabinbce0c1d2020-10-05 11:20:18 -07009059bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
9060{
9061 const TrackClientVector activeClients = output->getActiveClients();
9062 if (activeClients.empty()) {
9063 return true;
9064 }
9065 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
9066 if (index < 0) {
9067 ALOGE("%s, no audio patch found while there are active clients on output %d",
9068 __func__, output->getId());
9069 return false;
9070 }
9071 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
9072 DeviceVector routedDevices;
9073 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
9074 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
9075 patchDesc->mPatch.sinks[i].id);
9076 if (device == nullptr) {
9077 ALOGE("%s, no audio device found with id(%d)",
9078 __func__, patchDesc->mPatch.sinks[i].id);
9079 return false;
9080 }
9081 routedDevices.add(device);
9082 }
9083 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08009084 if (client->isInvalid()) {
9085 // No need to take care about invalidated clients.
9086 continue;
9087 }
jiabinbce0c1d2020-10-05 11:20:18 -07009088 sp<DeviceDescriptor> preferredDevice =
9089 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
9090 if (mEngine->getOutputDevicesForAttributes(
9091 client->attributes(), preferredDevice, false) == routedDevices) {
9092 return false;
9093 }
9094 }
9095 return true;
9096}
9097
9098sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01009099 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00009100 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
9101 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07009102{
9103 for (const auto& device : devices) {
9104 // TODO: This should be checking if the profile supports the device combo.
9105 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00009106 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
9107 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07009108 return nullptr;
9109 }
9110 }
9111 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
9112 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07009113 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00009114 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009115 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009116 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00009117 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07009118 return nullptr;
9119 }
jiabin14b50cc2023-12-13 19:01:52 +00009120 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
9121 auto portConfig = desc->getConfig();
9122 for (const auto& device : devices) {
9123 device->setPreferredConfig(&portConfig);
9124 }
9125 }
jiabinbce0c1d2020-10-05 11:20:18 -07009126
9127 // Here is where the out_set_parameters() for card & device gets called
9128 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
9129 const audio_devices_t deviceType = device->type();
9130 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00009131 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07009132 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
9133 mpClientInterface->setParameters(output, String8(param));
9134 free(param);
9135 }
jiabin12537fc2023-10-12 17:56:08 +00009136 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07009137 if (!profile->hasValidAudioProfile()) {
9138 ALOGW("%s() missing param", __func__);
9139 desc->close();
9140 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00009141 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
9142 // Reopen the output with the best audio profile picked by APM when the profile supports
9143 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07009144 desc->close();
9145 output = AUDIO_IO_HANDLE_NONE;
9146 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9147 profile->pickAudioProfile(
9148 config.sample_rate, config.channel_mask, config.format);
9149 config.offload_info.sample_rate = config.sample_rate;
9150 config.offload_info.channel_mask = config.channel_mask;
9151 config.offload_info.format = config.format;
9152
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009153 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07009154 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009155 if (status != NO_ERROR) {
9156 return nullptr;
9157 }
9158 }
9159
9160 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07009161 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
9162 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
9163 hwModule->getHalVersionMajor() >= 3) {
9164 setOutputDevices(__func__, desc, devices, true, 0, NULL);
9165 }
baek.kim -61c20122022-07-27 10:05:32 +00009166 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9167 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9168
jiabinbce0c1d2020-10-05 11:20:18 -07009169 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9170 sp<AudioPolicyMix> policyMix;
9171 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9172 policyMix->setOutput(desc);
9173 desc->mPolicyMix = policyMix;
9174 } else {
9175 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009176 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009177 }
9178
baek.kim -61c20122022-07-27 10:05:32 +00009179 } else if (hasPrimaryOutput() && speaker != nullptr
9180 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009181 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9182 // no duplicated output for:
9183 // - direct outputs
9184 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009185 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009186 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9187
9188 //TODO: configure audio effect output stage here
9189
9190 // open a duplicating output thread for the new output and the primary output
9191 sp<SwAudioOutputDescriptor> dupOutputDesc =
9192 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9193 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9194 if (status == NO_ERROR) {
9195 // add duplicated output descriptor
9196 addOutput(duplicatedOutput, dupOutputDesc);
9197 } else {
9198 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9199 mPrimaryOutput->mIoHandle, output);
9200 desc->close();
9201 removeOutput(output);
9202 nextAudioPortGeneration();
9203 return nullptr;
9204 }
9205 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009206 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9207 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9208 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009209 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009210 }
jiabinbce0c1d2020-10-05 11:20:18 -07009211 return desc;
9212}
9213
jiabinf1c73972022-04-14 16:28:52 -07009214status_t AudioPolicyManager::getDevicesForAttributes(
9215 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
wenyu zhang8558a332024-09-09 15:12:48 +00009216 // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9217 // over any usage or content type also present in attr.
9218 if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9219 attr.source != AUDIO_SOURCE_INVALID) {
9220 return getInputDevicesForAttributes(attr, devices);
9221 }
9222
jiabinf1c73972022-04-14 16:28:52 -07009223 // Devices are determined in the following precedence:
9224 //
9225 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9226 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9227 //
9228 // If no such dynamic policy then
9229 // 2) Devices containing an active client using setPreferredDevice
9230 // with same strategy as the attributes.
9231 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9232 //
9233 // If no corresponding active client with setPreferredDevice then
9234 // 3) Devices associated with the strategy determined by the attributes
9235 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9236 //
9237 // See related getOutputForAttrInt().
9238
9239 // check dynamic policies but only for primary descriptors (secondary not used for audible
9240 // audio routing, only used for duplication for playback capture)
9241 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009242 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009243 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009244 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9245 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9246 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009247 if (status != OK) {
9248 return status;
9249 }
9250
9251 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9252 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9253 // as they are unaffected by device/stream volume
9254 // (per SwAudioOutputDescriptor::isFixedVolume()).
9255 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9256 ) {
9257 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9258 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9259 devices.add(deviceDesc);
9260 } else {
9261 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9262 // which selects setPreferredDevice if active. This means forVolume call
9263 // will take an active setPreferredDevice, if such exists.
9264
9265 devices = mEngine->getOutputDevicesForAttributes(
9266 attr, nullptr /* preferredDevice */, false /* fromCache */);
9267 }
9268
9269 if (forVolume) {
9270 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9271 // for single volume control in AudioService (such relationship should exist if
9272 // SPEAKER_SAFE is present).
9273 //
9274 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9275 DeviceVector speakerSafeDevices =
9276 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9277 if (!speakerSafeDevices.isEmpty()) {
9278 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9279 devices.remove(speakerSafeDevices);
9280 }
9281 }
9282
9283 return NO_ERROR;
9284}
9285
wenyu zhang8558a332024-09-09 15:12:48 +00009286status_t AudioPolicyManager::getInputDevicesForAttributes(
9287 const audio_attributes_t &attr, DeviceVector &devices) {
9288 devices = DeviceVector(
9289 mEngine->getInputDeviceForAttributes(attr, 0 /*uid unknown here*/,
9290 AUDIO_SESSION_NONE,
9291 nullptr /* mix */));
9292 return NO_ERROR;
9293}
9294
jiabinf1c73972022-04-14 16:28:52 -07009295status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9296 AudioProfileVector& audioProfiles,
9297 uint32_t flags,
9298 bool isInput) {
9299 for (const auto& hwModule : mHwModules) {
9300 // the MSD module checks for different conditions
9301 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9302 continue;
9303 }
9304 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9305 : hwModule->getOutputProfiles();
9306 for (const auto& profile : ioProfiles) {
9307 if (!profile->areAllDevicesSupported(devices) ||
jiabin91beb492024-10-16 21:53:36 +00009308 !profile->isCompatibleProfileForFlags(flags)) {
jiabinf1c73972022-04-14 16:28:52 -07009309 continue;
9310 }
9311 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9312 }
9313 }
9314
9315 if (!isInput) {
9316 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9317 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9318 if (msdModule != nullptr) {
9319 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9320 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9321 for (const auto &profile: msdModule->getOutputProfiles()) {
9322 if (!profile->asAudioPort()->isDirectOutput()) {
9323 continue;
9324 }
9325 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9326 }
9327 } else {
9328 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9329 }
9330 }
9331 }
9332
9333 return NO_ERROR;
9334}
9335
jiabin3ff8d7d2022-12-13 06:27:44 +00009336sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9337 const audio_config_t *config,
9338 audio_output_flags_t flags,
9339 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009340 closeOutput(outputDesc->mIoHandle);
9341 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9342 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9343 if (preferredOutput == nullptr) {
9344 ALOGE("%s failed to reopen output device=%d, caller=%s",
9345 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009346 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009347 return preferredOutput;
9348}
9349
9350void AudioPolicyManager::reopenOutputsWithDevices(
9351 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9352 for (const auto& [output, devices] : outputsToReopen) {
9353 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9354 closeOutput(output);
9355 openOutputWithProfileAndDevice(desc->mProfile, devices);
9356 }
jiabina84c3d32022-12-02 18:59:55 +00009357}
9358
jiabinc44b3462022-12-08 12:52:31 -08009359PortHandleVector AudioPolicyManager::getClientsForStream(
9360 audio_stream_type_t streamType) const {
9361 PortHandleVector clients;
9362 for (size_t i = 0; i < mOutputs.size(); ++i) {
9363 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9364 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9365 }
9366 return clients;
9367}
9368
9369void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9370 PortHandleVector clients;
9371 for (auto stream : streams) {
9372 PortHandleVector clientsForStream = getClientsForStream(stream);
9373 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9374 }
9375 mpClientInterface->invalidateTracks(clients);
9376}
9377
jiabin220eea12024-05-17 17:55:20 +00009378void AudioPolicyManager::updateClientsInternalMute(
9379 const sp<android::SwAudioOutputDescriptor> &desc) {
9380 if (!desc->isBitPerfect() ||
9381 !com::android::media::audioserver::
9382 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9383 // This is only used for bit perfect output now.
9384 return;
9385 }
9386 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9387 bool bitPerfectClientInternalMute = false;
9388 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9389 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9390 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9391 bitPerfectClient = client;
9392 continue;
9393 }
9394 bool muted = false;
9395 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9396 // System sound is muted.
9397 muted = true;
9398 } else {
9399 bitPerfectClientInternalMute = true;
9400 }
9401 if (client->setInternalMute(muted)) {
9402 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9403 if (!result.ok()) {
9404 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9405 continue;
9406 }
9407 media::TrackInternalMuteInfo info;
9408 info.portId = result.value();
9409 info.muted = client->getInternalMute();
9410 clientsInternalMute.push_back(std::move(info));
9411 }
9412 }
9413 if (bitPerfectClient != nullptr &&
9414 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9415 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9416 if (result.ok()) {
9417 media::TrackInternalMuteInfo info;
9418 info.portId = result.value();
9419 info.muted = bitPerfectClient->getInternalMute();
9420 clientsInternalMute.push_back(std::move(info));
9421 } else {
9422 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9423 __func__, bitPerfectClient->portId());
9424 }
9425 }
9426 if (!clientsInternalMute.empty()) {
9427 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9428 status != NO_ERROR) {
9429 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9430 }
9431 }
9432}
9433
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00009434status_t AudioPolicyManager::getMmapPolicyInfos(AudioMMapPolicyType policyType,
9435 std::vector<AudioMMapPolicyInfo> *policyInfos) {
9436 if (policyType != AudioMMapPolicyType::DEFAULT &&
9437 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9438 return BAD_VALUE;
9439 }
9440 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9441 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9442 return status;
9443 }
9444 }
9445 *policyInfos = mMmapPolicyInfos[policyType];
9446 return NO_ERROR;
9447}
9448
9449status_t AudioPolicyManager::getMmapPolicyForDevice(
9450 AudioMMapPolicyType policyType, AudioMMapPolicyInfo *policyInfo) {
9451 if (policyType != AudioMMapPolicyType::DEFAULT &&
9452 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9453 return BAD_VALUE;
9454 }
9455 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9456 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9457 return status;
9458 }
9459 }
9460 auto it = mMmapPolicyByDeviceType[policyType].find(policyInfo->device.type);
9461 policyInfo->mmapPolicy = it == mMmapPolicyByDeviceType[policyType].end()
9462 ? AudioMMapPolicy::NEVER : it->second;
9463 return NO_ERROR;
9464}
9465
9466status_t AudioPolicyManager::updateMmapPolicyInfos(AudioMMapPolicyType policyType) {
9467 std::vector<AudioMMapPolicyInfo> policyInfos;
9468 if (status_t status = mpClientInterface->getMmapPolicyInfos(policyType, &policyInfos);
9469 status != NO_ERROR) {
9470 ALOGE("%s, failed, error = %d", __func__, status);
9471 return status;
9472 }
9473 std::map<AudioDeviceDescription, AudioMMapPolicy> mmapPolicyByDeviceType;
9474 if (policyInfos.size() == 1 && policyInfos[0].device == AudioDevice()) {
9475 // When there is only one AudioMMapPolicyInfo instance and the device is a default value,
9476 // it indicates the mmap policy is reported via system property. In that case, use the
9477 // routing information to fill details for how mmap is supported for a particular device.
9478 for (const auto &hwModule: mHwModules) {
9479 for (const auto &profile: hwModule->getInputProfiles()) {
9480 if ((profile->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ)
9481 != AUDIO_INPUT_FLAG_MMAP_NOIRQ) {
9482 continue;
9483 }
9484 for (const auto &device: profile->getSupportedDevices()) {
9485 auto deviceDesc =
9486 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9487 if (deviceDesc.ok()) {
9488 mmapPolicyByDeviceType.emplace(
9489 deviceDesc.value(), policyInfos[0].mmapPolicy);
9490 }
9491 }
9492 }
9493 for (const auto &profile: hwModule->getOutputProfiles()) {
9494 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)
9495 != AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
9496 continue;
9497 }
9498 for (const auto &device: profile->getSupportedDevices()) {
9499 auto deviceDesc =
9500 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9501 if (deviceDesc.ok()) {
9502 mmapPolicyByDeviceType.emplace(
9503 deviceDesc.value(), policyInfos[0].mmapPolicy);
9504 }
9505 }
9506 }
9507 }
9508 } else {
9509 for (const auto &info: policyInfos) {
9510 mmapPolicyByDeviceType[info.device.type] = info.mmapPolicy;
9511 }
9512 }
9513 mMmapPolicyByDeviceType.emplace(policyType, mmapPolicyByDeviceType);
9514 mMmapPolicyInfos.emplace(policyType, policyInfos);
9515 return NO_ERROR;
9516}
9517
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009518} // namespace android