blob: 36809abc2ec9f39bab2a10a8acadb03ea9f6429a [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>
jiabin7ed22ff2024-10-04 20:51:21 +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;
jiabin7ed22ff2024-10-04 20:51:21 +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,
1265 audio_port_handle_t *selectedDeviceId,
1266 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;
Francois Gaffie716e1432019-01-14 16:58:59 +01001273 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001274 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001275 const sp<DeviceDescriptor> requestedDevice =
1276 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1277
Eric Laurent8a1095a2019-11-08 14:44:16 -08001278 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001279 *isSpatialized = false;
1280
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001281 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1282 if (status != NO_ERROR) {
1283 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001284 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001285 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001286 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001287 }
François Gaffiec005e562018-11-06 15:04:49 +01001288 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001289
François Gaffiec005e562018-11-06 15:04:49 +01001290 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1291 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001292
Oscar Azucena873d10f2023-01-12 18:34:42 -08001293 bool usePrimaryOutputFromPolicyMixes = false;
1294
Kevin Rocard153f92d2018-12-18 18:33:28 -08001295 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1296 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1297 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001298 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001299 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1300 .channel_mask = config->channel_mask,
1301 .format = config->format,
1302 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001303 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001304 mAvailableOutputDevices, requestedDevice, primaryMix,
1305 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001306 if (status != OK) {
1307 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001308 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001309
Kevin Rocard153f92d2018-12-18 18:33:28 -08001310 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001311 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungdb27c442024-08-14 11:37:57 -07001312 && (!audio_is_linear_pcm(config->format) ||
1313 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001314 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001315 return BAD_VALUE;
1316 }
1317 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001318 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001319 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1320 primaryMix->mDeviceAddress,
1321 AUDIO_FORMAT_DEFAULT);
1322 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001323 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001324 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1325 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001326 // if a direct output can be opened to deliver the track's multi-channel content to the
1327 // output rather than being downmixed by the primary output, then use this direct
1328 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1329 // mix.
1330 bool tryDirectForChannelMask = policyDesc != nullptr
1331 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1332 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001333 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001334 audio_io_handle_t newOutput;
1335 status = openDirectOutput(
1336 *stream, session, config,
1337 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangf6e304f2024-07-09 23:06:58 -07001338 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001339 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001340 policyDesc = mOutputs.valueFor(newOutput);
1341 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001342 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001343 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001344 policyDesc = nullptr;
1345 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001346 }
1347 if (policyDesc != nullptr) {
1348 policyDesc->mPolicyMix = primaryMix;
1349 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001350 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1351 : AUDIO_PORT_HANDLE_NONE;
1352 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1353 // Remove direct flag as it is not on a direct output.
1354 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1355 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001356
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001357 ALOGV("getOutputForAttr() returns output %d", *output);
1358 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1359 *outputType = API_OUT_MIX_PLAYBACK;
1360 } else {
1361 *outputType = API_OUTPUT_LEGACY;
1362 }
1363 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001364 } else {
1365 if (policyMixDevice != nullptr) {
1366 ALOGE("%s, try to use primary mix but no output found", __func__);
1367 return INVALID_OPERATION;
1368 }
1369 // Fallback to default engine selection as the selected primary mix device is not
1370 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001371 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001372 }
François Gaffiec005e562018-11-06 15:04:49 +01001373 // Virtual sources must always be dynamicaly or explicitly routed
1374 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1375 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1376 return BAD_VALUE;
1377 }
1378 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1379 // in order to let the choice of the order to future vendor engine
1380 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001381
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001382 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001383 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001384 }
1385
Nadav Barb2f18162018-07-18 13:01:53 +03001386 // Set incall music only if device was explicitly set, and fallback to the device which is
1387 // chosen by the engine if not.
1388 // FIXME: provide a more generic approach which is not device specific and move this back
1389 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001390 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001391 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001392 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001393 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001394 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001395 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001396 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001397 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001398 }
1399 }
1400
François Gaffiec005e562018-11-06 15:04:49 +01001401 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1402 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1403 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001404
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001405 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001406 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001407 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001408 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001409 ALOGV("%s() Using MSD devices %s instead of devices %s",
1410 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001411 } else {
1412 *output = AUDIO_IO_HANDLE_NONE;
1413 }
1414 }
1415 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001416 sp<PreferredMixerAttributesInfo> info = nullptr;
1417 if (outputDevices.size() == 1) {
1418 info = getPreferredMixerAttributesInfo(
1419 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001420 mEngine->getProductStrategyForAttributes(*resultAttr),
1421 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001422 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1423 // and it is currently active.
1424 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001425 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001426 info = nullptr;
1427 }
jiabin8a096672024-09-18 18:20:24 +00001428
1429 if (info != nullptr && info->isBitPerfect() &&
1430 (*flags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
1431 AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1432 // Reject direct request if a preferred mixer config in use is bit-perfect.
1433 ALOGD("%s reject direct request as bit-perfect mixer attributes is active",
1434 __func__);
1435 return BAD_VALUE;
1436 }
1437
jiabin220eea12024-05-17 17:55:20 +00001438 if (com::android::media::audioserver::
1439 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1440 if (info != nullptr && info->getUid() == uid &&
1441 info->configMatches(*config) &&
1442 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1443 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1444 [this, &outputDevices](audio_usage_t usage) {
1445 return mOutputs.isUsageActiveOnDevice(
1446 usage, outputDevices[0]); }))) {
1447 // Bit-perfect request is not allowed when the phone mode is not normal or
1448 // there is any higher priority user case active.
1449 return INVALID_OPERATION;
1450 }
1451 }
jiabina84c3d32022-12-02 18:59:55 +00001452 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001453 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001454 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001455 // The client will be active if the client is currently preferred mixer owner and the
1456 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001457 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001458 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001459 && info->getUid() == uid
1460 && *output != AUDIO_IO_HANDLE_NONE
1461 // When bit-perfect output is selected for the preferred mixer attributes owner,
1462 // only need to consider the config matches.
1463 && mOutputs.valueFor(*output)->isConfigurationMatched(
1464 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001465
1466 if (*isBitPerfect) {
1467 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1468 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001469 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001470 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001471 AudioProfileVector profiles;
1472 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1473 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001474 const auto channels = profiles[0]->getChannels();
1475 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1476 config->channel_mask = *channels.begin();
1477 }
1478 const auto sampleRates = profiles[0]->getSampleRates();
1479 if (!sampleRates.empty() &&
1480 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1481 config->sample_rate = *sampleRates.begin();
1482 }
jiabinf1c73972022-04-14 16:28:52 -07001483 config->format = profiles[0]->getFormat();
1484 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001485 return INVALID_OPERATION;
1486 }
Paul McLeanaa981192015-03-21 09:55:15 -07001487
François Gaffiec005e562018-11-06 15:04:49 +01001488 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001489 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001490 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001491 *selectedDeviceId = outputDevice->getId();
1492 break;
1493 }
1494 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001495
Eric Laurent8a1095a2019-11-08 14:44:16 -08001496 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1497 *outputType = API_OUTPUT_TELEPHONY_TX;
1498 } else {
1499 *outputType = API_OUTPUT_LEGACY;
1500 }
1501
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001502 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1503
1504 return NO_ERROR;
1505}
1506
1507status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1508 audio_io_handle_t *output,
1509 audio_session_t session,
1510 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001511 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001512 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001513 audio_output_flags_t *flags,
1514 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001515 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001516 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001517 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001518 bool *isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +00001519 bool *isBitPerfect,
1520 float *volume)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001521{
1522 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1523 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1524 return INVALID_OPERATION;
1525 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001526 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001527 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001528 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001529 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001530 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001531 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001532 const sp<DeviceDescriptor> requestedDevice =
1533 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1534
1535 // Prevent from storing invalid requested device id in clients
1536 const audio_port_handle_t sanitizedRequestedPortId =
1537 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1538 *selectedDeviceId = sanitizedRequestedPortId;
1539
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001540 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001541 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001542 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1543 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001544 if (status != NO_ERROR) {
1545 return status;
1546 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001547 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001548 if (secondaryOutputs != nullptr) {
1549 for (auto &secondaryMix : secondaryMixes) {
1550 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1551 if (outputDesc != nullptr &&
1552 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1553 secondaryOutputs->push_back(outputDesc->mIoHandle);
1554 weakSecondaryOutputDescs.push_back(outputDesc);
1555 }
1556 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001557 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001558
Eric Laurent8fc147b2018-07-22 19:13:55 -07001559 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001560 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001561 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001562 };
jiabin4ef93452019-09-10 14:29:54 -07001563 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001564
Eric Laurentc209fe42020-06-05 18:11:23 -07001565 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001566 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001567 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001568 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001569 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001570 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001571 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001572 std::move(weakSecondaryOutputDescs),
1573 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001574 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001575
Andy Hung6b137d12024-08-27 22:35:17 +00001576 *volume = Volume::DbToAmpl(outputDesc->getCurVolume(toVolumeSource(resultAttr)));
1577
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001578 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1579 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001580
Eric Laurente83b55d2014-11-14 10:06:21 -08001581 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001582}
1583
Eric Laurentc529cf62020-04-17 18:19:10 -07001584status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1585 audio_session_t session,
1586 const audio_config_t *config,
1587 audio_output_flags_t flags,
1588 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001589 audio_io_handle_t *output,
1590 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001591
1592 *output = AUDIO_IO_HANDLE_NONE;
1593
1594 // skip direct output selection if the request can obviously be attached to a mixed output
1595 // and not explicitly requested
1596 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1597 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1598 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1599 return NAME_NOT_FOUND;
1600 }
1601
Mikhail Naganov806170e2024-09-05 17:26:50 -07001602 // Reject flag combinations that do not make sense. Note that the requested flags might not
1603 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1604 // combine the requested flags with its own flags, yielding an unsupported combination.
1605 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1606 return NAME_NOT_FOUND;
1607 }
1608
Eric Laurentc529cf62020-04-17 18:19:10 -07001609 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1610 // This prevents creating an offloaded track and tearing it down immediately after start
1611 // when audioflinger detects there is an active non offloadable effect.
1612 // FIXME: We should check the audio session here but we do not have it in this context.
1613 // This may prevent offloading in rare situations where effects are left active by apps
1614 // in the background.
1615 sp<IOProfile> profile;
1616 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1617 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1618 profile = getProfileForOutput(
1619 devices, config->sample_rate, config->format, config->channel_mask,
1620 flags, true /* directOnly */);
1621 }
1622
1623 if (profile == nullptr) {
1624 return NAME_NOT_FOUND;
1625 }
1626
1627 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1628 for (size_t i = 0; i < mOutputs.size(); i++) {
1629 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1630 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1631 // reuse direct output if currently open by the same client
1632 // and configured with same parameters
1633 if ((config->sample_rate == desc->getSamplingRate()) &&
1634 (config->format == desc->getFormat()) &&
1635 (config->channel_mask == desc->getChannelMask()) &&
1636 (session == desc->mDirectClientSession)) {
1637 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301638 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001639 mOutputs.keyAt(i), session);
1640 *output = mOutputs.keyAt(i);
1641 return NO_ERROR;
1642 }
1643 }
1644 }
1645
1646 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001647 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301648 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1649 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001650 return NAME_NOT_FOUND;
1651 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1652 // MMAP gracefully handles lack of an exclusive track resource by mixing
1653 // above the audio framework. For AAudio to know that the limit is reached,
1654 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301655 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1656 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001657 return NAME_NOT_FOUND;
1658 } else {
1659 // Close outputs on this profile, if available, to free resources for this request
1660 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1661 const auto desc = mOutputs.valueAt(i);
1662 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301663 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1664 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001665 closeOutput(desc->mIoHandle);
1666 }
1667 }
1668 }
1669 }
1670
1671 // Unable to close streams to find free resources for this request
1672 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301673 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1674 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001675 return NAME_NOT_FOUND;
1676 }
1677
Atneya Nairb16666a2023-12-11 20:18:33 -08001678 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001679
Michael Chan6fb34492020-12-08 15:44:49 +11001680 // An MSD patch may be using the only output stream that can service this request. Release
1681 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001682 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001683
Eric Laurentf1f22e72021-07-13 14:04:14 +02001684 status_t status =
Dean Wheatleydfb67b82024-01-23 09:36:29 +11001685 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001686 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001687
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001688 // only accept an output with the requested parameters, unless the format can be IEC61937
1689 // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1690 const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1691 && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1692 && audio_has_proportional_frames(outputDesc->getFormat());
Eric Laurentc529cf62020-04-17 18:19:10 -07001693 if (status != NO_ERROR ||
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001694 (!ignoreRequestedParametersCheck &&
1695 ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1696 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1697 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001698 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1699 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1700 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1701 config->channel_mask, outputDesc->getChannelMask());
1702 if (*output != AUDIO_IO_HANDLE_NONE) {
1703 outputDesc->close();
1704 }
1705 // fall back to mixer output if possible when the direct output could not be open
1706 if (audio_is_linear_pcm(config->format) &&
1707 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1708 return NAME_NOT_FOUND;
1709 }
1710 *output = AUDIO_IO_HANDLE_NONE;
1711 return BAD_VALUE;
1712 }
1713 outputDesc->mDirectOpenCount = 1;
1714 outputDesc->mDirectClientSession = session;
1715
1716 addOutput(*output, outputDesc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07001717 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
1718 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
1719 hwModule->getHalVersionMajor() >= 3) {
1720 setOutputDevices(__func__, outputDesc, devices, true, 0, NULL);
1721 }
Eric Laurentc529cf62020-04-17 18:19:10 -07001722 mPreviousOutputs = mOutputs;
1723 ALOGV("%s returns new direct output %d", __func__, *output);
1724 mpClientInterface->onAudioPortListUpdate();
1725 return NO_ERROR;
1726}
1727
François Gaffie11d30102018-11-02 16:09:09 +01001728audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1729 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001730 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001731 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001732 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001733 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001734 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001735 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001736 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001737{
Andy Hungc88b0642018-04-27 15:42:35 -07001738 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001739
jiabine375d412019-02-26 12:54:53 -08001740 // Discard haptic channel mask when forcing muting haptic channels.
1741 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001742 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1743 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001744
Eric Laurente552edb2014-03-10 17:42:56 -07001745 // open a direct output if required by specified parameters
1746 //force direct flag if offload flag is set: offloading implies a direct output stream
1747 // and all common behaviors are driven by checking only the direct flag
1748 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001749 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1750 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001751 }
Nadav Bar766fb022018-01-07 12:18:03 +02001752 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1753 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001754 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001755
1756 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1757
Eric Laurente83b55d2014-11-14 10:06:21 -08001758 // only allow deep buffering for music stream type
1759 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001760 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001761 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov806170e2024-09-05 17:26:50 -07001762 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001763 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001764 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001765 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001766 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001767 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001768 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001769 audio_is_linear_pcm(config->format) &&
1770 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001771 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001772 AUDIO_OUTPUT_FLAG_DIRECT);
1773 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001774 }
Eric Laurente552edb2014-03-10 17:42:56 -07001775
Carter Hsua3abb402021-10-26 11:11:20 +08001776 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1777 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1778 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1779 }
1780
Eric Laurentf9230d52024-01-26 18:49:09 +01001781 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001782 // was specified and offload or direct playback is not explicitly requested, and there is no
1783 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001784 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001785 if (mSpatializerOutput != nullptr &&
1786 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1787 prefMixerConfigInfo == nullptr &&
1788 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1789 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001790 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001791 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001792 }
1793
Eric Laurentc529cf62020-04-17 18:19:10 -07001794 audio_config_t directConfig = *config;
1795 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001796
1797 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1798 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001799 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001800 return output;
1801 }
1802
Eric Laurent14cbfca2016-03-17 09:42:16 -07001803 // A request for HW A/V sync cannot fallback to a mixed output because time
1804 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001805 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001806 return AUDIO_IO_HANDLE_NONE;
1807 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001808 // A request for Tuner cannot fallback to a mixed output
1809 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1810 return AUDIO_IO_HANDLE_NONE;
1811 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001812
Eric Laurente552edb2014-03-10 17:42:56 -07001813 // ignoring channel mask due to downmix capability in mixer
1814
1815 // open a non direct output
1816
1817 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001818 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001819 // get which output is suitable for the specified stream. The actual
1820 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001821 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001822 if (prefMixerConfigInfo != nullptr) {
1823 for (audio_io_handle_t outputHandle : outputs) {
1824 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1825 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1826 output = outputHandle;
1827 break;
1828 }
1829 }
1830 if (output == AUDIO_IO_HANDLE_NONE) {
1831 // No output open with the preferred profile. Open a new one.
1832 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1833 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1834 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1835 config.format = prefMixerConfigInfo->getConfigBase().format;
1836 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1837 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1838 &config, prefMixerConfigInfo->getFlags());
1839 if (preferredOutput == nullptr) {
1840 ALOGE("%s failed to open output with preferred mixer config", __func__);
1841 } else {
1842 output = preferredOutput->mIoHandle;
1843 }
1844 }
1845 } else {
1846 // at this stage we should ignore the DIRECT flag as no direct output could be
1847 // found earlier
1848 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001849 if (com::android::media::audioserver::
1850 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1851 // If the preferred mixer attributes is null, do not select the bit-perfect output
1852 // unless the bit-perfect output is the only output.
1853 // The bit-perfect output can exist while the passed in preferred mixer attributes
1854 // info is null when it is a high priority client. The high priority clients are
1855 // ringtone or alarm, which is not a bit-perfect use case.
1856 size_t i = 0;
1857 while (i < outputs.size() && outputs.size() > 1) {
1858 auto desc = mOutputs.valueFor(outputs[i]);
1859 // The output descriptor must not be null here.
1860 if (desc->isBitPerfect()) {
1861 outputs.removeItemsAt(i);
1862 } else {
1863 i += 1;
1864 }
1865 }
1866 }
jiabina84c3d32022-12-02 18:59:55 +00001867 output = selectOutput(
1868 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1869 }
Eric Laurente552edb2014-03-10 17:42:56 -07001870 }
François Gaffie11d30102018-11-02 16:09:09 +01001871 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001872 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001873 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001874
Eric Laurente552edb2014-03-10 17:42:56 -07001875 return output;
1876}
1877
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001878sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001879 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1880 mAvailableInputDevices);
1881 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1882}
1883
1884DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1885 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1886 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001887}
1888
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001889const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001890 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001891 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1892 if (msdModule != 0) {
1893 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1894 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1895 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1896 const struct audio_port_config *source = &patch->mPatch.sources[j];
1897 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1898 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001899 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001900 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001901 }
1902 }
1903 }
1904 return msdPatches;
1905}
1906
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001907bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1908 ssize_t index = mAudioPatches.indexOfKey(handle);
1909 if (index < 0) {
1910 return false;
1911 }
1912 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1913 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1914 if (msdModule == nullptr) {
1915 return false;
1916 }
1917 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1918 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1919 return true;
1920 }
1921 index = getMsdOutputPatches().indexOfKey(handle);
1922 if (index < 0) {
1923 return false;
1924 }
1925 return true;
1926}
1927
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001928status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1929 const InputProfileCollection &inputProfiles,
1930 const OutputProfileCollection &outputProfiles,
1931 const sp<DeviceDescriptor> &sourceDevice,
1932 const sp<DeviceDescriptor> &sinkDevice,
1933 AudioProfileVector& sourceProfiles,
1934 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001935 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001936 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001937 return NO_INIT;
1938 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001939 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001940 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001941 return NO_INIT;
1942 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001943 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001944 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1945 inProfile->supportsDevice(sourceDevice)) {
1946 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001947 }
1948 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001949 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001950 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001951 outProfile->supportsDevice(sinkDevice)) {
1952 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001953 }
1954 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001955 return NO_ERROR;
1956}
1957
1958status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1959 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1960 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1961{
Dean Wheatley16809da2022-12-09 14:55:46 +11001962 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1963 static const std::vector<audio_format_t> formatsOrder = {{
1964 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001965 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1966 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001967 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1968 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1969 // preferred).
1970 std::vector<audio_channel_mask_t> masks = {{
1971 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1972 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1973 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1974 // insert index masks (higher counts most preferred) as preferred over position masks
1975 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1976 masks.insert(
1977 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1978 }
1979 return masks;
1980 }();
1981
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001982 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001983 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1984 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001985 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001986 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1987 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001988 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001989 }
1990 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1991 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1992 sinkConfig->format = bestSinkConfig.format;
1993 // For encoded streams force direct flag to prevent downstream mixing.
1994 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1995 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001996 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1997 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001998 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001999 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
2000 // raw and IEC61937 framed streams.
2001 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2002 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
2003 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002004 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
2005 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11002006 sourceConfig->channel_mask =
2007 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
2008 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
2009 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002010 sourceConfig->format = bestSinkConfig.format;
2011 // Copy input stream directly without any processing (e.g. resampling).
2012 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2013 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
2014 if (hwAvSync) {
2015 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2016 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
2017 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2018 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
2019 }
2020 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
2021 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
2022 sinkConfig->config_mask |= config_mask;
2023 sourceConfig->config_mask |= config_mask;
2024 return NO_ERROR;
2025}
2026
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002027PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
2028 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002029{
2030 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002031 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
2032 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
2033 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
2034 if (deviceModule == nullptr) {
2035 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
2036 return patchBuilder;
2037 }
2038 const InputProfileCollection inputProfiles = msdIsSource ?
2039 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
2040 const OutputProfileCollection outputProfiles = msdIsSource ?
2041 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2042
2043 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2044 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2045 device : getMsdAudioOutDevices().itemAt(0);
2046 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2047
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002048 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2049 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002050 AudioProfileVector sourceProfiles;
2051 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002052 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2053 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002054 for (auto hwAvSync : { true, false }) {
2055 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2056 sourceProfiles, sinkProfiles) != NO_ERROR) {
2057 continue;
2058 }
2059 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2060 &sinkConfig) == NO_ERROR) {
2061 // Found a matching config. Re-create PatchBuilder with this config.
2062 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2063 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002064 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002065 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002066 " supporting PCM format conversion.", __func__);
2067 return patchBuilder;
2068}
2069
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002070status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002071 DeviceVector devices;
2072 if (outputDevices != nullptr && outputDevices->size() > 0) {
2073 devices.add(*outputDevices);
2074 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002075 // Use media strategy for unspecified output device. This should only
2076 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2077 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002078 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002079 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002080 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002081 }
Michael Chan6fb34492020-12-08 15:44:49 +11002082 std::vector<PatchBuilder> patchesToCreate;
2083 for (auto i = 0u; i < devices.size(); ++i) {
2084 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002085 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002086 }
2087 // Retain only the MSD patches associated with outputDevices request.
2088 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002089 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002090 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2091 auto retainedPatch = false;
2092 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2093 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2094 patchesToRemove.removeItemsAt(i);
2095 retainedPatch = true;
2096 break;
2097 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002098 }
Michael Chan6fb34492020-12-08 15:44:49 +11002099 if (retainedPatch) {
2100 it = patchesToCreate.erase(it);
2101 continue;
2102 }
2103 ++it;
2104 }
2105 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2106 return NO_ERROR;
2107 }
2108 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2109 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002110 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002111 }
Michael Chan6fb34492020-12-08 15:44:49 +11002112 status_t status = NO_ERROR;
2113 for (const auto &p : patchesToCreate) {
2114 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2115 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2116 char message[256];
2117 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2118 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2119 currStatus == NO_ERROR ? "Success" : "Error",
2120 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2121 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2122 if (currStatus == NO_ERROR) {
2123 ALOGD("%s", message);
2124 } else {
2125 ALOGE("%s", message);
2126 if (status == NO_ERROR) {
2127 status = currStatus;
2128 }
2129 }
2130 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002131 return status;
2132}
2133
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002134void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2135 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002136 for (size_t i = 0; i < msdPatches.size(); i++) {
2137 const auto& patch = msdPatches[i];
2138 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2139 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2140 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2141 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2142 releaseAudioPatch(patch->getHandle(), mUidCached);
2143 break;
2144 }
2145 }
2146 }
2147}
2148
Dorin Drimus94d94412022-02-02 09:05:02 +01002149bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002150 DeviceVector devicesToCheck =
2151 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002152 AudioPatchCollection msdPatches = getMsdOutputPatches();
2153 for (size_t i = 0; i < msdPatches.size(); i++) {
2154 const auto& patch = msdPatches[i];
2155 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2156 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2157 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2158 const auto& foundDevice = devicesToCheck.getDevice(
2159 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2160 if (foundDevice != nullptr) {
2161 devicesToCheck.remove(foundDevice);
2162 if (devicesToCheck.isEmpty()) {
2163 return true;
2164 }
2165 }
2166 }
2167 }
2168 }
2169 return false;
2170}
2171
Eric Laurente0720872014-03-11 09:30:41 -07002172audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002173 audio_output_flags_t flags,
2174 audio_format_t format,
2175 audio_channel_mask_t channelMask,
2176 uint32_t samplingRate,
2177 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002178{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002179 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2180 "%s called with format %#x", __func__, format);
2181
jiabinebb6af42020-06-09 17:31:17 -07002182 // Return the output that haptic-generating attached to when 1) session id is specified,
2183 // 2) haptic-generating effect exists for given session id and 3) the output that
2184 // haptic-generating effect attached to is in given outputs.
2185 if (sessionId != AUDIO_SESSION_NONE) {
2186 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2187 sessionId, FX_IID_HAPTICGENERATOR);
2188 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2189 return hapticGeneratingOutput;
2190 }
2191 }
2192
Eric Laurent16c66dd2019-05-01 17:54:10 -07002193 // Flags disqualifying an output: the match must happen before calling selectOutput()
2194 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2195 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2196
2197 // Flags expressing a functional request: must be honored in priority over
2198 // other criteria
2199 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2200 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002201 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2202 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002203 // Flags expressing a performance request: have lower priority than serving
2204 // requested sampling rate or channel mask
2205 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2206 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2207 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2208
2209 const audio_output_flags_t functionalFlags =
2210 (audio_output_flags_t)(flags & kFunctionalFlags);
2211 const audio_output_flags_t performanceFlags =
2212 (audio_output_flags_t)(flags & kPerformanceFlags);
2213
2214 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2215
Eric Laurente552edb2014-03-10 17:42:56 -07002216 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002217 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002218 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002219 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002220 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002221 // with tiebreak preferring the minimum number of extra functional flags
2222 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002223 // 3: the output supporting the exact channel mask
2224 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002225 // 5: the output with the highest sampling rate if the requested sample rate is
2226 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002227 // 6: the output with the highest number of requested performance flags
2228 // 7: the output with the bit depth the closest to the requested one
2229 // 8: the primary output
2230 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002231
Eric Laurent16c66dd2019-05-01 17:54:10 -07002232 // matching criteria values in priority order for best matching output so far
2233 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002234
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002235 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002236 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2237 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2238 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002239
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002240 for (audio_io_handle_t output : outputs) {
2241 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002242 // matching criteria values in priority order for current output
2243 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002244
Eric Laurent16c66dd2019-05-01 17:54:10 -07002245 if (outputDesc->isDuplicated()) {
2246 continue;
2247 }
2248 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2249 continue;
2250 }
Eric Laurent8838a382014-09-08 16:44:28 -07002251
Eric Laurent16c66dd2019-05-01 17:54:10 -07002252 // If haptic channel is specified, use the haptic output if present.
2253 // When using haptic output, same audio format and sample rate are required.
2254 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002255 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002256 // skip if haptic channel specified but output does not support it, or output support haptic
2257 // but there is no haptic channel requested AND no orphan haptic effect exist
2258 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2259 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002260 continue;
2261 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002262 // In the case of audio-coupled-haptic playback, there is no format conversion and
2263 // resampling in the framework, same format/channel/sampleRate for client and the output
2264 // thread is required. In the case of HapticGenerator effect, do not require format
2265 // matching.
2266 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2267 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002268 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002269 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002270 }
2271
2272 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002273 const int matchingFunctionalFlags =
2274 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2275 const int totalFunctionalFlags =
2276 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2277 // Prefer matching functional flags, but subtract unnecessary functional flags.
2278 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002279
2280 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002281 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2282 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002283 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2284 channelCount <= outputChannelCount) {
2285 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002286 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2287 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002288 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002289 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002290 currentMatchCriteria[3] = outputChannelCount;
2291 }
2292
2293 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002294 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002295 int diff; // avoid unsigned integer overflow.
2296 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2297
2298 // prefer the closest output sampling rate greater than or equal to target
2299 // if none exists, prefer the closest output sampling rate less than target.
2300 //
2301 // criteria is offset to make non-negative.
2302 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002303 }
2304
2305 // performance flags match
2306 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2307
2308 // format match
2309 if (format != AUDIO_FORMAT_INVALID) {
2310 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002311 PolicyAudioPort::kFormatDistanceMax -
2312 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002313 }
2314
2315 // primary output match
2316 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2317
2318 // compare match criteria by priority then value
2319 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2320 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2321 bestMatchCriteria = currentMatchCriteria;
2322 bestOutput = output;
2323
2324 std::stringstream result;
2325 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2326 std::ostream_iterator<int>(result, " "));
2327 ALOGV("%s new bestOutput %d criteria %s",
2328 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002329 }
2330 }
2331
Eric Laurent16c66dd2019-05-01 17:54:10 -07002332 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002333}
2334
Eric Laurent8fc147b2018-07-22 19:13:55 -07002335status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002336{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002337 ALOGV("%s portId %d", __FUNCTION__, portId);
2338
2339 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2340 if (outputDesc == 0) {
2341 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002342 return BAD_VALUE;
2343 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002344 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002345
Eric Laurent8fc147b2018-07-22 19:13:55 -07002346 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002347 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002348
jiabin220eea12024-05-17 17:55:20 +00002349 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2350 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2351 && outputDesc->isBitPerfect()) {
2352 // Usually, APM selects bit-perfect output for high priority use cases only when
2353 // bit-perfect output is the only output that can be routed to the selected device.
2354 // However, here is no need to play high priority use cases such as ringtone and alarm
2355 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2356 // can attach to new output.
2357 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2358 __func__, client->stream());
2359 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2360 return DEAD_OBJECT;
2361 }
2362
Eric Laurent733ce942017-12-07 12:18:25 -08002363 status_t status = outputDesc->start();
2364 if (status != NO_ERROR) {
2365 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002366 }
2367
Eric Laurent97ac8712018-07-27 18:59:02 -07002368 uint32_t delayMs;
2369 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002370
2371 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002372 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002373 if (status == DEAD_OBJECT) {
2374 sp<SwAudioOutputDescriptor> desc =
2375 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2376 if (desc == nullptr) {
2377 // This is not common, it may indicate something wrong with the HAL.
2378 ALOGE("%s unable to open output with default config", __func__);
2379 return status;
2380 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002381 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002382 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002383 }
jiabina84c3d32022-12-02 18:59:55 +00002384
2385 // If the client is the first one active on preferred mixer parameters, reopen the output
2386 // if the current mixer parameters doesn't match the preferred one.
2387 if (outputDesc->devices().size() == 1) {
2388 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2389 outputDesc->devices()[0]->getId(), client->strategy());
2390 if (info != nullptr && info->getUid() == client->uid()) {
2391 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2392 info->getConfigBase(), info->getFlags())) {
2393 stopSource(outputDesc, client);
2394 outputDesc->stop();
2395 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2396 config.channel_mask = info->getConfigBase().channel_mask;
2397 config.sample_rate = info->getConfigBase().sample_rate;
2398 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002399 sp<SwAudioOutputDescriptor> desc =
2400 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2401 if (desc == nullptr) {
2402 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002403 }
jiabin220eea12024-05-17 17:55:20 +00002404 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002405 // Intentionally return error to let the client side resending request for
2406 // creating and starting.
2407 return DEAD_OBJECT;
2408 }
2409 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002410 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002411 // If it is first bit-perfect client, reroute all clients that will be routed to
2412 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2413 PortHandleVector clientsToInvalidate;
jiabine6b87492024-09-18 23:36:14 +00002414 std::vector<sp<SwAudioOutputDescriptor>> outputsToResetDevice;
jiabine3d1f552023-06-14 17:42:17 +00002415 for (size_t i = 0; i < mOutputs.size(); i++) {
jiabinfedb92e2024-09-16 21:36:30 +00002416 if (mOutputs[i] == outputDesc || (!mOutputs[i]->devices().isEmpty() &&
2417 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty())) {
jiabine3d1f552023-06-14 17:42:17 +00002418 continue;
2419 }
jiabine6b87492024-09-18 23:36:14 +00002420 if (mOutputs[i]->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
2421 outputsToResetDevice.push_back(mOutputs[i]);
2422 }
jiabine3d1f552023-06-14 17:42:17 +00002423 for (const auto& c : mOutputs[i]->getClientIterable()) {
2424 clientsToInvalidate.push_back(c->portId());
2425 }
2426 }
2427 if (!clientsToInvalidate.empty()) {
2428 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2429 __func__);
2430 mpClientInterface->invalidateTracks(clientsToInvalidate);
2431 }
jiabine6b87492024-09-18 23:36:14 +00002432 for (const auto& output : outputsToResetDevice) {
2433 resetOutputDevice(output, 0 /*delayMs*/, nullptr /*patchHandle*/);
2434 }
jiabine3d1f552023-06-14 17:42:17 +00002435 }
jiabina84c3d32022-12-02 18:59:55 +00002436 }
2437 }
2438
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002439 if (client->hasPreferredDevice()) {
2440 // playback activity with preferred device impacts routing occurred, inform upper layers
2441 mpClientInterface->onRoutingUpdated();
2442 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002443 if (delayMs != 0) {
2444 usleep(delayMs * 1000);
2445 }
2446
jiabin220eea12024-05-17 17:55:20 +00002447 if (status == NO_ERROR &&
2448 outputDesc->mPreferredAttrInfo != nullptr &&
2449 outputDesc->isBitPerfect() &&
2450 com::android::media::audioserver::
2451 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2452 // A new client is started on bit-perfect output, update all clients internal mute.
2453 updateClientsInternalMute(outputDesc);
2454 }
2455
Eric Laurentc75307b2015-03-17 15:29:32 -07002456 return status;
2457}
2458
Eric Laurent96d1dda2022-03-14 17:14:19 +01002459bool AudioPolicyManager::isLeUnicastActive() const {
2460 if (isInCall()) {
2461 return true;
2462 }
2463 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2464}
2465
2466bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2467 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2468 return false;
2469 }
2470 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2471 ALOGV("%s active %d", __func__, active);
2472 return active;
2473}
2474
Eric Laurent97ac8712018-07-27 18:59:02 -07002475status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2476 const sp<TrackClientDescriptor>& client,
2477 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002478{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002479 // cannot start playback of STREAM_TTS if any other output is being used
2480 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002481
2482 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002483 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002484 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002485 auto clientStrategy = client->strategy();
2486 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002487 if (stream == AUDIO_STREAM_TTS) {
2488 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002489 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002490 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002491 return INVALID_OPERATION;
2492 } else {
2493 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2494 }
2495 } else {
2496 // some playback other than beacon starts
2497 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2498 }
2499
Eric Laurent77305a62016-07-25 16:39:22 -07002500 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002501 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002502 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002503
François Gaffie11d30102018-11-02 16:09:09 +01002504 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002505 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002506 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002507 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002508 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002509 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002510 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002511 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002512 } else {
2513 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002514 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002515 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2516 AUDIO_FORMAT_DEFAULT);
2517 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2518 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002519 }
2520
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002521 // requiresMuteCheck is false when we can bypass mute strategy.
2522 // It covers a common case when there is no materially active audio
2523 // and muting would result in unnecessary delay and dropped audio.
2524 const uint32_t outputLatencyMs = outputDesc->latency();
2525 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002526 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002527
Eric Laurente552edb2014-03-10 17:42:56 -07002528 // increment usage count for this stream on the requested output:
2529 // NOTE that the usage count is the same for duplicated output and hardware output which is
2530 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002531 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002532
2533 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002534 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002535 // Preferred device may be exclusive, use only if no other active clients on this output
2536 devices = DeviceVector(
2537 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2538 } else {
2539 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2540 }
François Gaffie11d30102018-11-02 16:09:09 +01002541 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002542 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002543 }
2544 }
Eric Laurente552edb2014-03-10 17:42:56 -07002545
François Gaffiec005e562018-11-06 15:04:49 +01002546 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002547 selectOutputForMusicEffects();
2548 }
2549
François Gaffie1c878552018-11-22 16:53:21 +01002550 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002551 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002552 if (devices.isEmpty()) {
2553 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002554 }
François Gaffiec005e562018-11-06 15:04:49 +01002555 bool shouldWait =
2556 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2557 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2558 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002559 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002560 const bool needToCloseBitPerfectOutput =
2561 (com::android::media::audioserver::
2562 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2563 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2564 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002565 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002566 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002567 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002568 // An output has a shared device if
2569 // - managed by the same hw module
2570 // - supports the currently selected device
2571 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002572 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002573
Eric Laurent77305a62016-07-25 16:39:22 -07002574 // force a device change if any other output is:
2575 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002576 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002577 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002578 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002579 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002580 // change the device currently selected by the other output.
2581 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002582 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002583 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002584 force = true;
2585 }
2586 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002587 // a notification so that audio focus effect can propagate, or that a mute/unmute
2588 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002589 const uint32_t latencyMs = desc->latency();
2590 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2591
2592 if (shouldWait && isActive && (waitMs < latencyMs)) {
2593 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002594 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002595
2596 // Require mute check if another output is on a shared device
2597 // and currently active to have proper drain and avoid pops.
2598 // Note restoring AudioTracks onto this output needs to invoke
2599 // a volume ramp if there is no mute.
2600 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002601
2602 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2603 outputsToReopen.push_back(desc);
2604 }
Eric Laurente552edb2014-03-10 17:42:56 -07002605 }
2606 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002607
jiabin220eea12024-05-17 17:55:20 +00002608 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002609 // If the output is open with preferred mixer attributes, but the routed device is
2610 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2611 // changed.
2612 return DEAD_OBJECT;
2613 }
jiabin220eea12024-05-17 17:55:20 +00002614 for (auto& outputToReopen : outputsToReopen) {
2615 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2616 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002617 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302618 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2619 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002620
Eric Laurente552edb2014-03-10 17:42:56 -07002621 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002622 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002623 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002624 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002625 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002626 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002627 outputDesc->useHwGain() /*force*/)) {
2628 // request AudioService to reinitialize the volume curves asynchronously
2629 ALOGE("checkAndSetVolume failed, requesting volume range init");
2630 mpClientInterface->onVolumeRangeInitRequest();
2631 };
Eric Laurente552edb2014-03-10 17:42:56 -07002632
2633 // update the outputs if starting an output with a stream that can affect notification
2634 // routing
2635 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002636
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002637 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002638 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002639 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002640 }
Eric Laurentdc462862016-07-19 12:29:53 -07002641
2642 if (waitMs > muteWaitMs) {
2643 *delayMs = waitMs - muteWaitMs;
2644 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002645
2646 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2647 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2648 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2649 // change occurs after the MixerThread starts and causes a stream volume
2650 // glitch.
2651 //
2652 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002653 }
Eric Laurentdc462862016-07-19 12:29:53 -07002654
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002655 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002656 mEngine->getForceUse(
2657 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002658 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002659 }
2660
Eric Laurent97ac8712018-07-27 18:59:02 -07002661 // Automatically enable the remote submix input when output is started on a re routing mix
2662 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002663 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2664 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002665 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2666 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2667 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002668 "remote-submix",
2669 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002670 }
2671
Eric Laurent96d1dda2022-03-14 17:14:19 +01002672 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2673
Eric Laurente552edb2014-03-10 17:42:56 -07002674 return NO_ERROR;
2675}
2676
Eric Laurent96d1dda2022-03-14 17:14:19 +01002677void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2678 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2679 bool isUnicastActive = isLeUnicastActive();
2680
2681 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002682 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002683 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2684 for (size_t i = 0; i < mOutputs.size(); i++) {
2685 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2686 if (desc != ignoredOutput && desc->isActive()
2687 && ((isUnicastActive &&
2688 !desc->devices().
2689 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2690 || (wasUnicastActive &&
2691 !desc->devices().getDevicesFromTypes(
2692 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2693 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2694 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002695 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002696 // If the device is using preferred mixer attributes, the output need to reopen
2697 // with default configuration when the new selected devices are different from
2698 // current routing devices.
2699 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2700 continue;
2701 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302702 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002703 // re-apply device specific volume if not done by setOutputDevice()
2704 if (!force) {
2705 applyStreamVolumes(desc, newDevices.types(), delayMs);
2706 }
2707 }
2708 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002709 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002710 }
2711}
2712
Eric Laurent8fc147b2018-07-22 19:13:55 -07002713status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002714{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002715 ALOGV("%s portId %d", __FUNCTION__, portId);
2716
2717 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2718 if (outputDesc == 0) {
2719 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002720 return BAD_VALUE;
2721 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002722 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002723
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002724 if (client->hasPreferredDevice(true)) {
2725 // playback activity with preferred device impacts routing occurred, inform upper layers
2726 mpClientInterface->onRoutingUpdated();
2727 }
2728
Eric Laurent97ac8712018-07-27 18:59:02 -07002729 ALOGV("stopOutput() output %d, stream %d, session %d",
2730 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002731
Eric Laurent97ac8712018-07-27 18:59:02 -07002732 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002733
Eric Laurent733ce942017-12-07 12:18:25 -08002734 if (status == NO_ERROR ) {
2735 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002736 } else {
2737 return status;
2738 }
2739
2740 if (outputDesc->devices().size() == 1) {
2741 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2742 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002743 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002744 if (info != nullptr && info->getUid() == client->uid()) {
2745 info->decreaseActiveClient();
2746 if (info->getActiveClientCount() == 0) {
2747 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002748 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002749 }
2750 }
jiabin220eea12024-05-17 17:55:20 +00002751 if (com::android::media::audioserver::
2752 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2753 !outputReopened && outputDesc->isBitPerfect()) {
2754 // Only need to update the clients' internal mute when the output is bit-perfect and it
2755 // is not reopened.
2756 updateClientsInternalMute(outputDesc);
2757 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002758 }
2759 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002760}
2761
Eric Laurent97ac8712018-07-27 18:59:02 -07002762status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2763 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002764{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002765 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002766 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002767 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002768 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002769
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002770 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2771
François Gaffie1c878552018-11-22 16:53:21 +01002772 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2773 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002774 // Automatically disable the remote submix input when output is stopped on a
2775 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002776 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002777 if (isSingleDeviceType(
2778 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002779 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002780 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002781 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2782 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002783 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002784 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002785 }
2786 }
2787 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002788 if (client->hasPreferredDevice(true) &&
2789 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002790 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002791 forceDeviceUpdate = true;
2792 }
2793
Eric Laurente552edb2014-03-10 17:42:56 -07002794 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002795 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002796
Eric Laurente552edb2014-03-10 17:42:56 -07002797 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002798 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002799 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002800 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002801
2802 // If the routing does not change, if an output is routed on a device using HwGain
2803 // (aka setAudioPortConfig) and there are still active clients following different
2804 // volume group(s), force reapply volume
2805 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2806 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2807
Eric Laurente552edb2014-03-10 17:42:56 -07002808 // delay the device switch by twice the latency because stopOutput() is executed when
2809 // the track stop() command is received and at that time the audio track buffer can
2810 // still contain data that needs to be drained. The latency only covers the audio HAL
2811 // and kernel buffers. Also the latency does not always include additional delay in the
2812 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302813 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002814 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002815
2816 // force restoring the device selection on other active outputs if it differs from the
2817 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002818 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002819 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002820 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002821 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002822 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002823 desc->isActive() &&
2824 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002825 (newDevices != desc->devices())) {
2826 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2827 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002828
jiabin220eea12024-05-17 17:55:20 +00002829 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002830 // If the device is using preferred mixer attributes, the output need to
2831 // reopen with default configuration when the new selected devices are
2832 // different from current routing devices.
2833 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2834 continue;
2835 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302836 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002837
Eric Laurent57de36c2016-09-28 16:59:11 -07002838 // re-apply device specific volume if not done by setOutputDevice()
2839 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002840 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002841 }
Eric Laurente552edb2014-03-10 17:42:56 -07002842 }
2843 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002844 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002845 // update the outputs if stopping one with a stream that can affect notification routing
2846 handleNotificationRoutingForStream(stream);
2847 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002848
2849 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2850 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002851 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002852 }
2853
François Gaffiec005e562018-11-06 15:04:49 +01002854 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002855 selectOutputForMusicEffects();
2856 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002857
2858 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2859
Eric Laurente552edb2014-03-10 17:42:56 -07002860 return NO_ERROR;
2861 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002862 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002863 return INVALID_OPERATION;
2864 }
2865}
2866
jiabinbce0c1d2020-10-05 11:20:18 -07002867bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002868{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002869 ALOGV("%s portId %d", __FUNCTION__, portId);
2870
2871 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2872 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002873 // If an output descriptor is closed due to a device routing change,
2874 // then there are race conditions with releaseOutput from tracks
2875 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2876 // destroyed shortly thereafter.
2877 //
2878 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002879 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002880 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002881 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002882
2883 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002884
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302885 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2886 if (outputDesc->isClientActive(client)) {
2887 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2888 stopOutput(portId);
2889 }
2890
Eric Laurent8fc147b2018-07-22 19:13:55 -07002891 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2892 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002893 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002894 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002895 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002896 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002897 if (--outputDesc->mDirectOpenCount == 0) {
2898 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002899 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002900 }
2901 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302902
Andy Hung39efb7a2018-09-26 15:39:28 -07002903 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002904 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2905 // The output is pending reopened to query dynamic profiles and
2906 // there is no active clients
2907 closeOutput(outputDesc->mIoHandle);
2908 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2909 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2910 if (newOutputDesc == nullptr) {
2911 ALOGE("%s failed to open output", __func__);
2912 }
2913 return true;
2914 }
2915 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002916}
2917
Eric Laurentcaf7f482014-11-25 17:50:47 -08002918status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2919 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002920 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002921 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002922 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002923 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002924 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002925 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002926 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002927 audio_port_handle_t *portId,
2928 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002929{
François Gaffiec005e562018-11-06 15:04:49 +01002930 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002931 "flags %#x attributes=%s requested device ID %d",
2932 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2933 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002934
Eric Laurentad2e7b92017-09-14 20:06:42 -07002935 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002936 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002937 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002938 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002939 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002940 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002941 sp<RecordClientDescriptor> clientDesc;
2942 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002943 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002944 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002945
2946 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2947 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2948 return INVALID_OPERATION;
2949 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002950
Francois Gaffie716e1432019-01-14 16:58:59 +01002951 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2952 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002953 }
2954
Paul McLean466dc8e2015-04-17 13:15:36 -06002955 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002956 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002957 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002958
Eric Laurentad2e7b92017-09-14 20:06:42 -07002959 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2960 // possible
2961 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2962 *input != AUDIO_IO_HANDLE_NONE) {
2963 ssize_t index = mInputs.indexOfKey(*input);
2964 if (index < 0) {
2965 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2966 status = BAD_VALUE;
2967 goto error;
2968 }
2969 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002970 RecordClientVector clients = inputDesc->getClientsForSession(session);
2971 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002972 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2973 status = BAD_VALUE;
2974 goto error;
2975 }
2976 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2977 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002978 // corresponds to a new client and is only permitted from the same UID.
2979 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002980 if (clients.size() > 1) {
2981 for (const auto& client : clients) {
2982 // The client map is ordered by key values (portId) and portIds are allocated
2983 // incrementaly. So the first client in this list is the one opened by audio flinger
2984 // when the mmap stream is created and should be ignored as it does not correspond
2985 // to an actual client
2986 if (client == *clients.cbegin()) {
2987 continue;
2988 }
2989 if (uid != client->uid() && !client->isSilenced()) {
2990 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2991 uid, client->portId(), client->uid());
2992 status = INVALID_OPERATION;
2993 goto error;
2994 }
Eric Laurent331679c2018-04-16 17:03:16 -07002995 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002996 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002997 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002998 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002999
Eric Laurentfecbceb2021-02-09 14:46:43 +01003000 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003001 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003002 }
3003
3004 *input = AUDIO_IO_HANDLE_NONE;
3005 *inputType = API_INPUT_INVALID;
3006
Francois Gaffie716e1432019-01-14 16:58:59 +01003007 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02003008 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003009 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003010 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003011 ALOGW("%s could not find input mix for attr %s",
3012 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07003013 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01003014 }
jiabinc1de2df2019-05-07 14:26:40 -07003015 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
3016 String8(attr->tags + strlen("addr=")),
3017 AUDIO_FORMAT_DEFAULT);
3018 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07003019 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07003020 __func__, attributes.source, attributes.tags);
3021 status = BAD_VALUE;
3022 goto error;
3023 }
3024
Kevin Rocard25f9b052019-02-27 15:08:54 -08003025 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
3026 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
3027 } else {
3028 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
3029 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01003030 if (virtualDeviceId) {
3031 *virtualDeviceId = policyMix->mVirtualDeviceId;
3032 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003033 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003034 if (explicitRoutingDevice != nullptr) {
3035 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07003036 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01003037 // Prevent from storing invalid requested device id in clients
3038 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003039 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08003040 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
3041 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07003042 }
François Gaffie11d30102018-11-02 16:09:09 +01003043 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003044 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003045 status = BAD_VALUE;
3046 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08003047 }
Alden DSouzab7d20782021-02-08 08:51:42 -08003048 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
3049 *inputType = API_INPUT_MIX_CAPTURE;
3050 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01003051 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3052 // there is an external policy, but this input is attached to a mix of recorders,
3053 // meaning it receives audio injected into the framework, so the recorder doesn't
3054 // know about it and is therefore considered "legacy"
3055 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003056
3057 if (virtualDeviceId) {
3058 *virtualDeviceId = policyMix->mVirtualDeviceId;
3059 }
François Gaffie11d30102018-11-02 16:09:09 +01003060 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003061 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003062 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003063 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003064 } else {
3065 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003066 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003067
Eric Laurent599c7582015-12-07 18:05:55 -08003068 }
3069
François Gaffiec005e562018-11-06 15:04:49 +01003070 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003071 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003072 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003073 AudioProfileVector profiles;
3074 status_t ret = getProfilesForDevices(
3075 DeviceVector(device), profiles, flags, true /*isInput*/);
3076 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003077 const auto channels = profiles[0]->getChannels();
3078 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3079 config->channel_mask = *channels.begin();
3080 }
3081 const auto sampleRates = profiles[0]->getSampleRates();
3082 if (!sampleRates.empty() &&
3083 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3084 config->sample_rate = *sampleRates.begin();
3085 }
jiabinf1c73972022-04-14 16:28:52 -07003086 config->format = profiles[0]->getFormat();
3087 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003088 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003089 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003090
Marvin Ramine5a122d2023-12-07 13:57:59 +01003091
3092 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3093 *virtualDeviceId = policyMix->mVirtualDeviceId;
3094 }
3095
Eric Laurent8f42ea12018-08-08 09:08:25 -07003096exit:
3097
François Gaffiec005e562018-11-06 15:04:49 +01003098 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3099 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003100
Francois Gaffie716e1432019-01-14 16:58:59 +01003101 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003102 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003103 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003104
Mikhail Naganov2996f672019-04-18 12:29:59 -07003105 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003106 requestedDeviceId, attributes.source, flags,
3107 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003108 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003109 // Move (if found) effect for the client session to its input
3110 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003111 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003112
3113 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3114 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003115
Eric Laurent599c7582015-12-07 18:05:55 -08003116 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003117
3118error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003119 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003120}
3121
3122
François Gaffie11d30102018-11-02 16:09:09 +01003123audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003124 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003125 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003126 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003127 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003128 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003129{
3130 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003131 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003132 bool isSoundTrigger = false;
3133
François Gaffiec005e562018-11-06 15:04:49 +01003134 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003135 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3136 if (index >= 0) {
3137 input = mSoundTriggerSessions.valueFor(session);
3138 isSoundTrigger = true;
3139 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3140 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3141 } else {
3142 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003143 }
François Gaffiec005e562018-11-06 15:04:49 +01003144 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003145 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003146 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003147 }
3148
Carter Hsua3abb402021-10-26 11:11:20 +08003149 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3150 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3151 }
3152
Eric Laurentfe231122017-11-17 17:48:06 -08003153 // sampling rate and flags may be updated by getInputProfile
3154 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3155 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003156 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003157 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003158 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003159 // find a compatible input profile (not necessarily identical in parameters)
3160 sp<IOProfile> profile = getInputProfile(
3161 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3162 if (profile == nullptr) {
3163 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003164 }
jiabin2fd710d2022-05-02 23:20:22 +00003165
Glenn Kasten05ddca52016-02-11 08:17:12 -08003166 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003167 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003168 if (samplingRate == 0) {
3169 samplingRate = profileSamplingRate;
3170 }
Eric Laurente552edb2014-03-10 17:42:56 -07003171
Eric Laurent322b4d22015-04-03 15:57:54 -07003172 if (profile->getModuleHandle() == 0) {
3173 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003174 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003175 }
3176
Eric Laurentec376dc2021-04-08 20:41:22 +02003177 // Reuse an already opened input if a client with the same session ID already exists
3178 // on that input
3179 for (size_t i = 0; i < mInputs.size(); i++) {
3180 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3181 if (desc->mProfile != profile) {
3182 continue;
3183 }
3184 RecordClientVector clients = desc->clientsList();
3185 for (const auto &client : clients) {
3186 if (session == client->session()) {
3187 return desc->mIoHandle;
3188 }
3189 }
3190 }
3191
Eric Laurentc71b11b2024-06-03 12:54:53 +00003192 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003193 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003194 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3195 // First pick best candidate for preemption (there may not be any):
3196 // - Preempt and input if:
3197 // - It has only strictly lower priority use cases than the new client
3198 // - It has equal priority use cases than the new client, was not
3199 // opened thanks to preemption or has been active since opened.
3200 // - Order the preemption candidates by inactive first and priority second
3201 sp<AudioInputDescriptor> closeCandidate;
3202 int leastCloseRank = INT_MAX;
3203 static const int sCloseActive = 0x100;
3204
3205 for (size_t i = 0; i < mInputs.size(); i++) {
3206 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3207 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003208 continue;
3209 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003210 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3211 if (topPrioClient == nullptr) {
3212 continue;
3213 }
3214 int topPrio = source_priority(topPrioClient->source());
3215 if (topPrio < source_priority(attributes.source)
3216 || (topPrio == source_priority(attributes.source)
3217 && !desc->isPreemptor())) {
3218 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3219 if (closeRank < leastCloseRank) {
3220 leastCloseRank = closeRank;
3221 closeCandidate = desc;
3222 }
3223 }
3224 }
3225
3226 if (closeCandidate != nullptr) {
3227 closeInput(closeCandidate->mIoHandle);
3228 // Mark the new input as being issued from a preemption
3229 // so that is will not be preempted later
3230 isPreemptor = true;
3231 } else {
3232 // Then pick the best reusable input (There is always one)
3233 // The order of preference is:
3234 // 1) active inputs with same use case as the new client
3235 // 2) inactive inputs with same use case
3236 // 3) active inputs with different use cases
3237 // 4) inactive inputs with different use cases
3238 sp<AudioInputDescriptor> reuseCandidate;
3239 int leastReuseRank = INT_MAX;
3240 static const int sReuseDifferentUseCase = 0x100;
3241
3242 for (size_t i = 0; i < mInputs.size(); i++) {
3243 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3244 if (desc->mProfile != profile) {
3245 continue;
3246 }
3247 int reuseRank = sReuseDifferentUseCase;
3248 for (const auto& client: desc->getClientIterable()) {
3249 if (client->source() == attributes.source) {
3250 reuseRank = 0;
3251 break;
3252 }
3253 }
3254 reuseRank += desc->isActive() ? 0 : 1;
3255 if (reuseRank < leastReuseRank) {
3256 leastReuseRank = reuseRank;
3257 reuseCandidate = desc;
3258 }
3259 }
3260 return reuseCandidate->mIoHandle;
3261 }
3262 } else { // fix_input_sharing_logic()
3263 for (size_t i = 0; i < mInputs.size(); ) {
3264 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3265 if (desc->mProfile != profile) {
3266 i++;
3267 continue;
3268 }
3269 // if sound trigger, reuse input if used by other sound trigger on same session
3270 // else
3271 // reuse input if active client app is not in IDLE state
3272 //
3273 RecordClientVector clients = desc->clientsList();
3274 bool doClose = false;
3275 for (const auto& client : clients) {
3276 if (isSoundTrigger != client->isSoundTrigger()) {
3277 continue;
3278 }
3279 if (client->isSoundTrigger()) {
3280 if (session == client->session()) {
3281 return desc->mIoHandle;
3282 }
3283 continue;
3284 }
3285 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003286 return desc->mIoHandle;
3287 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003288 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003289 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003290 if (doClose) {
3291 closeInput(desc->mIoHandle);
3292 } else {
3293 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003294 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003295 }
3296 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003297 }
3298
Eric Laurentc71b11b2024-06-03 12:54:53 +00003299 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3300 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003301
Eric Laurentfe231122017-11-17 17:48:06 -08003302 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3303 lConfig.sample_rate = profileSamplingRate;
3304 lConfig.channel_mask = profileChannelMask;
3305 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003306
François Gaffie11d30102018-11-02 16:09:09 +01003307 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003308
3309 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003310 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003311 (profileSamplingRate != lConfig.sample_rate) ||
3312 !audio_formats_match(profileFormat, lConfig.format) ||
3313 (profileChannelMask != lConfig.channel_mask)) {
3314 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003315 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003316 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003317 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003318 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003319 }
Eric Laurent599c7582015-12-07 18:05:55 -08003320 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003321 }
3322
Eric Laurentc722f302014-12-10 11:21:49 -08003323 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003324
Eric Laurent599c7582015-12-07 18:05:55 -08003325 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003326 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003327
Eric Laurent599c7582015-12-07 18:05:55 -08003328 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003329}
3330
Eric Laurent4eb58f12018-12-07 16:41:02 -08003331status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003332{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003333 ALOGV("%s portId %d", __FUNCTION__, portId);
3334
3335 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3336 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003337 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003338 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003339 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003340 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003341 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003342 if (client->active()) {
3343 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3344 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003345 }
3346
Eric Laurent8f42ea12018-08-08 09:08:25 -07003347 audio_session_t session = client->session();
3348
Eric Laurent4eb58f12018-12-07 16:41:02 -08003349 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003350
Eric Laurent4eb58f12018-12-07 16:41:02 -08003351 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003352
Eric Laurent4eb58f12018-12-07 16:41:02 -08003353 status_t status = inputDesc->start();
3354 if (status != NO_ERROR) {
3355 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003356 }
Eric Laurente552edb2014-03-10 17:42:56 -07003357
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003358 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003359 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003360 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003361
Eric Laurent8f42ea12018-08-08 09:08:25 -07003362 // indicate active capture to sound trigger service if starting capture from a mic on
3363 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003364 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003365 if (device != nullptr) {
3366 status = setInputDevice(input, device, true /* force */);
3367 } else {
3368 ALOGW("%s no new input device can be found for descriptor %d",
3369 __FUNCTION__, inputDesc->getId());
3370 status = BAD_VALUE;
3371 }
Eric Laurente552edb2014-03-10 17:42:56 -07003372
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003373 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003374 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003375 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003376 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003377 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3378 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003379 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003380 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003381
François Gaffie11d30102018-11-02 16:09:09 +01003382 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3383 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003384 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003385 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003386 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003387
Eric Laurent8f42ea12018-08-08 09:08:25 -07003388 // automatically enable the remote submix output when input is started if not
3389 // used by a policy mix of type MIX_TYPE_RECORDERS
3390 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003391 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003392 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003393 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003394 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003395 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3396 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003397 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003398 if (address != "") {
3399 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3400 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003401 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003402 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003403 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003404 } else if (status != NO_ERROR) {
3405 // Restore client activity state.
3406 inputDesc->setClientActive(client, false);
3407 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003408 }
3409
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003410 ALOGV("%s input %d source = %d status = %d exit",
3411 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003412
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003413 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003414}
3415
Eric Laurent8fc147b2018-07-22 19:13:55 -07003416status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003417{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003418 ALOGV("%s portId %d", __FUNCTION__, portId);
3419
3420 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3421 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003422 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003423 return BAD_VALUE;
3424 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003425 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003426 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003427 if (!client->active()) {
3428 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003429 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003430 }
Carter Hsue6139d52021-07-08 10:30:20 +08003431 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003432 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003433
Eric Laurent8f42ea12018-08-08 09:08:25 -07003434 inputDesc->stop();
3435 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003436 auto current_source = inputDesc->source();
3437 setInputDevice(input, getNewInputDevice(inputDesc),
3438 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003439 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003440 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003441 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003442 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003443 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3444 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003445 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003446 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003447
3448 // automatically disable the remote submix output when input is stopped if not
3449 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003450 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003451 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003452 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003453 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003454 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3455 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003456 }
3457 if (address != "") {
3458 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3459 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003460 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003461 }
3462 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003463 resetInputDevice(input);
3464
3465 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3466 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003467 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3468 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003469 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003470 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003471 }
3472 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003473 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003474 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003475}
3476
Eric Laurent8fc147b2018-07-22 19:13:55 -07003477void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003478{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003479 ALOGV("%s portId %d", __FUNCTION__, portId);
3480
3481 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3482 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003483 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003484 return;
3485 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003486 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003487 audio_io_handle_t input = inputDesc->mIoHandle;
3488
Eric Laurent8f42ea12018-08-08 09:08:25 -07003489 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003490
Andy Hung39efb7a2018-09-26 15:39:28 -07003491 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003492
3493 // If no more clients are present in this session, park effects to an orphan chain
3494 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3495 if (clientsOnSession.size() == 0) {
3496 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3497 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003498 if (inputDesc->getClientCount() > 0) {
3499 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003500 return;
3501 }
3502
Eric Laurent05b90f82014-08-27 15:32:29 -07003503 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003504 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003505 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003506}
3507
Eric Laurent8f42ea12018-08-08 09:08:25 -07003508void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003509{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003510 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003511
3512 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003513 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003514 }
3515}
3516
Eric Laurent8f42ea12018-08-08 09:08:25 -07003517void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3518{
3519 stopInput(portId);
3520 releaseInput(portId);
3521}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003522
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003523bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3524 if (input->clientsList().size() == 0
3525 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3526 return true;
3527 }
3528 for (const auto& client : input->clientsList()) {
3529 sp<DeviceDescriptor> device =
3530 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3531 client->session());
3532 if (!input->supportedDevices().contains(device)) {
3533 return true;
3534 }
3535 }
3536 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3537 return false;
3538}
3539
Eric Laurent0dd51852019-04-19 18:18:58 -07003540void AudioPolicyManager::checkCloseInputs() {
3541 // After connecting or disconnecting an input device, close input if:
3542 // - it has no client (was just opened to check profile) OR
3543 // - none of its supported devices are connected anymore OR
3544 // - one of its clients cannot be routed to one of its supported
3545 // devices anymore. Otherwise update device selection
3546 std::vector<audio_io_handle_t> inputsToClose;
3547 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003548 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003549 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003550 }
3551 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003552 for (const audio_io_handle_t handle : inputsToClose) {
3553 ALOGV("%s closing input %d", __func__, handle);
3554 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003555 }
Eric Laurentd4692962014-05-05 18:13:44 -07003556}
3557
Vlad Popa87e0e582024-05-20 18:49:20 -07003558status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3559 const char *address __unused,
3560 bool enabled,
3561 audio_stream_type_t streamToDriveAbs)
3562{
Vlad Popaa536eb32024-07-18 16:00:35 -07003563 if (!enabled) {
3564 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3565 return NO_ERROR;
3566 }
3567
Vlad Popa87e0e582024-05-20 18:49:20 -07003568 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3569 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3570 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3571 toString(streamToDriveAbs).c_str());
3572 return BAD_VALUE;
3573 }
3574
Vlad Popaa536eb32024-07-18 16:00:35 -07003575 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
Vlad Popa87e0e582024-05-20 18:49:20 -07003576 return NO_ERROR;
3577}
3578
François Gaffie251c7f02018-11-07 10:41:08 +01003579void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003580{
3581 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003582 if (indexMin < 0 || indexMax < 0) {
3583 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3584 return;
3585 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003586 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003587
3588 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003589 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3590 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003591 continue;
3592 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003593 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003594 }
Eric Laurente552edb2014-03-10 17:42:56 -07003595}
3596
Eric Laurente0720872014-03-11 09:30:41 -07003597status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003598 int index,
3599 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003600{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003601 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003602 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3603 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3604 return NO_ERROR;
3605 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303606 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3607 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003608 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003609}
3610
Eric Laurente0720872014-03-11 09:30:41 -07003611status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003612 int *index,
3613 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003614{
François Gaffiec005e562018-11-06 15:04:49 +01003615 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3616 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003617 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003618 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003619 deviceTypes = mEngine->getOutputDevicesForStream(
3620 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003621 }
jiabin9a3361e2019-10-01 09:38:30 -07003622 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003623}
3624
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003625status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003626 int index,
3627 audio_devices_t device)
3628{
3629 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003630 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3631 if (group == VOLUME_GROUP_NONE) {
3632 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003633 return BAD_VALUE;
3634 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003635 ALOGV("%s: group %d matching with %s index %d",
3636 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003637 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003638 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003639 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003640 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3641 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3642 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3643 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003644 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3645
3646 status = setVolumeCurveIndex(index, device, curves);
3647 if (status != NO_ERROR) {
3648 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3649 return status;
3650 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003651
jiabin9a3361e2019-10-01 09:38:30 -07003652 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003653 auto curCurvAttrs = curves.getAttributes();
3654 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3655 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003656 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003657 } else if (!curves.getStreamTypes().empty()) {
3658 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003659 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003660 } else {
3661 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3662 return BAD_VALUE;
3663 }
jiabin9a3361e2019-10-01 09:38:30 -07003664 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3665 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003666
François Gaffiecfe17322018-11-07 13:41:29 +01003667 // update volume on all outputs and streams matching the following:
3668 // - The requested stream (or a stream matching for volume control) is active on the output
3669 // - The device (or devices) selected by the engine for this stream includes
3670 // the requested device
3671 // - For non default requested device, currently selected device on the output is either the
3672 // requested device or one of the devices selected by the engine for this stream
3673 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3674 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003675 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003676 for (size_t i = 0; i < mOutputs.size(); i++) {
3677 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003678 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003679
jiabin9a3361e2019-10-01 09:38:30 -07003680 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3681 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003682 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003683
3684 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003685 continue;
3686 }
3687 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3688 curDevices.find(device) == curDevices.end()) {
3689 continue;
3690 }
3691 bool applyVolume = false;
3692 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3693 curSrcDevices.insert(device);
3694 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003695 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3696 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003697 } else {
3698 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3699 }
3700 if (!applyVolume) {
3701 continue; // next output
3702 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003703 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3704 // If a higher priority strategy is active, and the output is routed to a device with a
3705 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003706 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003707 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003708 // If the volume source is active with higher priority source, ensure at least Sw Muted
3709 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003710 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3711 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3712 false /*preferredDevice*/);
3713 if (activeClients.empty()) {
3714 continue;
3715 }
3716 bool isPreempted = false;
3717 bool isHigherPriority = productStrategy < strategy;
3718 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003719 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003720 ALOGV("%s: Strategy=%d (\nrequester:\n"
3721 " group %d, volumeGroup=%d attributes=%s)\n"
3722 " higher priority source active:\n"
3723 " volumeGroup=%d attributes=%s) \n"
3724 " on output %zu, bailing out", __func__, productStrategy,
3725 group, group, toString(attributes).c_str(),
3726 client->volumeSource(), toString(client->attributes()).c_str(), i);
3727 applyVolume = false;
3728 isPreempted = true;
3729 break;
3730 }
3731 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003732 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003733 applyVolume = true;
3734 }
3735 }
3736 if (isPreempted || applyVolume) {
3737 break;
3738 }
3739 }
3740 if (!applyVolume) {
3741 continue; // next output
3742 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003743 }
François Gaffieed91f582020-01-31 10:35:37 +01003744 //FIXME: workaround for truncated touch sounds
3745 // delayed volume change for system stream to be removed when the problem is
3746 // handled by system UI
3747 status_t volStatus = checkAndSetVolume(
3748 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003749 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003750 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3751 if (volStatus != NO_ERROR) {
3752 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003753 }
3754 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003755
3756 // update voice volume if the an active call route exists
3757 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3758 && (curSrcDevices.find(
3759 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3760 != curSrcDevices.end())) {
3761 bool isVoiceVolSrc;
3762 bool isBtScoVolSrc;
3763 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3764 isVoiceVolSrc, isBtScoVolSrc, __func__)
3765 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003766 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3767 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3768 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003769 }
3770 }
3771
François Gaffiecfe17322018-11-07 13:41:29 +01003772 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3773 return status;
3774}
3775
François Gaffieaaac0fd2018-11-22 17:56:39 +01003776status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003777 audio_devices_t device,
3778 IVolumeCurves &volumeCurves)
3779{
3780 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3781 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003782 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3783 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003784 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303785 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3786 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003787 return BAD_VALUE;
3788 }
3789 if (!audio_is_output_device(device)) {
3790 return BAD_VALUE;
3791 }
3792
3793 // Force max volume if stream cannot be muted
3794 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3795
François Gaffieaaac0fd2018-11-22 17:56:39 +01003796 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003797 volumeCurves.addCurrentVolumeIndex(device, index);
3798 return NO_ERROR;
3799}
3800
3801status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3802 int &index,
3803 audio_devices_t device)
3804{
3805 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3806 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003807 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003808 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003809 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003810 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003811 }
jiabin9a3361e2019-10-01 09:38:30 -07003812 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003813}
3814
3815status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3816 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003817 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003818{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003819 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003820 return BAD_VALUE;
3821 }
jiabin9a3361e2019-10-01 09:38:30 -07003822 index = curves.getVolumeIndex(deviceTypes);
3823 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003824 return NO_ERROR;
3825}
3826
3827status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3828 int &index)
3829{
3830 index = getVolumeCurves(attr).getVolumeIndexMin();
3831 return NO_ERROR;
3832}
3833
3834status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3835 int &index)
3836{
3837 index = getVolumeCurves(attr).getVolumeIndexMax();
3838 return NO_ERROR;
3839}
3840
Eric Laurent36829f92017-04-07 19:04:42 -07003841audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003842{
3843 // select one output among several suitable for global effects.
3844 // The priority is as follows:
3845 // 1: An offloaded output. If the effect ends up not being offloadable,
3846 // AudioFlinger will invalidate the track and the offloaded output
3847 // will be closed causing the effect to be moved to a PCM output.
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003848 // 2: Spatializer output if the stereo spatializer feature enabled
3849 // 3: A deep buffer output
3850 // 4: The primary output
3851 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003852
François Gaffiec005e562018-11-06 15:04:49 +01003853 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3854 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003855 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003856
Eric Laurent36829f92017-04-07 19:04:42 -07003857 if (outputs.size() == 0) {
3858 return AUDIO_IO_HANDLE_NONE;
3859 }
Eric Laurente552edb2014-03-10 17:42:56 -07003860
Eric Laurent36829f92017-04-07 19:04:42 -07003861 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3862 bool activeOnly = true;
3863
3864 while (output == AUDIO_IO_HANDLE_NONE) {
3865 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003866 audio_io_handle_t outputSpatializer = AUDIO_IO_HANDLE_NONE;
Eric Laurent36829f92017-04-07 19:04:42 -07003867 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3868 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3869
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003870 for (audio_io_handle_t outputLoop : outputs) {
3871 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputLoop);
Eric Laurent83d17c22019-04-02 17:10:01 -07003872 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003873 continue;
3874 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003875 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003876 activeOnly, outputLoop, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003877 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003878 outputOffloaded = outputLoop;
3879 }
3880 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
3881 if (SpatializerHelper::isStereoSpatializationFeatureEnabled()) {
3882 outputSpatializer = outputLoop;
3883 }
Eric Laurent36829f92017-04-07 19:04:42 -07003884 }
3885 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003886 outputDeepBuffer = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003887 }
3888 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003889 outputPrimary = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003890 }
3891 }
3892 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3893 output = outputOffloaded;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003894 } else if (outputSpatializer != AUDIO_IO_HANDLE_NONE) {
3895 output = outputSpatializer;
Eric Laurent36829f92017-04-07 19:04:42 -07003896 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3897 output = outputDeepBuffer;
3898 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3899 output = outputPrimary;
3900 } else {
3901 output = outputs[0];
3902 }
3903 activeOnly = false;
3904 }
3905
3906 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003907 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3908 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003909 mMusicEffectOutput = output;
3910 }
3911
3912 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003913 return output;
3914}
3915
Eric Laurent36829f92017-04-07 19:04:42 -07003916audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3917{
3918 return selectOutputForMusicEffects();
3919}
3920
Eric Laurente0720872014-03-11 09:30:41 -07003921status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003922 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003923 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003924 int session,
3925 int id)
3926{
Shunkai Yao29d10572024-03-19 04:31:47 +00003927 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003928 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003929 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003930 index = mInputs.indexOfKey(io);
3931 if (index < 0) {
3932 ALOGW("registerEffect() unknown io %d", io);
3933 return INVALID_OPERATION;
3934 }
Eric Laurente552edb2014-03-10 17:42:56 -07003935 }
3936 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003937 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3938 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3939 || strategy == PRODUCT_STRATEGY_NONE));
3940 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003941}
3942
Eric Laurentc241b0d2018-11-28 09:08:49 -08003943status_t AudioPolicyManager::unregisterEffect(int id)
3944{
3945 if (mEffects.getEffect(id) == nullptr) {
3946 return INVALID_OPERATION;
3947 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003948 if (mEffects.isEffectEnabled(id)) {
3949 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3950 setEffectEnabled(id, false);
3951 }
3952 return mEffects.unregisterEffect(id);
3953}
3954
3955status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3956{
3957 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3958 if (effect == nullptr) {
3959 return INVALID_OPERATION;
3960 }
3961
3962 status_t status = mEffects.setEffectEnabled(id, enabled);
3963 if (status == NO_ERROR) {
3964 mInputs.trackEffectEnabled(effect, enabled);
3965 }
3966 return status;
3967}
3968
Eric Laurent6c796322019-04-09 14:13:17 -07003969
3970status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3971{
3972 mEffects.moveEffects(ids, io);
3973 return NO_ERROR;
3974}
3975
Eric Laurentc75307b2015-03-17 15:29:32 -07003976bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3977{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003978 auto vs = toVolumeSource(stream, false);
3979 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003980}
3981
3982bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3983{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003984 auto vs = toVolumeSource(stream, false);
3985 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003986}
3987
Eric Laurente0720872014-03-11 09:30:41 -07003988bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003989{
3990 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003991 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003992 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003993 return true;
3994 }
3995 }
3996 return false;
3997}
3998
Eric Laurent275e8e92014-11-30 15:14:47 -08003999// Register a list of custom mixes with their attributes and format.
4000// When a mix is registered, corresponding input and output profiles are
4001// added to the remote submix hw module. The profile contains only the
4002// parameters (sampling rate, format...) specified by the mix.
4003// The corresponding input remote submix device is also connected.
4004//
4005// When a remote submix device is connected, the address is checked to select the
4006// appropriate profile and the corresponding input or output stream is opened.
4007//
4008// When capture starts, getInputForAttr() will:
4009// - 1 look for a mix matching the address passed in attribtutes tags if any
4010// - 2 if none found, getDeviceForInputSource() will:
4011// - 2.1 look for a mix matching the attributes source
4012// - 2.2 if none found, default to device selection by policy rules
4013// At this time, the corresponding output remote submix device is also connected
4014// and active playback use cases can be transferred to this mix if needed when reconnecting
4015// after AudioTracks are invalidated
4016//
4017// When playback starts, getOutputForAttr() will:
4018// - 1 look for a mix matching the address passed in attribtutes tags if any
4019// - 2 if none found, look for a mix matching the attributes usage
4020// - 3 if none found, default to device and output selection by policy rules.
4021
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004022status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08004023{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004024 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
4025 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004026 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004027 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01004028 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004029 // examine each mix's route type
4030 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004031 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08004032 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
4033 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
4034 ALOGE("Unsupported Policy Mix %zu of %zu: "
4035 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
4036 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004037 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08004038 break;
4039 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08004040 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
4041 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07004042 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004043 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
4044 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004045 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004046 rSubmixModule = mHwModules.getModuleFromName(
4047 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4048 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004049 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08004050 i);
4051 res = INVALID_OPERATION;
4052 break;
4053 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004054 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004055
Eric Laurent97ac8712018-07-27 18:59:02 -07004056 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004057 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004058 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004059 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004060 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4061 } else {
4062 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4063 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004064 }
François Gaffie036e1e92015-03-19 10:16:24 +01004065
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004066 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004067 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004068 res = INVALID_OPERATION;
4069 break;
4070 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004071 audio_config_t outputConfig = mix.mFormat;
4072 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004073 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4074 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004075 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4076 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004077 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004078 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4079 audio_is_linear_pcm(outputConfig.format)
4080 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004081 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004082 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4083 audio_is_linear_pcm(inputConfig.format)
4084 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004085
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004086 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004087 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004088 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004089 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004090 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004091 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004092 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004093 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4094 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004095 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004096 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004097 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004098
4099 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4100 mix.mDeviceType, mix.mDeviceAddress,
4101 String8(), AUDIO_FORMAT_DEFAULT);
4102 if (device == nullptr) {
4103 res = INVALID_OPERATION;
4104 break;
4105 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004106
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004107 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004108 // First try to find an already opened output supporting the device
4109 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004110 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004111
Eric Laurentc529cf62020-04-17 18:19:10 -07004112 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004113 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004114 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004115 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004116 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004117 } else {
4118 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004119 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004120 }
4121 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004122 // If no output found, try to find a direct output profile supporting the device
4123 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4124 sp<HwModule> module = mHwModules[i];
4125 for (size_t j = 0;
4126 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4127 j++) {
4128 sp<IOProfile> profile = module->getOutputProfiles()[j];
4129 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4130 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4131 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004132 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004133 res = INVALID_OPERATION;
4134 } else {
4135 foundOutput = true;
4136 }
4137 }
4138 }
4139 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004140 if (res != NO_ERROR) {
4141 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004142 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004143 res = INVALID_OPERATION;
4144 break;
4145 } else if (!foundOutput) {
4146 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004147 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004148 res = INVALID_OPERATION;
4149 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004150 } else {
4151 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004152 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004153 }
Eric Laurentc722f302014-12-10 11:21:49 -08004154 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004155 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004156 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004157 if (audio_flags::audio_mix_ownership()) {
4158 // Only unregister mixes that were actually registered to not accidentally unregister
4159 // mixes that already existed previously.
4160 unregisterPolicyMixes(registeredMixes);
4161 registeredMixes.clear();
4162 } else {
4163 unregisterPolicyMixes(mixes);
4164 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004165 } else if (checkOutputs) {
4166 checkForDeviceAndOutputChanges();
4167 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004168 }
4169 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004170}
4171
4172status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4173{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004174 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004175 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004176 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004177 sp<HwModule> rSubmixModule;
4178 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004179 for (const auto& mix : mixes) {
4180 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004181
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004182 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004183 rSubmixModule = mHwModules.getModuleFromName(
4184 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4185 if (rSubmixModule == 0) {
4186 res = INVALID_OPERATION;
4187 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004188 }
4189 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004190
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004191 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004192
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004193 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004194 res = INVALID_OPERATION;
4195 continue;
4196 }
4197
Marvin Ramin0783e202024-03-05 12:45:50 +01004198 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004199 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004200 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4201 status_t currentRes =
4202 setDeviceConnectionStateInt(device,
4203 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4204 address.c_str(),
4205 "remote-submix",
4206 AUDIO_FORMAT_DEFAULT);
4207 if (!audio_flags::audio_mix_ownership()) {
4208 res = currentRes;
4209 }
4210 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004211 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004212 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004213 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004214 }
4215 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004216 }
jiabin5740f082019-08-19 15:08:30 -07004217 rSubmixModule->removeOutputProfile(address.c_str());
4218 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004219
Kevin Rocard153f92d2018-12-18 18:33:28 -08004220 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004221 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004222 res = INVALID_OPERATION;
4223 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004224 } else {
4225 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004226 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004227 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004228 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004229
4230 if (res == NO_ERROR && checkOutputs) {
4231 checkForDeviceAndOutputChanges();
4232 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004233 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004234 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004235}
4236
Marvin Raminbdefaf02023-11-01 09:10:32 +01004237status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4238 if (!audio_flags::audio_mix_test_api()) {
4239 return INVALID_OPERATION;
4240 }
4241
4242 _aidl_return.clear();
4243 _aidl_return.reserve(mPolicyMixes.size());
4244 for (const auto &policyMix: mPolicyMixes) {
4245 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4246 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4247 policyMix->mCbFlags);
4248 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004249 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004250 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004251 }
4252
Vlad Popaa5d73f32024-03-08 16:05:38 -08004253 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004254 return OK;
4255}
4256
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004257status_t AudioPolicyManager::updatePolicyMix(
4258 const AudioMix& mix,
4259 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4260 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4261 if (res == NO_ERROR) {
4262 checkForDeviceAndOutputChanges();
4263 updateCallAndOutputRouting();
4264 }
4265 return res;
4266}
4267
Mikhail Naganov100f0122018-11-29 11:22:16 -08004268void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4269{
4270 size_t i = 0;
4271 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4272 for (const auto& fmt : mManualSurroundFormats) {
4273 if (i++ != 0) dst->append(", ");
4274 std::string sfmt;
4275 FormatConverter::toString(fmt, sfmt);
4276 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4277 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4278 }
4279}
4280
Eric Laurentc529cf62020-04-17 18:19:10 -07004281// Returns true if all devices types match the predicate and are supported by one HW module
4282bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004283 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004284 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004285 const char *context,
4286 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004287 for (size_t i = 0; i < devices.size(); i++) {
4288 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004289 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004290 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004291 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004292 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004293 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004294 return false;
4295 }
4296 }
4297 return true;
4298}
4299
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004300void AudioPolicyManager::changeOutputDevicesMuteState(
4301 const AudioDeviceTypeAddrVector& devices) {
4302 ALOGVV("%s() num devices %zu", __func__, devices.size());
4303
4304 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4305 getSoftwareOutputsForDevices(devices);
4306
4307 for (size_t i = 0; i < outputs.size(); i++) {
4308 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4309 DeviceVector prevDevices = outputDesc->devices();
4310 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4311 }
4312}
4313
4314std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4315 const AudioDeviceTypeAddrVector& devices) const
4316{
4317 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4318 DeviceVector deviceDescriptors;
4319 for (size_t j = 0; j < devices.size(); j++) {
4320 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4321 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4322 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4323 ALOGE("%s: device type %#x address %s not supported or not an output device",
4324 __func__, devices[j].mType, devices[j].getAddress());
4325 continue;
4326 }
4327 deviceDescriptors.add(desc);
4328 }
4329 for (size_t i = 0; i < mOutputs.size(); i++) {
4330 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4331 continue;
4332 }
4333 outputs.push_back(mOutputs.valueAt(i));
4334 }
4335 return outputs;
4336}
4337
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004338status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004339 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004340 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004341 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4342 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004343 }
4344 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004345 if (res != NO_ERROR) {
4346 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4347 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004348 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004349
4350 checkForDeviceAndOutputChanges();
4351 updateCallAndOutputRouting();
4352
4353 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004354}
4355
4356status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4357 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004358 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4359 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004360 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004361 __FUNCTION__, uid);
4362 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004363 }
4364
Eric Laurentc529cf62020-04-17 18:19:10 -07004365 checkForDeviceAndOutputChanges();
4366 updateCallAndOutputRouting();
4367
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004368 return res;
4369}
4370
Eric Laurent2517af32020-11-25 15:31:27 +01004371
jiabin0a488932020-08-07 17:32:40 -07004372status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4373 device_role_t role,
4374 const AudioDeviceTypeAddrVector &devices) {
4375 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4376 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004377
Eric Laurentc529cf62020-04-17 18:19:10 -07004378 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004379 return BAD_VALUE;
4380 }
jiabin0a488932020-08-07 17:32:40 -07004381 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004382 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004383 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4384 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004385 return status;
4386 }
4387
4388 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004389
4390 bool forceVolumeReeval = false;
4391 // FIXME: workaround for truncated touch sounds
4392 // to be removed when the problem is handled by system UI
4393 uint32_t delayMs = 0;
4394 if (strategy == mCommunnicationStrategy) {
4395 forceVolumeReeval = true;
4396 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4397 updateInputRouting();
4398 }
4399 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004400
4401 return NO_ERROR;
4402}
4403
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004404void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4405 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004406{
4407 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004408 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004409 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004410 // Only apply special touch sound delay once
4411 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004412 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004413 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004414 for (size_t i = 0; i < mOutputs.size(); i++) {
4415 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4416 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004417 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4418 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004419 // As done in setDeviceConnectionState, we could also fix default device issue by
4420 // preventing the force re-routing in case of default dev that distinguishes on address.
4421 // Let's give back to engine full device choice decision however.
jiabin2361ed82024-09-20 17:36:31 +00004422 bool newDevicesNotEmpty = !newDevices.isEmpty();
4423 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()
4424 && newDevicesNotEmpty) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004425 // If the device is using preferred mixer attributes, the output need to reopen
4426 // with default configuration when the new selected devices are different from
4427 // current routing devices.
4428 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4429 continue;
4430 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304431
jiabin2361ed82024-09-20 17:36:31 +00004432 waitMs = setOutputDevices(__func__, outputDesc, newDevices,
4433 newDevicesNotEmpty /*force*/, delayMs,
4434 nullptr /*patchHandle*/, !skipDelays /*requiresMuteCheck*/,
4435 !newDevicesNotEmpty /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004436 // Only apply special touch sound delay once
4437 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004438 }
4439 if (forceVolumeReeval && !newDevices.isEmpty()) {
4440 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4441 }
4442 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004443 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004444 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004445}
4446
Eric Laurent2517af32020-11-25 15:31:27 +01004447void AudioPolicyManager::updateInputRouting() {
4448 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304449 // Skip for hotword recording as the input device switch
4450 // is handled within sound trigger HAL
4451 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4452 continue;
4453 }
Eric Laurent2517af32020-11-25 15:31:27 +01004454 auto newDevice = getNewInputDevice(activeDesc);
4455 // Force new input selection if the new device can not be reached via current input
4456 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4457 setInputDevice(activeDesc->mIoHandle, newDevice);
4458 } else {
4459 closeInput(activeDesc->mIoHandle);
4460 }
4461 }
4462}
4463
Paul Wang5d7cdb52022-11-22 09:45:06 +00004464status_t
4465AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4466 device_role_t role,
4467 const AudioDeviceTypeAddrVector &devices) {
4468 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4469 dumpAudioDeviceTypeAddrVector(devices).c_str());
4470
Eric Laurent78fedbf2023-03-09 14:40:44 +01004471 if (!areAllDevicesSupported(
4472 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004473 return BAD_VALUE;
4474 }
4475 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4476 if (status != NO_ERROR) {
4477 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4478 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4479 return status;
4480 }
4481
4482 checkForDeviceAndOutputChanges();
4483
4484 bool forceVolumeReeval = false;
4485 // TODO(b/263479999): workaround for truncated touch sounds
4486 // to be removed when the problem is handled by system UI
4487 uint32_t delayMs = 0;
4488 if (strategy == mCommunnicationStrategy) {
4489 forceVolumeReeval = true;
4490 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4491 updateInputRouting();
4492 }
4493 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4494
4495 return NO_ERROR;
4496}
4497
4498status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4499 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004500{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004501 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004502
Paul Wang5d7cdb52022-11-22 09:45:06 +00004503 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004504 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004505 ALOGW_IF(status != NAME_NOT_FOUND,
4506 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004507 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004508 return status;
4509 }
4510
4511 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004512
4513 bool forceVolumeReeval = false;
4514 // FIXME: workaround for truncated touch sounds
4515 // to be removed when the problem is handled by system UI
4516 uint32_t delayMs = 0;
4517 if (strategy == mCommunnicationStrategy) {
4518 forceVolumeReeval = true;
4519 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4520 updateInputRouting();
4521 }
4522 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004523
4524 return NO_ERROR;
4525}
4526
jiabin0a488932020-08-07 17:32:40 -07004527status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4528 device_role_t role,
4529 AudioDeviceTypeAddrVector &devices) {
4530 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004531}
4532
Jiabin Huang3b98d322020-09-03 17:54:16 +00004533status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4534 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4535 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4536 dumpAudioDeviceTypeAddrVector(devices).c_str());
4537
Mikhail Naganov55773032020-10-01 15:08:13 -07004538 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004539 return BAD_VALUE;
4540 }
4541 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4542 ALOGW_IF(status != NO_ERROR,
4543 "Engine could not set preferred devices %s for audio source %d role %d",
4544 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4545
Wenyu Zhang47655d22024-10-01 12:24:53 +00004546 if (status == NO_ERROR) {
4547 updateInputRouting();
4548 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004549 return status;
4550}
4551
4552status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4553 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4554 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4555 dumpAudioDeviceTypeAddrVector(devices).c_str());
4556
Mikhail Naganov55773032020-10-01 15:08:13 -07004557 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004558 return BAD_VALUE;
4559 }
4560 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4561 ALOGW_IF(status != NO_ERROR,
4562 "Engine could not add preferred devices %s for audio source %d role %d",
4563 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4564
Eric Laurent2517af32020-11-25 15:31:27 +01004565 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004566 return status;
4567}
4568
4569status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4570 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4571{
4572 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4573 dumpAudioDeviceTypeAddrVector(devices).c_str());
4574
Eric Laurent78fedbf2023-03-09 14:40:44 +01004575 if (!areAllDevicesSupported(
4576 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004577 return BAD_VALUE;
4578 }
4579
4580 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4581 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004582 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004583 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004584 if (status == NO_ERROR) {
4585 updateInputRouting();
4586 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004587 return status;
4588}
4589
4590status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4591 device_role_t role) {
4592 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4593
4594 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004595 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004596 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004597 if (status == NO_ERROR) {
4598 updateInputRouting();
4599 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004600 return status;
4601}
4602
4603status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4604 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4605 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4606}
4607
Oscar Azucena90e77632019-11-27 17:12:28 -08004608status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004609 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004610 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004611 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4612 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004613 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004614 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4615 if (status != NO_ERROR) {
4616 ALOGE("%s() could not set device affinity for userId %d",
4617 __FUNCTION__, userId);
4618 return status;
4619 }
4620
4621 // reevaluate outputs for all devices
4622 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004623 changeOutputDevicesMuteState(devices);
4624 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4625 true /* skipDelays */);
4626 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004627
4628 return NO_ERROR;
4629}
4630
4631status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004632 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004633 AudioDeviceTypeAddrVector devices;
4634 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004635 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4636 if (status != NO_ERROR) {
4637 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4638 __FUNCTION__, userId);
4639 return status;
4640 }
4641
4642 // reevaluate outputs for all devices
4643 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004644 changeOutputDevicesMuteState(devices);
4645 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4646 true /* skipDelays */);
4647 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004648
4649 return NO_ERROR;
4650}
4651
Andy Hungc29d82b2018-10-05 12:23:17 -07004652void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004653{
Andy Hungc29d82b2018-10-05 12:23:17 -07004654 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004655 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004656 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004657 std::string stateLiteral;
4658 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004659 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004660 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4661 "communications", "media", "record", "dock", "system",
4662 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4663 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4664 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004665 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4666 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4667 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4668 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4669 dst->append(" (MANUAL: ");
4670 dumpManualSurroundFormats(dst);
4671 dst->append(")");
4672 }
4673 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004674 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004675 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4676 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004677 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004678 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004679
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004680 dst->append("\n");
4681 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4682 dst->append("\n");
4683 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004684 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004685 mOutputs.dump(dst);
4686 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004687 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004688 mAudioPatches.dump(dst);
4689 mPolicyMixes.dump(dst);
4690 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004691
Kevin Rocardb99cc752019-03-21 20:52:24 -07004692 dst->appendFormat(" AllowedCapturePolicies:\n");
4693 for (auto& policy : mAllowedCapturePolicies) {
4694 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4695 }
4696
jiabina84c3d32022-12-02 18:59:55 +00004697 dst->appendFormat(" Preferred mixer audio configuration:\n");
4698 for (const auto it : mPreferredMixerAttrInfos) {
4699 dst->appendFormat(" - device port id: %d\n", it.first);
4700 for (const auto preferredMixerInfoIt : it.second) {
4701 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4702 preferredMixerInfoIt.second->dump(dst);
4703 }
4704 }
4705
François Gaffiec005e562018-11-06 15:04:49 +01004706 dst->appendFormat("\nPolicy Engine dump:\n");
4707 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004708
4709 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4710 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4711 dst->appendFormat(" - device type: %s, driving stream %d\n",
4712 dumpDeviceTypes({it.first}).c_str(),
4713 mEngine->getVolumeGroupForAttributes(it.second));
4714 }
jiabin7ed22ff2024-10-04 20:51:21 +00004715
4716 // dump mmap policy by device
4717 dst->appendFormat("\nMmap policy:\n");
4718 for (const auto& [policyType, policyByDevice] : mMmapPolicyByDeviceType) {
4719 std::stringstream ss;
4720 ss << '{';
4721 for (const auto& [deviceType, policy] : policyByDevice) {
4722 ss << deviceType.toString() << ":" << toString(policy) << " ";
4723 }
4724 ss << '}';
4725 dst->appendFormat(" - %s: %s\n", toString(policyType).c_str(), ss.str().c_str());
4726 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004727}
4728
4729status_t AudioPolicyManager::dump(int fd)
4730{
4731 String8 result;
4732 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004733 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004734 return NO_ERROR;
4735}
4736
Kevin Rocardb99cc752019-03-21 20:52:24 -07004737status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4738{
4739 mAllowedCapturePolicies[uid] = capturePolicy;
4740 return NO_ERROR;
4741}
4742
Eric Laurente552edb2014-03-10 17:42:56 -07004743// This function checks for the parameters which can be offloaded.
4744// This can be enhanced depending on the capability of the DSP and policy
4745// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004746audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004747{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004748 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004749 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004750 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004751 offloadInfo.format,
4752 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4753 offloadInfo.has_video);
4754
jiabin2b9d5a12021-12-10 01:06:29 +00004755 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004756 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004757 }
4758
4759 // See if there is a profile to support this.
4760 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004761 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004762 offloadInfo.sample_rate,
4763 offloadInfo.format,
4764 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004765 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4766 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004767 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4768 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4769 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004770 if (profile == nullptr) {
4771 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4772 }
4773 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4774 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4775 }
4776 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004777}
4778
Michael Chana94fbb22018-04-24 14:31:19 +10004779bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4780 const audio_attributes_t& attributes) {
4781 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004782 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004783 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4784 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004785 config.sample_rate,
4786 config.format,
4787 config.channel_mask,
4788 output_flags,
4789 true /* directOnly */);
4790 ALOGV("%s() profile %sfound with name: %s, "
4791 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4792 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004793 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004794 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004795
4796 // also try the MSD module if compatible profile not found
4797 if (profile == nullptr) {
4798 profile = getMsdProfileForOutput(outputDevices,
4799 config.sample_rate,
4800 config.format,
4801 config.channel_mask,
4802 output_flags,
4803 true /* directOnly */);
4804 ALOGV("%s() MSD profile %sfound with name: %s, "
4805 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4806 __FUNCTION__, profile != 0 ? "" : "NOT ",
4807 (profile != 0 ? profile->getTagName().c_str() : "null"),
4808 config.sample_rate, config.format, config.channel_mask, output_flags);
4809 }
4810 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004811}
4812
jiabin2b9d5a12021-12-10 01:06:29 +00004813bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4814 bool durationIgnored) {
4815 if (mMasterMono) {
4816 return false; // no offloading if mono is set.
4817 }
4818
4819 // Check if offload has been disabled
4820 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4821 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4822 return false;
4823 }
4824
4825 // Check if stream type is music, then only allow offload as of now.
4826 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4827 {
4828 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4829 return false;
4830 }
4831
4832 //TODO: enable audio offloading with video when ready
4833 const bool allowOffloadWithVideo =
4834 property_get_bool("audio.offload.video", false /* default_value */);
4835 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4836 ALOGV("%s: has_video == true, returning false", __func__);
4837 return false;
4838 }
4839
4840 //If duration is less than minimum value defined in property, return false
4841 const int min_duration_secs = property_get_int32(
4842 "audio.offload.min.duration.secs", -1 /* default_value */);
4843 if (!durationIgnored) {
4844 if (min_duration_secs >= 0) {
4845 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4846 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4847 __func__, min_duration_secs);
4848 return false;
4849 }
4850 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4851 ALOGV("%s: Offload denied by duration < default min(=%u)",
4852 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4853 return false;
4854 }
4855 }
4856
4857 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4858 // creating an offloaded track and tearing it down immediately after start when audioflinger
4859 // detects there is an active non offloadable effect.
4860 // FIXME: We should check the audio session here but we do not have it in this context.
4861 // This may prevent offloading in rare situations where effects are left active by apps
4862 // in the background.
4863 if (mEffects.isNonOffloadableEffectEnabled()) {
4864 return false;
4865 }
4866
4867 return true;
4868}
4869
4870audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4871 const audio_config_t *config) {
4872 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4873 offloadInfo.format = config->format;
4874 offloadInfo.sample_rate = config->sample_rate;
4875 offloadInfo.channel_mask = config->channel_mask;
4876 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4877 offloadInfo.has_video = false;
4878 offloadInfo.is_streaming = false;
4879 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4880
4881 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4882 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4883 audio_flags_to_audio_output_flags(attr->flags, &flags);
4884 // only retain flags that will drive compressed offload or passthrough
4885 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4886 if (offloadPossible) {
4887 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4888 }
4889 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4890
Dorin Drimusfae3c642022-03-17 18:36:30 +01004891 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin8a096672024-09-18 18:20:24 +00004892 if (std::any_of(engineOutputDevices.begin(), engineOutputDevices.end(),
4893 [this, attr](sp<DeviceDescriptor> device) {
4894 return getPreferredMixerAttributesInfo(
4895 device->getId(),
4896 mEngine->getProductStrategyForAttributes(*attr),
4897 true /*activeBitPerfectPreferred*/) != nullptr;
4898 })) {
4899 // Bit-perfect playback is active on one of the selected devices, direct output will
4900 // be rejected at this instant.
4901 return AUDIO_DIRECT_NOT_SUPPORTED;
4902 }
jiabin2b9d5a12021-12-10 01:06:29 +00004903 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004904 DeviceVector outputDevices = engineOutputDevices;
4905 // the MSD module checks for different conditions and output devices
4906 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4907 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4908 continue;
4909 }
4910 outputDevices = getMsdAudioOutDevices();
4911 }
jiabin2b9d5a12021-12-10 01:06:29 +00004912 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004913 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004914 config->sample_rate, nullptr /*updatedSamplingRate*/,
4915 config->format, nullptr /*updatedFormat*/,
4916 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004917 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004918 continue;
4919 }
4920 // reject profiles not corresponding to a device currently available
4921 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4922 continue;
4923 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004924 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4925 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004926 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004927 != AUDIO_DIRECT_NOT_SUPPORTED) {
4928 // Already reports offload gapless supported. No need to report offload support.
4929 continue;
4930 }
4931 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4932 != AUDIO_OUTPUT_FLAG_NONE) {
4933 // If offload gapless is reported, no need to report offload support.
4934 directMode = (audio_direct_mode_t) ((directMode &
4935 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4936 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4937 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004938 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004939 }
4940 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004941 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004942 }
4943 }
4944 }
4945 return directMode;
4946}
4947
Dorin Drimusf2196d82022-01-03 12:11:18 +01004948status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4949 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004950 if (mEffects.isNonOffloadableEffectEnabled()) {
4951 return OK;
4952 }
jiabinf1c73972022-04-14 16:28:52 -07004953 DeviceVector devices;
4954 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004955 if (status != OK) {
4956 return status;
4957 }
4958 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4959 if (devices.empty()) {
4960 return OK; // no output devices for the attributes
4961 }
jiabinf1c73972022-04-14 16:28:52 -07004962 return getProfilesForDevices(devices, audioProfilesVector,
4963 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004964}
4965
jiabina84c3d32022-12-02 18:59:55 +00004966status_t AudioPolicyManager::getSupportedMixerAttributes(
4967 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4968 ALOGV("%s, portId=%d", __func__, portId);
4969 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4970 if (deviceDescriptor == nullptr) {
4971 ALOGE("%s the requested device is currently unavailable", __func__);
4972 return BAD_VALUE;
4973 }
jiabin96daffc2023-05-11 17:51:55 +00004974 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4975 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4976 deviceDescriptor->type());
4977 return BAD_VALUE;
4978 }
jiabina84c3d32022-12-02 18:59:55 +00004979 for (const auto& hwModule : mHwModules) {
4980 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4981 if (curProfile->supportsDevice(deviceDescriptor)) {
4982 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4983 }
4984 }
4985 }
4986 return NO_ERROR;
4987}
4988
4989status_t AudioPolicyManager::setPreferredMixerAttributes(
4990 const audio_attributes_t *attr,
4991 audio_port_handle_t portId,
4992 uid_t uid,
4993 const audio_mixer_attributes_t *mixerAttributes) {
4994 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4995 "mixerBehavior=%d}, uid=%d, portId=%u",
4996 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4997 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4998 mixerAttributes->mixer_behavior, uid, portId);
4999 if (attr->usage != AUDIO_USAGE_MEDIA) {
5000 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
5001 return BAD_VALUE;
5002 }
5003 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5004 if (deviceDescriptor == nullptr) {
5005 ALOGE("%s the requested device is currently unavailable", __func__);
5006 return BAD_VALUE;
5007 }
5008 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5009 ALOGE("%s(%d), type=%d, is not a usb output device",
5010 __func__, portId, deviceDescriptor->type());
5011 return BAD_VALUE;
5012 }
5013
5014 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5015 audio_flags_to_audio_output_flags(attr->flags, &flags);
5016 flags = (audio_output_flags_t) (flags |
5017 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
5018 sp<IOProfile> profile = nullptr;
5019 DeviceVector devices(deviceDescriptor);
5020 for (const auto& hwModule : mHwModules) {
5021 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5022 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00005023 && curProfile->getCompatibilityScore(
5024 devices,
5025 mixerAttributes->config.sample_rate,
5026 nullptr /*updatedSamplingRate*/,
5027 mixerAttributes->config.format,
5028 nullptr /*updatedFormat*/,
5029 mixerAttributes->config.channel_mask,
5030 nullptr /*updatedChannelMask*/,
5031 flags,
5032 false /*exactMatchRequiredForInputFlags*/)
5033 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00005034 profile = curProfile;
5035 break;
5036 }
5037 }
5038 }
5039 if (profile == nullptr) {
5040 ALOGE("%s, there is no compatible profile found", __func__);
5041 return BAD_VALUE;
5042 }
5043
5044 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
5045 sp<PreferredMixerAttributesInfo>::make(
5046 uid, portId, profile, flags, *mixerAttributes);
5047 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5048 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
5049
5050 // If 1) there is any client from the preferred mixer configuration owner that is currently
5051 // active and matches the strategy and 2) current output is on the preferred device and the
5052 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
5053 // configuration.
5054 std::vector<audio_io_handle_t> outputsToReopen;
5055 for (size_t i = 0; i < mOutputs.size(); i++) {
5056 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00005057 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
5058 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00005059 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00005060 } else {
5061 for (const auto &client: output->getActiveClients()) {
5062 if (client->uid() == uid && client->strategy() == strategy) {
5063 client->setIsInvalid();
5064 outputsToReopen.push_back(output->mIoHandle);
5065 }
jiabina84c3d32022-12-02 18:59:55 +00005066 }
5067 }
5068 }
5069 }
5070 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5071 config.sample_rate = mixerAttributes->config.sample_rate;
5072 config.channel_mask = mixerAttributes->config.channel_mask;
5073 config.format = mixerAttributes->config.format;
5074 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005075 sp<SwAudioOutputDescriptor> desc =
5076 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5077 if (desc == nullptr) {
5078 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5079 continue;
5080 }
jiabin220eea12024-05-17 17:55:20 +00005081 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005082 }
5083
5084 return NO_ERROR;
5085}
5086
5087sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005088 audio_port_handle_t devicePortId,
5089 product_strategy_t strategy,
5090 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005091 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5092 if (it == mPreferredMixerAttrInfos.end()) {
5093 return nullptr;
5094 }
jiabind9a58d32023-06-01 17:57:30 +00005095 if (activeBitPerfectPreferred) {
5096 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005097 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005098 return info;
5099 }
5100 }
jiabina84c3d32022-12-02 18:59:55 +00005101 }
jiabind9a58d32023-06-01 17:57:30 +00005102 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5103 return strategyMatchedMixerAttrInfoIt == it->second.end()
5104 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005105}
5106
5107status_t AudioPolicyManager::getPreferredMixerAttributes(
5108 const audio_attributes_t *attr,
5109 audio_port_handle_t portId,
5110 audio_mixer_attributes_t* mixerAttributes) {
5111 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5112 portId, mEngine->getProductStrategyForAttributes(*attr));
5113 if (info == nullptr) {
5114 return NAME_NOT_FOUND;
5115 }
5116 *mixerAttributes = info->getMixerAttributes();
5117 return NO_ERROR;
5118}
5119
5120status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5121 audio_port_handle_t portId,
5122 uid_t uid) {
5123 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5124 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5125 if (preferredMixerAttrInfo == nullptr) {
5126 return NAME_NOT_FOUND;
5127 }
5128 if (preferredMixerAttrInfo->getUid() != uid) {
5129 ALOGE("%s, requested uid=%d, owned uid=%d",
5130 __func__, uid, preferredMixerAttrInfo->getUid());
5131 return PERMISSION_DENIED;
5132 }
5133 mPreferredMixerAttrInfos[portId].erase(strategy);
5134 if (mPreferredMixerAttrInfos[portId].empty()) {
5135 mPreferredMixerAttrInfos.erase(portId);
5136 }
5137
5138 // Reconfig existing output
5139 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5140 for (size_t i = 0; i < mOutputs.size(); i++) {
5141 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5142 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5143 }
5144 }
5145 for (const auto output : potentialOutputsToReopen) {
5146 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5147 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5148 preferredMixerAttrInfo->getFlags())) {
5149 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5150 }
5151 }
5152 return NO_ERROR;
5153}
5154
Eric Laurent6a94d692014-05-20 11:18:06 -07005155status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5156 audio_port_type_t type,
5157 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005158 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005159 unsigned int *generation)
5160{
jiabin19cdba52020-11-24 11:28:58 -08005161 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5162 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005163 return BAD_VALUE;
5164 }
5165 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005166 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005167 *num_ports = 0;
5168 }
5169
5170 size_t portsWritten = 0;
5171 size_t portsMax = *num_ports;
5172 *num_ports = 0;
5173 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005174 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5175 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005176 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005177 for (const auto& dev : mAvailableOutputDevices) {
5178 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005179 continue;
5180 }
5181 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005182 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005183 }
5184 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005185 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005186 }
5187 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005188 for (const auto& dev : mAvailableInputDevices) {
5189 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005190 continue;
5191 }
5192 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005193 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005194 }
5195 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005196 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005197 }
5198 }
5199 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5200 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5201 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5202 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5203 }
5204 *num_ports += mInputs.size();
5205 }
5206 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005207 size_t numOutputs = 0;
5208 for (size_t i = 0; i < mOutputs.size(); i++) {
5209 if (!mOutputs[i]->isDuplicated()) {
5210 numOutputs++;
5211 if (portsWritten < portsMax) {
5212 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5213 }
5214 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005215 }
Eric Laurent84c70242014-06-23 08:46:27 -07005216 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005217 }
5218 }
jiabina84c3d32022-12-02 18:59:55 +00005219
Eric Laurent6a94d692014-05-20 11:18:06 -07005220 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005221 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005222 return NO_ERROR;
5223}
5224
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005225status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5226 std::vector<media::AudioPortFw>* _aidl_return) {
5227 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5228 audio_port_v7 port;
5229 dev->toAudioPort(&port);
5230 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5231 _aidl_return->push_back(std::move(aidlPort));
5232 return OK;
5233 };
5234
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005235 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005236 for (const auto& dev : module->getDeclaredDevices()) {
5237 if (role == media::AudioPortRole::NONE ||
5238 ((role == media::AudioPortRole::SOURCE)
5239 == audio_is_input_device(dev->type()))) {
5240 RETURN_STATUS_IF_ERROR(pushPort(dev));
5241 }
5242 }
5243 }
5244 return OK;
5245}
5246
jiabin19cdba52020-11-24 11:28:58 -08005247status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005248{
Eric Laurent99fcae42018-05-17 16:59:18 -07005249 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5250 return BAD_VALUE;
5251 }
5252 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5253 if (dev != 0) {
5254 dev->toAudioPort(port);
5255 return NO_ERROR;
5256 }
5257 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5258 if (dev != 0) {
5259 dev->toAudioPort(port);
5260 return NO_ERROR;
5261 }
5262 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5263 if (out != 0) {
5264 out->toAudioPort(port);
5265 return NO_ERROR;
5266 }
5267 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5268 if (in != 0) {
5269 in->toAudioPort(port);
5270 return NO_ERROR;
5271 }
5272 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005273}
5274
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005275status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5276 audio_patch_handle_t *handle,
5277 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005278{
François Gaffieafd4cea2019-11-18 15:50:22 +01005279 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005280 if (handle == NULL || patch == NULL) {
5281 return BAD_VALUE;
5282 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005283 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005284 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005285 return BAD_VALUE;
5286 }
5287 // only one source per audio patch supported for now
5288 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005289 return INVALID_OPERATION;
5290 }
Eric Laurent874c42872014-08-08 15:13:39 -07005291 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 return INVALID_OPERATION;
5293 }
Eric Laurent874c42872014-08-08 15:13:39 -07005294 for (size_t i = 0; i < patch->num_sinks; i++) {
5295 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5296 return INVALID_OPERATION;
5297 }
5298 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005299
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005300 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5301 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5302 if (srcDevice == nullptr || sinkDevice == nullptr) {
5303 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5304 return BAD_VALUE;
5305 }
5306 ALOGV("%s between source %s and sink %s", __func__,
5307 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5308 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5309 // Default attributes, default volume priority, not to infer with non raw audio patches.
5310 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5311 const struct audio_port_config *source = &patch->sources[0];
5312 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005313 new SourceClientDescriptor(
5314 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5315 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005316 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005317 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005318
5319 status_t status =
5320 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5321
5322 if (status != NO_ERROR) {
5323 return INVALID_OPERATION;
5324 }
5325 mAudioSources.add(portId, sourceDesc);
5326 return NO_ERROR;
5327}
5328
5329status_t AudioPolicyManager::connectAudioSourceToSink(
5330 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5331 const struct audio_patch *patch,
5332 audio_patch_handle_t &handle,
5333 uid_t uid, uint32_t delayMs)
5334{
5335 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5336 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5337 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5338 return INVALID_OPERATION;
5339 }
5340 sourceDesc->connect(handle, sinkDevice);
5341 if (isMsdPatch(handle)) {
5342 return NO_ERROR;
5343 }
5344 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5345 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5346 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5347 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5348 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5349 goto FailurePatchAdded;
5350 }
5351 status = swOutput->start();
5352 if (status != NO_ERROR) {
5353 goto FailureSourceAdded;
5354 }
5355 swOutput->addClient(sourceDesc);
5356 status = startSource(swOutput, sourceDesc, &delayMs);
5357 if (status != NO_ERROR) {
5358 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5359 goto FailureSourceActive;
5360 }
5361 if (delayMs != 0) {
5362 usleep(delayMs * 1000);
5363 }
5364 return NO_ERROR;
5365
5366FailureSourceActive:
5367 swOutput->stop();
5368 releaseOutput(sourceDesc->portId());
5369FailureSourceAdded:
5370 sourceDesc->setSwOutput(nullptr);
5371FailurePatchAdded:
5372 releaseAudioPatchInternal(handle);
5373 return INVALID_OPERATION;
5374}
5375
5376status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5377 audio_patch_handle_t *handle,
5378 uid_t uid, uint32_t delayMs,
5379 const sp<SourceClientDescriptor>& sourceDesc)
5380{
5381 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005382 sp<AudioPatch> patchDesc;
5383 ssize_t index = mAudioPatches.indexOfKey(*handle);
5384
François Gaffieafd4cea2019-11-18 15:50:22 +01005385 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5386 patch->sources[0].role,
5387 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005388#if LOG_NDEBUG == 0
5389 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005390 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5391 patch->sinks[i].role,
5392 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005393 }
5394#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005395
5396 if (index >= 0) {
5397 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005398 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5399 __func__, mUidCached, patchDesc->getUid(), uid);
5400 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005401 return INVALID_OPERATION;
5402 }
5403 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005404 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005405 }
5406
5407 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005408 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005409 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005410 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005411 return BAD_VALUE;
5412 }
Eric Laurent84c70242014-06-23 08:46:27 -07005413 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5414 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005415 if (patchDesc != 0) {
5416 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005417 ALOGV("%s source id differs for patch current id %d new id %d",
5418 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005419 return BAD_VALUE;
5420 }
5421 }
Eric Laurent874c42872014-08-08 15:13:39 -07005422 DeviceVector devices;
5423 for (size_t i = 0; i < patch->num_sinks; i++) {
5424 // Only support mix to devices connection
5425 // TODO add support for mix to mix connection
5426 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005427 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005428 return INVALID_OPERATION;
5429 }
5430 sp<DeviceDescriptor> devDesc =
5431 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5432 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005433 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005434 return BAD_VALUE;
5435 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005436
jiabin66acc432024-02-06 00:57:36 +00005437 if (outputDesc->mProfile->getCompatibilityScore(
5438 DeviceVector(devDesc),
5439 patch->sources[0].sample_rate,
5440 nullptr, // updatedSamplingRate
5441 patch->sources[0].format,
5442 nullptr, // updatedFormat
5443 patch->sources[0].channel_mask,
5444 nullptr, // updatedChannelMask
5445 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005446 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005447 return INVALID_OPERATION;
5448 }
5449 devices.add(devDesc);
5450 }
5451 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005452 return INVALID_OPERATION;
5453 }
Eric Laurent874c42872014-08-08 15:13:39 -07005454
Eric Laurent6a94d692014-05-20 11:18:06 -07005455 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005456 ALOGV("%s setting device %s on output %d",
5457 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305458 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005459 index = mAudioPatches.indexOfKey(*handle);
5460 if (index >= 0) {
5461 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005462 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005463 }
5464 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005465 patchDesc->setUid(uid);
5466 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005467 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005468 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005469 return INVALID_OPERATION;
5470 }
5471 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5472 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5473 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005474 // only one sink supported when connecting an input device to a mix
5475 if (patch->num_sinks > 1) {
5476 return INVALID_OPERATION;
5477 }
François Gaffie53615e22015-03-19 09:24:12 +01005478 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005479 if (inputDesc == NULL) {
5480 return BAD_VALUE;
5481 }
5482 if (patchDesc != 0) {
5483 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5484 return BAD_VALUE;
5485 }
5486 }
François Gaffie11d30102018-11-02 16:09:09 +01005487 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005488 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005489 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005490 return BAD_VALUE;
5491 }
5492
jiabin66acc432024-02-06 00:57:36 +00005493 if (inputDesc->mProfile->getCompatibilityScore(
5494 DeviceVector(device),
5495 patch->sinks[0].sample_rate,
5496 nullptr, /*updatedSampleRate*/
5497 patch->sinks[0].format,
5498 nullptr, /*updatedFormat*/
5499 patch->sinks[0].channel_mask,
5500 nullptr, /*updatedChannelMask*/
5501 // FIXME for the parameter type,
5502 // and the NONE
5503 (audio_output_flags_t)
5504 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005505 return INVALID_OPERATION;
5506 }
5507 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005508 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005509 device->toString().c_str(), inputDesc->mIoHandle);
5510 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005511 index = mAudioPatches.indexOfKey(*handle);
5512 if (index >= 0) {
5513 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005514 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005515 }
5516 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005517 patchDesc->setUid(uid);
5518 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005519 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005520 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005521 return INVALID_OPERATION;
5522 }
5523 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5524 // device to device connection
5525 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005526 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005527 return BAD_VALUE;
5528 }
5529 }
François Gaffie11d30102018-11-02 16:09:09 +01005530 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005531 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005532 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005533 return BAD_VALUE;
5534 }
Eric Laurent874c42872014-08-08 15:13:39 -07005535
Eric Laurent6a94d692014-05-20 11:18:06 -07005536 //update source and sink with our own data as the data passed in the patch may
5537 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005538 PatchBuilder patchBuilder;
5539 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005540
5541 // if first sink is to MSD, establish single MSD patch
5542 if (getMsdAudioOutDevices().contains(
5543 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5544 ALOGV("%s patching to MSD", __FUNCTION__);
5545 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5546 goto installPatch;
5547 }
5548
François Gaffieafd4cea2019-11-18 15:50:22 +01005549 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5550 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005551
Eric Laurent874c42872014-08-08 15:13:39 -07005552 for (size_t i = 0; i < patch->num_sinks; i++) {
5553 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005554 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005555 return INVALID_OPERATION;
5556 }
François Gaffie11d30102018-11-02 16:09:09 +01005557 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005558 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005559 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005560 return BAD_VALUE;
5561 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005562 audio_port_config sinkPortConfig = {};
5563 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5564 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005565
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005566 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5567 // volume management purpose (tracking activity)
5568 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5569 // in config XML to reach the sink so that is can be declared as available.
5570 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005571 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005572 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005573 // take care of dynamic routing for SwOutput selection,
5574 audio_attributes_t attributes = sourceDesc->attributes();
5575 audio_stream_type_t stream = sourceDesc->stream();
5576 audio_attributes_t resultAttr;
5577 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5578 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005579 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5580 config.channel_mask =
5581 (audio_channel_mask_get_representation(sourceMask)
5582 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5583 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005584 config.format = sourceDesc->config().format;
5585 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5586 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5587 bool isRequestedDeviceForExclusiveUse = false;
5588 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005589 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005590 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005591 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5592 &stream, sourceDesc->uid(), &config, &flags,
5593 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005594 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005595 if (output == AUDIO_IO_HANDLE_NONE) {
5596 ALOGV("%s no output for device %s",
5597 __FUNCTION__, sinkDevice->toString().c_str());
5598 return INVALID_OPERATION;
5599 }
5600 outputDesc = mOutputs.valueFor(output);
5601 if (outputDesc->isDuplicated()) {
5602 ALOGE("%s output is duplicated", __func__);
5603 return INVALID_OPERATION;
5604 }
François Gaffie7e39df22022-04-26 12:48:49 +02005605 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5606 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005607 } else {
5608 // Same for "raw patches" aka created from createAudioPatch API
5609 SortedVector<audio_io_handle_t> outputs =
5610 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5611 // if the sink device is reachable via an opened output stream, request to
5612 // go via this output stream by adding a second source to the patch
5613 // description
5614 output = selectOutput(outputs);
5615 if (output == AUDIO_IO_HANDLE_NONE) {
5616 ALOGE("%s no output available for internal patch sink", __func__);
5617 return INVALID_OPERATION;
5618 }
5619 outputDesc = mOutputs.valueFor(output);
5620 if (outputDesc->isDuplicated()) {
5621 ALOGV("%s output for device %s is duplicated",
5622 __func__, sinkDevice->toString().c_str());
5623 return INVALID_OPERATION;
5624 }
François Gaffie7e39df22022-04-26 12:48:49 +02005625 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005626 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005627 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005628 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005629 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005630 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005631 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5632 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005633 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5634 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005635 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005636 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005637 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005638 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005639 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005640 return INVALID_OPERATION;
5641 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005642 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005643 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005644 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005645 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005646 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005647 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005648 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005649 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5650 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005651 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005652 }
Eric Laurent83b88082014-06-20 18:31:16 -07005653 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005654 }
5655 // TODO: check from routing capabilities in config file and other conflicting patches
5656
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005657installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005658 status_t status = installPatch(
5659 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005660 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005661 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005662 return INVALID_OPERATION;
5663 }
5664 } else {
5665 return BAD_VALUE;
5666 }
5667 } else {
5668 return BAD_VALUE;
5669 }
5670 return NO_ERROR;
5671}
5672
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005673status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005674{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005675 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005676 ssize_t index = mAudioPatches.indexOfKey(handle);
5677
5678 if (index < 0) {
5679 return BAD_VALUE;
5680 }
5681 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005682 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5683 __func__, mUidCached, patchDesc->getUid(), uid);
5684 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005685 return INVALID_OPERATION;
5686 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005687 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5688 for (size_t i = 0; i < mAudioSources.size(); i++) {
5689 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5690 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5691 portId = sourceDesc->portId();
5692 break;
5693 }
5694 }
5695 return portId != AUDIO_PORT_HANDLE_NONE ?
5696 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005697}
Eric Laurent6a94d692014-05-20 11:18:06 -07005698
François Gaffieafd4cea2019-11-18 15:50:22 +01005699status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005700 uint32_t delayMs,
5701 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005702{
5703 ALOGV("%s patch %d", __func__, handle);
5704 if (mAudioPatches.indexOfKey(handle) < 0) {
5705 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5706 return BAD_VALUE;
5707 }
5708 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005709 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005710 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005711 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005712 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005713 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005714 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005715 return BAD_VALUE;
5716 }
5717
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305718 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005719 getNewOutputDevices(outputDesc, true /*fromCache*/),
5720 true,
5721 0,
5722 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005723 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5724 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005725 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005726 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005727 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005728 return BAD_VALUE;
5729 }
5730 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005731 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005732 true,
5733 NULL);
5734 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005735 status_t status =
5736 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5737 ALOGV("%s patch panel returned %d patchHandle %d",
5738 __func__, status, patchDesc->getAfHandle());
5739 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005740 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005741 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005742 // SW or HW Bridge
5743 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5744 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005745 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005746 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5747 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5748 outputDesc = sourceDesc->swOutput().promote();
5749 }
5750 if (outputDesc == nullptr) {
5751 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5752 // releaseOutput has already called closeOutput in case of direct output
5753 return NO_ERROR;
5754 }
François Gaffie7e39df22022-04-26 12:48:49 +02005755 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005756 // While using a HwBridge, force reconsidering device only if not reusing an existing
5757 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005758 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005759 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5760 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5761 // Reconsider device only for cases:
5762 // 1 / Active Output
5763 // 2 / Inactive Output previously hosting HwBridge
5764 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5765 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5766 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305767 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005768 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5769 outputDesc->devices(),
5770 force,
5771 0,
5772 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005773 } else {
5774 return BAD_VALUE;
5775 }
5776 } else {
5777 return BAD_VALUE;
5778 }
5779 return NO_ERROR;
5780}
5781
5782status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5783 struct audio_patch *patches,
5784 unsigned int *generation)
5785{
François Gaffie53615e22015-03-19 09:24:12 +01005786 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005787 return BAD_VALUE;
5788 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005789 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005790 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005791}
5792
Eric Laurente1715a42014-05-20 11:30:42 -07005793status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005794{
Eric Laurente1715a42014-05-20 11:30:42 -07005795 ALOGV("setAudioPortConfig()");
5796
5797 if (config == NULL) {
5798 return BAD_VALUE;
5799 }
5800 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5801 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005802 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5803 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005804 }
5805
Eric Laurenta121f902014-06-03 13:32:54 -07005806 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005807 if (config->type == AUDIO_PORT_TYPE_MIX) {
5808 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005809 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005810 if (outputDesc == NULL) {
5811 return BAD_VALUE;
5812 }
Eric Laurent84c70242014-06-23 08:46:27 -07005813 ALOG_ASSERT(!outputDesc->isDuplicated(),
5814 "setAudioPortConfig() called on duplicated output %d",
5815 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005816 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005817 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005818 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005819 if (inputDesc == NULL) {
5820 return BAD_VALUE;
5821 }
Eric Laurenta121f902014-06-03 13:32:54 -07005822 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005823 } else {
5824 return BAD_VALUE;
5825 }
5826 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5827 sp<DeviceDescriptor> deviceDesc;
5828 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5829 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5830 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5831 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5832 } else {
5833 return BAD_VALUE;
5834 }
5835 if (deviceDesc == NULL) {
5836 return BAD_VALUE;
5837 }
Eric Laurenta121f902014-06-03 13:32:54 -07005838 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005839 } else {
5840 return BAD_VALUE;
5841 }
5842
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005843 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005844 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5845 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005846 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005847 audioPortConfig->toAudioPortConfig(&newConfig, config);
5848 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005849 }
Eric Laurenta121f902014-06-03 13:32:54 -07005850 if (status != NO_ERROR) {
5851 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005852 }
Eric Laurente1715a42014-05-20 11:30:42 -07005853
5854 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005855}
5856
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005857void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5858{
Eric Laurentd60560a2015-04-10 11:31:20 -07005859 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005860 clearAudioPatches(uid);
5861 clearSessionRoutes(uid);
5862}
5863
Eric Laurent6a94d692014-05-20 11:18:06 -07005864void AudioPolicyManager::clearAudioPatches(uid_t uid)
5865{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005866 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005867 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005868 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005869 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005870 }
5871 }
5872}
5873
François Gaffiec005e562018-11-06 15:04:49 +01005874void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005875{
François Gaffiec005e562018-11-06 15:04:49 +01005876 // Take the first attributes following the product strategy as it is used to retrieve the routed
5877 // device. All attributes wihin a strategy follows the same "routing strategy"
5878 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5879 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005880 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005881 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005882 for (size_t j = 0; j < mOutputs.size(); j++) {
5883 if (mOutputs.keyAt(j) == ouptutToSkip) {
5884 continue;
5885 }
5886 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005887 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005888 continue;
5889 }
5890 // If the default device for this strategy is on another output mix,
5891 // invalidate all tracks in this strategy to force re connection.
5892 // Otherwise select new device on the output mix.
5893 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005894 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005895 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005896 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005897 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005898 // If the device is using preferred mixer attributes, the output need to reopen
5899 // with default configuration when the new selected devices are different from
5900 // current routing devices.
5901 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5902 continue;
5903 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305904 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005905 }
5906 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005907 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005908}
5909
5910void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5911{
5912 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005913 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005914 for (size_t i = 0; i < mOutputs.size(); i++) {
5915 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005916 for (const auto& client : outputDesc->getClientIterable()) {
5917 if (client->hasPreferredDevice() && client->uid() == uid) {
5918 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005919 auto clientStrategy = client->strategy();
5920 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5921 end(affectedStrategies)) {
5922 continue;
5923 }
5924 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005925 }
5926 }
5927 }
5928 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005929 for (const auto& strategy : affectedStrategies) {
5930 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005931 }
5932
5933 // remove input routes associated with this uid
5934 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005935 for (size_t i = 0; i < mInputs.size(); i++) {
5936 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005937 for (const auto& client : inputDesc->getClientIterable()) {
5938 if (client->hasPreferredDevice() && client->uid() == uid) {
5939 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5940 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005941 }
5942 }
5943 }
5944 // reroute inputs if necessary
5945 SortedVector<audio_io_handle_t> inputsToClose;
5946 for (size_t i = 0; i < mInputs.size(); i++) {
5947 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005948 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005949 inputsToClose.add(inputDesc->mIoHandle);
5950 }
5951 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005952 for (const auto& input : inputsToClose) {
5953 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005954 }
5955}
5956
Eric Laurentd60560a2015-04-10 11:31:20 -07005957void AudioPolicyManager::clearAudioSources(uid_t uid)
5958{
5959 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005960 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5961 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005962 stopAudioSource(mAudioSources.keyAt(i));
5963 }
5964 }
5965}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005966
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005967status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5968 audio_io_handle_t *ioHandle,
5969 audio_devices_t *device)
5970{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005971 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5972 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005973 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005974 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5975 if (deviceDesc == nullptr) {
5976 return INVALID_OPERATION;
5977 }
5978 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005979
François Gaffiedf372692015-03-19 10:43:27 +01005980 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005981}
5982
Eric Laurentd60560a2015-04-10 11:31:20 -07005983status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005984 const audio_attributes_t *attributes,
5985 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00005986 uid_t uid) {
5987 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00005988 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00005989}
5990
5991status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5992 const audio_attributes_t *attributes,
5993 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00005994 uid_t uid, bool internal, bool isCallRx,
5995 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005996{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005997 ALOGV("%s", __FUNCTION__);
5998 *portId = AUDIO_PORT_HANDLE_NONE;
5999
6000 if (source == NULL || attributes == NULL || portId == NULL) {
6001 ALOGW("%s invalid argument: source %p attributes %p handle %p",
6002 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006003 return BAD_VALUE;
6004 }
6005
Eric Laurentd60560a2015-04-10 11:31:20 -07006006 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
6007 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006008 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
6009 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006010 return INVALID_OPERATION;
6011 }
6012
François Gaffie11d30102018-11-02 16:09:09 +01006013 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07006014 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006015 String8(source->ext.device.address),
6016 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01006017 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006018 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006019 return BAD_VALUE;
6020 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006021
jiabin4ef93452019-09-10 14:29:54 -07006022 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07006023
François Gaffieaaac0fd2018-11-22 17:56:39 +01006024 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01006025 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006026 mEngine->getStreamTypeForAttributes(*attributes),
6027 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00006028 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07006029
David Lif85c5e32024-07-01 13:14:10 +00006030 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07006031 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006032 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006033 }
6034 return status;
6035}
6036
David Lif85c5e32024-07-01 13:14:10 +00006037status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
6038 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07006039{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006040 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006041
6042 // make sure we only have one patch per source.
6043 disconnectAudioSource(sourceDesc);
6044
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006045 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006046 // May the device (dynamic) have been disconnected/reconnected, id has changed.
6047 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
6048 sourceDesc->srcDevice()->type(),
6049 String8(sourceDesc->srcDevice()->address().c_str()),
6050 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01006051 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02006052 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01006053 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01006054 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006055 if (!mAvailableOutputDevices.contains(sinkDevice)) {
6056 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
6057 return INVALID_OPERATION;
6058 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006059 PatchBuilder patchBuilder;
6060 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
6061 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01006062
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006063 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00006064 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07006065}
6066
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006067status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07006068{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006069 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6070 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006071 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006072 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006073 return BAD_VALUE;
6074 }
6075 status_t status = disconnectAudioSource(sourceDesc);
6076
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006077 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006078 return status;
6079}
6080
Andy Hung2ddee192015-12-18 17:34:44 -08006081status_t AudioPolicyManager::setMasterMono(bool mono)
6082{
6083 if (mMasterMono == mono) {
6084 return NO_ERROR;
6085 }
6086 mMasterMono = mono;
6087 // if enabling mono we close all offloaded devices, which will invalidate the
6088 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6089 // for recreating the new AudioTrack as non-offloaded PCM.
6090 //
6091 // If disabling mono, we leave all tracks as is: we don't know which clients
6092 // and tracks are able to be recreated as offloaded. The next "song" should
6093 // play back offloaded.
6094 if (mMasterMono) {
6095 Vector<audio_io_handle_t> offloaded;
6096 for (size_t i = 0; i < mOutputs.size(); ++i) {
6097 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6098 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6099 offloaded.push(desc->mIoHandle);
6100 }
6101 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006102 for (const auto& handle : offloaded) {
6103 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006104 }
6105 }
6106 // update master mono for all remaining outputs
6107 for (size_t i = 0; i < mOutputs.size(); ++i) {
6108 updateMono(mOutputs.keyAt(i));
6109 }
6110 return NO_ERROR;
6111}
6112
6113status_t AudioPolicyManager::getMasterMono(bool *mono)
6114{
6115 *mono = mMasterMono;
6116 return NO_ERROR;
6117}
6118
Eric Laurentac9cef52017-06-09 15:46:26 -07006119float AudioPolicyManager::getStreamVolumeDB(
6120 audio_stream_type_t stream, int index, audio_devices_t device)
6121{
Vlad Popa9d482762024-06-21 16:40:23 -07006122 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6123 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006124}
6125
jiabin81772902018-04-02 17:52:27 -07006126status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6127 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006128 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006129{
Kriti Dang6537def2021-03-02 13:46:59 +01006130 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6131 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006132 return BAD_VALUE;
6133 }
Kriti Dang6537def2021-03-02 13:46:59 +01006134 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6135 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006136
6137 size_t formatsWritten = 0;
6138 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006139
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006140 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006141 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6142 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006143 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006144 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006145 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006146 bool formatEnabled = true;
6147 switch (forceUse) {
6148 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006149 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006150 break;
6151 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6152 formatEnabled = false;
6153 break;
6154 default: // AUTO or ALWAYS => true
6155 break;
jiabin81772902018-04-02 17:52:27 -07006156 }
6157 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6158 }
jiabin81772902018-04-02 17:52:27 -07006159 }
6160 return NO_ERROR;
6161}
6162
Kriti Dang6537def2021-03-02 13:46:59 +01006163status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6164 audio_format_t *surroundFormats) {
6165 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6166 return BAD_VALUE;
6167 }
6168 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6169 __func__, *numSurroundFormats, surroundFormats);
6170
6171 size_t formatsWritten = 0;
6172 size_t formatsMax = *numSurroundFormats;
6173 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6174
6175 // Return formats from all device profiles that have already been resolved by
6176 // checkOutputsForDevice().
6177 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6178 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6179 audio_devices_t deviceType = device->type();
6180 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6181 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006182 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6183 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006184 continue;
6185 }
6186 // Formats reported by sink devices
6187 std::unordered_set<audio_format_t> formatset;
6188 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6189 formatset.insert(it->second.begin(), it->second.end());
6190 }
6191
6192 // Formats hard-coded in the in policy configuration file (if any).
6193 FormatVector encodedFormats = device->encodedFormats();
6194 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6195 // Filter the formats which are supported by the vendor hardware.
6196 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006197 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006198 formats.insert(*it);
6199 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006200 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006201 if (pair.second.count(*it) != 0) {
6202 formats.insert(pair.first);
6203 break;
6204 }
6205 }
6206 }
6207 }
6208 }
6209 *numSurroundFormats = formats.size();
6210 for (const auto& format: formats) {
6211 if (formatsWritten < formatsMax) {
6212 surroundFormats[formatsWritten++] = format;
6213 }
6214 }
6215 return NO_ERROR;
6216}
6217
jiabin81772902018-04-02 17:52:27 -07006218status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6219{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006220 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006221 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6222 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006223 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006224 return BAD_VALUE;
6225 }
6226
Mikhail Naganov100f0122018-11-29 11:22:16 -08006227 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6228 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006229 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006230 return INVALID_OPERATION;
6231 }
6232
Mikhail Naganov100f0122018-11-29 11:22:16 -08006233 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006234 return NO_ERROR;
6235 }
6236
Mikhail Naganov100f0122018-11-29 11:22:16 -08006237 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006238 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006239 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006240 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006241 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006242 }
6243 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006244 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006245 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006246 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006247 }
6248 }
6249
6250 sp<SwAudioOutputDescriptor> outputDesc;
6251 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006252 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6253 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006254 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6255 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006256 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006257 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006258 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006259 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6260 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006261 name.c_str(),
6262 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006263 if (status != NO_ERROR) {
6264 continue;
6265 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006266 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006267 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6268 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006269 name.c_str(),
6270 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006271 profileUpdated |= (status == NO_ERROR);
6272 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006273 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006274 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006275 AUDIO_DEVICE_IN_HDMI);
6276 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6277 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006278 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006279 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006280 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6281 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6282 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006283 name.c_str(),
6284 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006285 if (status != NO_ERROR) {
6286 continue;
6287 }
6288 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6289 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6290 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006291 name.c_str(),
6292 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006293 profileUpdated |= (status == NO_ERROR);
6294 }
6295
jiabin81772902018-04-02 17:52:27 -07006296 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006297 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006298 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006299 }
6300
6301 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6302}
6303
Eric Laurent5ada82e2019-08-29 17:53:54 -07006304void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006305{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006306 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006307 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006308 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006309 }
6310}
6311
jiabin6012f912018-11-02 17:06:30 -07006312bool AudioPolicyManager::isHapticPlaybackSupported()
6313{
6314 for (const auto& hwModule : mHwModules) {
6315 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6316 for (const auto &outProfile : outputProfiles) {
6317 struct audio_port audioPort;
6318 outProfile->toAudioPort(&audioPort);
6319 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6320 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6321 return true;
6322 }
6323 }
6324 }
6325 }
6326 return false;
6327}
6328
Carter Hsu325a8eb2022-01-19 19:56:51 +08006329bool AudioPolicyManager::isUltrasoundSupported()
6330{
6331 bool hasUltrasoundOutput = false;
6332 bool hasUltrasoundInput = false;
6333 for (const auto& hwModule : mHwModules) {
6334 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6335 if (!hasUltrasoundOutput) {
6336 for (const auto &outProfile : outputProfiles) {
6337 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6338 hasUltrasoundOutput = true;
6339 break;
6340 }
6341 }
6342 }
6343
6344 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6345 if (!hasUltrasoundInput) {
6346 for (const auto &inputProfile : inputProfiles) {
6347 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6348 hasUltrasoundInput = true;
6349 break;
6350 }
6351 }
6352 }
6353
6354 if (hasUltrasoundOutput && hasUltrasoundInput)
6355 return true;
6356 }
6357 return false;
6358}
6359
Atneya Nair698f5ef2022-12-15 16:15:09 -08006360bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6361{
6362 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6363 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6364 for (const auto& hwModule : mHwModules) {
6365 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6366 for (const auto &inputProfile : inputProfiles) {
6367 if ((inputProfile->getFlags() & mask) == mask) {
6368 return true;
6369 }
6370 }
6371 }
6372 return false;
6373}
6374
Eric Laurent8340e672019-11-06 11:01:08 -08006375bool AudioPolicyManager::isCallScreenModeSupported()
6376{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006377 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006378}
6379
6380
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006381status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006382{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006383 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006384 if (!sourceDesc->isConnected()) {
6385 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6386 return NO_ERROR;
6387 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006388 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6389 if (swOutput != 0) {
6390 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006391 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006392 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006393 }
jiabinbce0c1d2020-10-05 11:20:18 -07006394 if (releaseOutput(sourceDesc->portId())) {
6395 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6396 // no need to release audio patch here but just return NO_ERROR.
6397 return NO_ERROR;
6398 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006399 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006400 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006401 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006402 // close Hwoutput and remove from mHwOutputs
6403 } else {
6404 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6405 }
6406 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006407 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006408 sourceDesc->disconnect();
6409 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006410}
6411
François Gaffiec005e562018-11-06 15:04:49 +01006412sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6413 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006414{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006415 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006416 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006417 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006418 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006419 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6420 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006421 source = sourceDesc;
6422 break;
6423 }
6424 }
6425 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006426}
6427
Eric Laurentb4f42a92022-01-17 17:37:31 +01006428bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006429 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006430 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006431{
6432 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6433 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006434 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006435 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006436 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6437 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6438 return false;
6439 }
6440 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6441 return false;
6442 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006443 }
6444
Eric Laurentd332bc82023-08-04 11:45:23 +02006445 // The caller can have the audio config criteria ignored by either passing a null ptr or
6446 // the AUDIO_CONFIG_INITIALIZER value.
6447 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006448 // some positional channel masks and PCM format and for stereo if low latency performance
6449 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006450
6451 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006452 const bool channel_mask_spatialized =
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00006453 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6454 ? audio_channel_mask_contains_stereo(config->channel_mask)
6455 : audio_is_channel_mask_spatialized(config->channel_mask);
Andy Hung481bfe32023-12-18 14:00:29 -08006456 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006457 return false;
6458 }
6459 if (!audio_is_linear_pcm(config->format)) {
6460 return false;
6461 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006462 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6463 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6464 return false;
6465 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006466 }
6467
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006468 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006469 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006470 if (profile == nullptr) {
6471 return false;
6472 }
6473
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006474 return true;
6475}
6476
Shunkai Yao4c3af932024-04-26 04:12:21 +00006477// The Spatializer output is compatible with Haptic use cases if:
6478// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6479// with client if client haptic channel bits were set, or
6480// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6481// including the haptic bits or creating the HapticGenerator effect for same session.
6482bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6483 const audio_config_t* config, audio_session_t sessionId) const {
6484 const auto clientHapticChannel =
6485 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6486 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6487 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6488
6489 if (threadOutputHapticChannel) {
6490 // check format and sampleRate match if client haptic channel mask exist
6491 if (clientHapticChannel) {
6492 return mSpatializerOutput->getFormat() == config->format &&
6493 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6494 }
6495 return true;
6496 } else {
6497 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6498 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6499 // HapticGenerator effect for this session) are not supported.
6500 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006501 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006502 }
6503}
6504
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006505void AudioPolicyManager::checkVirtualizerClientRoutes() {
6506 std::set<audio_stream_type_t> streamsToInvalidate;
6507 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006508 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6509 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006510 audio_attributes_t attr = client->attributes();
6511 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6512 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6513 audio_config_base_t clientConfig = client->config();
6514 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006515 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006516 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006517 streamsToInvalidate.insert(client->stream());
6518 }
6519 }
6520 }
6521
jiabinc44b3462022-12-08 12:52:31 -08006522 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006523}
6524
Eric Laurente191d1b2022-04-15 11:59:25 +02006525
6526bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6527 const sp<SwAudioOutputDescriptor>& outputDesc) {
6528 if (outputDesc->isDuplicated()) {
6529 return false;
6530 }
6531 DeviceVector devices = outputDesc->supportedDevices();
6532 for (size_t i = 0; i < mOutputs.size(); i++) {
6533 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6534 if (desc == outputDesc || desc->isDuplicated()) {
6535 continue;
6536 }
6537 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6538 if (!sharedDevices.isEmpty()
6539 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6540 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6541 return false;
6542 }
6543 }
6544 return true;
6545}
6546
6547
Eric Laurentfa0f6742021-08-17 18:39:44 +02006548status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006549 const audio_attributes_t *attr,
6550 audio_io_handle_t *output) {
6551 *output = AUDIO_IO_HANDLE_NONE;
6552
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006553 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6554 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6555 audio_config_t *configPtr = nullptr;
6556 audio_config_t config;
6557 if (mixerConfig != nullptr) {
6558 config = audio_config_initializer(mixerConfig);
6559 configPtr = &config;
6560 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006561 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006562 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006563 return BAD_VALUE;
6564 }
6565
6566 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006567 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006568 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006569 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006570 return BAD_VALUE;
6571 }
6572
Eric Laurente191d1b2022-04-15 11:59:25 +02006573 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006574 for (size_t i = 0; i < mOutputs.size(); i++) {
6575 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006576 if (!desc->isDuplicated()
6577 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6578 spatializerOutputs.push_back(desc);
6579 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006580 }
6581 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006582 mSpatializerOutput.clear();
6583 bool outputsChanged = false;
6584 for (const auto& desc : spatializerOutputs) {
6585 if (desc->mProfile == profile
6586 && (configPtr == nullptr
6587 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6588 mSpatializerOutput = desc;
6589 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6590 } else {
6591 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6592 " and devices %s", __func__, desc->mIoHandle,
6593 configPtr != nullptr ? configPtr->channel_mask : 0,
6594 devices.toString().c_str());
6595 closeOutput(desc->mIoHandle);
6596 outputsChanged = true;
6597 }
Eric Laurent39095982021-08-24 18:29:27 +02006598 }
6599
Eric Laurente191d1b2022-04-15 11:59:25 +02006600 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006601 sp<SwAudioOutputDescriptor> desc =
6602 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006603 if (desc != nullptr) {
6604 mSpatializerOutput = desc;
6605 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006606 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006607 }
6608
6609 checkVirtualizerClientRoutes();
6610
Eric Laurente191d1b2022-04-15 11:59:25 +02006611 if (outputsChanged) {
6612 mPreviousOutputs = mOutputs;
6613 mpClientInterface->onAudioPortListUpdate();
6614 }
6615
6616 if (mSpatializerOutput == nullptr) {
6617 ALOGV("%s could not open spatializer output with requested config", __func__);
6618 return BAD_VALUE;
6619 }
Eric Laurent39095982021-08-24 18:29:27 +02006620 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006621 ALOGV("%s returning new spatializer output %d", __func__, *output);
6622 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006623}
6624
Eric Laurentfa0f6742021-08-17 18:39:44 +02006625status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6626 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006627 return INVALID_OPERATION;
6628 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006629 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006630 return BAD_VALUE;
6631 }
Eric Laurent39095982021-08-24 18:29:27 +02006632
Eric Laurente191d1b2022-04-15 11:59:25 +02006633 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6634 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6635 closeOutput(mSpatializerOutput->mIoHandle);
6636 //from now on mSpatializerOutput is null
6637 checkVirtualizerClientRoutes();
6638 }
Eric Laurent39095982021-08-24 18:29:27 +02006639
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006640 return NO_ERROR;
6641}
6642
Eric Laurente552edb2014-03-10 17:42:56 -07006643// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006644// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006645// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006646uint32_t AudioPolicyManager::nextAudioPortGeneration()
6647{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006648 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006649}
6650
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006651AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006652 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006653 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006654 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006655 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006656 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006657 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006658 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006659 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006660 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006661 mAudioPortGeneration(1),
6662 mBeaconMuteRefCount(0),
6663 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006664 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006665 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006666 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006667 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006668{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006669}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006670
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006671status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006672 if (mEngine == nullptr) {
6673 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006674 }
6675 mEngine->setObserver(this);
6676 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006677 if (status != NO_ERROR) {
6678 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6679 return status;
6680 }
François Gaffie2110e042015-03-24 08:41:51 +01006681
jiabin29230182023-04-04 21:02:36 +00006682 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6683 // at the end of this function.
6684 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006685 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6686 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6687
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006688 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006689 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006690 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006691
Eric Laurent3a4311c2014-03-17 12:00:47 -07006692 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006693 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6694 defaultOutputDevice == nullptr ||
6695 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6696 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6697 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006698 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006699 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006700 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006701
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006702 // Silence ALOGV statements
6703 property_set("log.tag." LOG_TAG, "D");
6704
Eric Laurente552edb2014-03-10 17:42:56 -07006705 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006706 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006707}
6708
Eric Laurente0720872014-03-11 09:30:41 -07006709AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006710{
Eric Laurente552edb2014-03-10 17:42:56 -07006711 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006712 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006713 }
6714 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006715 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006716 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006717 mAvailableOutputDevices.clear();
6718 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006719 mOutputs.clear();
6720 mInputs.clear();
6721 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006722 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006723 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006724}
6725
Eric Laurente0720872014-03-11 09:30:41 -07006726status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006727{
Eric Laurent87ffa392015-05-22 10:32:38 -07006728 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006729}
6730
Eric Laurente552edb2014-03-10 17:42:56 -07006731// ---
6732
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006733void AudioPolicyManager::onNewAudioModulesAvailable()
6734{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006735 DeviceVector newDevices;
6736 onNewAudioModulesAvailableInt(&newDevices);
6737 if (!newDevices.empty()) {
6738 nextAudioPortGeneration();
6739 mpClientInterface->onAudioPortListUpdate();
6740 }
6741}
6742
6743void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6744{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006745 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006746 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6747 continue;
6748 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006749 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006750 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6751 handle != AUDIO_MODULE_HANDLE_NONE) {
6752 hwModule->setHandle(handle);
6753 } else {
6754 ALOGW("could not load HW module %s", hwModule->getName());
6755 continue;
6756 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006757 }
6758 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006759 // open all output streams needed to access attached devices.
6760 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006761 // This also validates mAvailableOutputDevices list
6762 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6763 if (!outProfile->canOpenNewIo()) {
6764 ALOGE("Invalid Output profile max open count %u for profile %s",
6765 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6766 continue;
6767 }
6768 if (!outProfile->hasSupportedDevices()) {
6769 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6770 continue;
6771 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006772 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6773 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006774 mTtsOutputAvailable = true;
6775 }
6776
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006777 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006778 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006779 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006780 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6781 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006782 } else {
6783 // choose first device present in profile's SupportedDevices also part of
6784 // mAvailableOutputDevices.
6785 if (availProfileDevices.isEmpty()) {
6786 continue;
6787 }
6788 supportedDevice = availProfileDevices.itemAt(0);
6789 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006790 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006791 continue;
6792 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306793
6794 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6795 && availProfileDevices.areAllDevicesAttached()) {
6796 ALOGV("%s skip opening output for mmap profile %s", __func__,
6797 outProfile->getTagName().c_str());
6798 continue;
6799 }
6800
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006801 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6802 mpClientInterface);
6803 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006804 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006805 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006806 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6807 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006808 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006809 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006810 if (status != NO_ERROR) {
6811 ALOGW("Cannot open output stream for devices %s on hw module %s",
6812 supportedDevice->toString().c_str(), hwModule->getName());
6813 continue;
6814 }
6815 for (const auto &device : availProfileDevices) {
6816 // give a valid ID to an attached device once confirmed it is reachable
6817 if (!device->isAttached()) {
6818 device->attach(hwModule);
6819 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006820 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006821 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006822 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6823 }
6824 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006825 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006826 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6827 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006828 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006829 }
Eric Laurent39095982021-08-24 18:29:27 +02006830 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006831 outputDesc->close();
6832 } else {
6833 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306834 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006835 DeviceVector(supportedDevice),
6836 true,
6837 0,
6838 NULL);
6839 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006840 }
6841 // open input streams needed to access attached devices to validate
6842 // mAvailableInputDevices list
6843 for (const auto& inProfile : hwModule->getInputProfiles()) {
6844 if (!inProfile->canOpenNewIo()) {
6845 ALOGE("Invalid Input profile max open count %u for profile %s",
6846 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6847 continue;
6848 }
6849 if (!inProfile->hasSupportedDevices()) {
6850 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6851 continue;
6852 }
6853 // chose first device present in profile's SupportedDevices also part of
6854 // available input devices
6855 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006856 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006857 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006858 ALOGV("%s: Input device list is empty! for profile %s",
6859 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006860 continue;
6861 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306862
6863 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6864 && availProfileDevices.areAllDevicesAttached()) {
6865 ALOGV("%s skip opening input for mmap profile %s", __func__,
6866 inProfile->getTagName().c_str());
6867 continue;
6868 }
6869
Eric Laurentc71b11b2024-06-03 12:54:53 +00006870 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6871 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006872
6873 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6874 status_t status = inputDesc->open(nullptr,
6875 availProfileDevices.itemAt(0),
6876 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306877 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006878 &input);
6879 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306880 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6881 __func__, availProfileDevices.toString().c_str(),
6882 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006883 continue;
6884 }
6885 for (const auto &device : availProfileDevices) {
6886 // give a valid ID to an attached device once confirmed it is reachable
6887 if (!device->isAttached()) {
6888 device->attach(hwModule);
6889 device->importAudioPortAndPickAudioProfile(inProfile, true);
6890 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006891 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006892 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6893 }
6894 }
6895 inputDesc->close();
6896 }
6897 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006898
6899 // Check if spatializer outputs can be closed until used.
6900 // mOutputs vector never contains duplicated outputs at this point.
6901 std::vector<audio_io_handle_t> outputsClosed;
6902 for (size_t i = 0; i < mOutputs.size(); i++) {
6903 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6904 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6905 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6906 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006907 nextAudioPortGeneration();
6908 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6909 if (index >= 0) {
6910 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6911 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6912 patchDesc->getAfHandle(), 0);
6913 mAudioPatches.removeItemsAt(index);
6914 mpClientInterface->onAudioPatchListUpdate();
6915 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006916 desc->close();
6917 }
6918 }
6919 for (auto output : outputsClosed) {
6920 removeOutput(output);
6921 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006922}
6923
Eric Laurent98e38192018-02-15 18:31:53 -08006924void AudioPolicyManager::addOutput(audio_io_handle_t output,
6925 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006926{
Eric Laurent1c333e22014-05-20 10:48:17 -07006927 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006928 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006929 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006930 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006931 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006932}
6933
François Gaffie53615e22015-03-19 09:24:12 +01006934void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6935{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006936 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6937 ALOGV("%s: removing primary output", __func__);
6938 mPrimaryOutput = nullptr;
6939 }
François Gaffie53615e22015-03-19 09:24:12 +01006940 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006941 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006942}
6943
Eric Laurent98e38192018-02-15 18:31:53 -08006944void AudioPolicyManager::addInput(audio_io_handle_t input,
6945 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006946{
Eric Laurent1c333e22014-05-20 10:48:17 -07006947 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006948 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006949}
Eric Laurente552edb2014-03-10 17:42:56 -07006950
François Gaffie11d30102018-11-02 16:09:09 +01006951status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006952 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006953 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006954{
François Gaffie11d30102018-11-02 16:09:09 +01006955 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006956 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006957 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006958
François Gaffie11d30102018-11-02 16:09:09 +01006959 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006960 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006961 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006962 }
Eric Laurente552edb2014-03-10 17:42:56 -07006963
Eric Laurent3b73df72014-03-11 09:06:29 -07006964 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006965 // first call getAudioPort to get the supported attributes from the HAL
6966 struct audio_port_v7 port = {};
6967 device->toAudioPort(&port);
6968 status_t status = mpClientInterface->getAudioPort(&port);
6969 if (status == NO_ERROR) {
6970 device->importAudioPort(port);
6971 }
6972
6973 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006974 for (size_t i = 0; i < mOutputs.size(); i++) {
6975 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006976 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006977 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006978 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6979 mOutputs.keyAt(i), device->toString().c_str());
6980 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006981 }
6982 }
6983 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006984 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006985 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006986 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6987 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006988 if (profile->supportsDevice(device)) {
6989 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05306990 ALOGV("%s(): adding profile %s from module %s",
6991 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006992 }
6993 }
6994 }
6995
Eric Laurent7b279bb2015-12-14 10:18:23 -08006996 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006997
Eric Laurente552edb2014-03-10 17:42:56 -07006998 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006999 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007000 return BAD_VALUE;
7001 }
7002
7003 // open outputs for matching profiles if needed. Direct outputs are also opened to
7004 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7005 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007006 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07007007
7008 // nothing to do if one output is already opened for this profile
7009 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007010 for (j = 0; j < outputs.size(); j++) {
7011 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07007012 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007013 // matching profile: save the sample rates, format and channel masks supported
7014 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01007015 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07007016 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007017 }
Eric Laurente552edb2014-03-10 17:42:56 -07007018 break;
7019 }
7020 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007021 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07007022 continue;
7023 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307024 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7025 ALOGV("%s skip opening output for mmap profile %s",
7026 __func__, profile->getTagName().c_str());
7027 continue;
7028 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007029 if (!profile->canOpenNewIo()) {
7030 ALOGW("Max Output number %u already opened for this profile %s",
7031 profile->maxOpenCount, profile->getTagName().c_str());
7032 continue;
7033 }
7034
Eric Laurent83efe1c2017-07-09 16:51:08 -07007035 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00007036 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07007037 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
7038 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07007039 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01007040 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007041 profiles.removeAt(profile_index);
7042 profile_index--;
7043 } else {
7044 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07007045 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01007046 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07007047 // TODO: when getAudioPort is ready, it may not be needed to import the audio
7048 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07007049 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007050 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007051
François Gaffie11d30102018-11-02 16:09:09 +01007052 if (device_distinguishes_on_address(deviceType)) {
7053 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
7054 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307055 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
7056 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007057 }
Eric Laurente552edb2014-03-10 17:42:56 -07007058 ALOGV("checkOutputsForDevice(): adding output %d", output);
7059 }
7060 }
7061
7062 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007063 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007064 return BAD_VALUE;
7065 }
Eric Laurentd4692962014-05-05 18:13:44 -07007066 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07007067 // check if one opened output is not needed any more after disconnecting one device
7068 for (size_t i = 0; i < mOutputs.size(); i++) {
7069 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007070 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007071 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007072 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01007073 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01007074 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01007075 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007076 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7077 mOutputs.keyAt(i));
7078 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007079 }
Eric Laurente552edb2014-03-10 17:42:56 -07007080 }
7081 }
Eric Laurentd4692962014-05-05 18:13:44 -07007082 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007083 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007084 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7085 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007086 if (!profile->supportsDevice(device)) {
7087 continue;
7088 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307089 ALOGV("%s(): clearing direct output profile %s on module %s",
7090 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007091 profile->clearAudioProfiles();
7092 if (!profile->hasDynamicAudioProfile()) {
7093 continue;
7094 }
7095 // When a device is disconnected, if there is an IOProfile that contains dynamic
7096 // profiles and supports the disconnected device, call getAudioPort to repopulate
7097 // the capabilities of the devices that is supported by the IOProfile.
7098 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7099 if (supportedDevice == device ||
7100 !mAvailableOutputDevices.contains(supportedDevice)) {
7101 continue;
7102 }
7103 struct audio_port_v7 port;
7104 supportedDevice->toAudioPort(&port);
7105 status_t status = mpClientInterface->getAudioPort(&port);
7106 if (status == NO_ERROR) {
7107 supportedDevice->importAudioPort(port);
7108 }
Eric Laurente552edb2014-03-10 17:42:56 -07007109 }
7110 }
7111 }
7112 }
7113 return NO_ERROR;
7114}
7115
François Gaffie11d30102018-11-02 16:09:09 +01007116status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007117 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007118{
François Gaffie11d30102018-11-02 16:09:09 +01007119 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007120 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007121 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007122 }
7123
Eric Laurentd4692962014-05-05 18:13:44 -07007124 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007125 sp<AudioInputDescriptor> desc;
7126
jiabinbf5f4262023-04-12 21:48:34 +00007127 // first call getAudioPort to get the supported attributes from the HAL
7128 struct audio_port_v7 port = {};
7129 device->toAudioPort(&port);
7130 status_t status = mpClientInterface->getAudioPort(&port);
7131 if (status == NO_ERROR) {
7132 device->importAudioPort(port);
7133 }
7134
Eric Laurent0dd51852019-04-19 18:18:58 -07007135 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007136 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007137 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007138 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007139 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007140 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007141 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007142
François Gaffie11d30102018-11-02 16:09:09 +01007143 if (profile->supportsDevice(device)) {
7144 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307145 ALOGV("%s : adding profile %s from module %s", __func__,
7146 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007147 }
7148 }
7149 }
7150
Eric Laurent0dd51852019-04-19 18:18:58 -07007151 if (profiles.isEmpty()) {
7152 ALOGW("%s: No input profile available for device %s",
7153 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007154 return BAD_VALUE;
7155 }
7156
7157 // open inputs for matching profiles if needed. Direct inputs are also opened to
7158 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7159 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7160
Eric Laurent1c333e22014-05-20 10:48:17 -07007161 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007162
Eric Laurentd4692962014-05-05 18:13:44 -07007163 // nothing to do if one input is already opened for this profile
7164 size_t input_index;
7165 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7166 desc = mInputs.valueAt(input_index);
7167 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007168 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007169 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007170 }
Eric Laurentd4692962014-05-05 18:13:44 -07007171 break;
7172 }
7173 }
7174 if (input_index != mInputs.size()) {
7175 continue;
7176 }
7177
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307178 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7179 ALOGV("%s skip opening input for mmap profile %s",
7180 __func__, profile->getTagName().c_str());
7181 continue;
7182 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007183 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307184 ALOGW("%s Max Input number %u already opened for this profile %s",
7185 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007186 continue;
7187 }
7188
Eric Laurentc71b11b2024-06-03 12:54:53 +00007189 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007190 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307191 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307192 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7193 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007194
Eric Laurentcf2c0212014-07-25 16:20:43 -07007195 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007196 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007197 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007198 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007199 mpClientInterface->setParameters(input, String8(param));
7200 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007201 }
jiabin12537fc2023-10-12 17:56:08 +00007202 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007203 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307204 ALOGW("%s direct input missing param for profile %s", __func__,
7205 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007206 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007207 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007208 }
7209
Eric Laurent0dd51852019-04-19 18:18:58 -07007210 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007211 addInput(input, desc);
7212 }
7213 } // endif input != 0
7214
Eric Laurentcf2c0212014-07-25 16:20:43 -07007215 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307216 ALOGW("%s could not open input for device %s on profile %s", __func__,
7217 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007218 profiles.removeAt(profile_index);
7219 profile_index--;
7220 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007221 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007222 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007223 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307224 ALOGV("%s: adding input %d for profile %s", __func__,
7225 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007226
7227 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307228 ALOGV("%s: closing input %d for profile %s", __func__,
7229 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007230 closeInput(input);
7231 }
Eric Laurentd4692962014-05-05 18:13:44 -07007232 }
7233 } // end scan profiles
7234
7235 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007236 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007237 return BAD_VALUE;
7238 }
7239 } else {
7240 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007241 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007242 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007243 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007244 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007245 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007246 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007247 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307248 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7249 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007250 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007251 }
7252 }
7253 }
7254 } // end disconnect
7255
7256 return NO_ERROR;
7257}
7258
7259
Eric Laurente0720872014-03-11 09:30:41 -07007260void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007261{
7262 ALOGV("closeOutput(%d)", output);
7263
François Gaffie1c878552018-11-22 16:53:21 +01007264 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7265 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007266 ALOGW("closeOutput() unknown output %d", output);
7267 return;
7268 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007269 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007270 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007271
Eric Laurente552edb2014-03-10 17:42:56 -07007272 // look for duplicated outputs connected to the output being removed.
7273 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007274 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7275 if (dupOutput->isDuplicated() &&
7276 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7277 sp<SwAudioOutputDescriptor> remainingOutput =
7278 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007279 // As all active tracks on duplicated output will be deleted,
7280 // and as they were also referenced on the other output, the reference
7281 // count for their stream type must be adjusted accordingly on
7282 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007283 const bool wasActive = remainingOutput->isActive();
7284 // Note: no-op on the closing output where all clients has already been set inactive
7285 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007286 // stop() will be a no op if the output is still active but is needed in case all
7287 // active streams refcounts where cleared above
7288 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007289 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007290 }
Eric Laurente552edb2014-03-10 17:42:56 -07007291 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7292 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7293
7294 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007295 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007296 }
7297 }
7298
Eric Laurent05b90f82014-08-27 15:32:29 -07007299 nextAudioPortGeneration();
7300
François Gaffie1c878552018-11-22 16:53:21 +01007301 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007302 if (index >= 0) {
7303 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007304 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7305 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007306 mAudioPatches.removeItemsAt(index);
7307 mpClientInterface->onAudioPatchListUpdate();
7308 }
7309
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007310 if (closingOutputWasActive) {
7311 closingOutput->stop();
7312 }
François Gaffie1c878552018-11-22 16:53:21 +01007313 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007314 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007315 for (const auto device : closingOutput->devices()) {
7316 device->setPreferredConfig(nullptr);
7317 }
7318 }
Eric Laurente552edb2014-03-10 17:42:56 -07007319
François Gaffie53615e22015-03-19 09:24:12 +01007320 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007321 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007322 if (closingOutput == mSpatializerOutput) {
7323 mSpatializerOutput.clear();
7324 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007325
7326 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7327 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007328 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007329 bool directOutputOpen = false;
7330 for (size_t i = 0; i < mOutputs.size(); i++) {
7331 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7332 directOutputOpen = true;
7333 break;
7334 }
7335 }
7336 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007337 ALOGV("no direct outputs open, reset MSD patches");
7338 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7339 // how output devices for patching are resolved. Avoid by caching and reusing the
7340 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7341 // devices to patch to. This may be complicated by the fact that devices may become
7342 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007343 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007344 }
7345 }
jiabin220eea12024-05-17 17:55:20 +00007346
7347 if (closingOutput->mPreferredAttrInfo != nullptr) {
7348 closingOutput->mPreferredAttrInfo->resetActiveClient();
7349 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007350}
7351
7352void AudioPolicyManager::closeInput(audio_io_handle_t input)
7353{
7354 ALOGV("closeInput(%d)", input);
7355
7356 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7357 if (inputDesc == NULL) {
7358 ALOGW("closeInput() unknown input %d", input);
7359 return;
7360 }
7361
Eric Laurent6a94d692014-05-20 11:18:06 -07007362 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007363
François Gaffie11d30102018-11-02 16:09:09 +01007364 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007365 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007366 if (index >= 0) {
7367 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007368 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7369 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007370 mAudioPatches.removeItemsAt(index);
7371 mpClientInterface->onAudioPatchListUpdate();
7372 }
7373
François Gaffie6ebbce02023-07-19 13:27:53 +02007374 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007375 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007376 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007377
François Gaffie11d30102018-11-02 16:09:09 +01007378 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7379 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007380 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007381 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007382 }
Eric Laurente552edb2014-03-10 17:42:56 -07007383}
7384
François Gaffie11d30102018-11-02 16:09:09 +01007385SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7386 const DeviceVector &devices,
7387 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007388{
7389 SortedVector<audio_io_handle_t> outputs;
7390
François Gaffie11d30102018-11-02 16:09:09 +01007391 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007392 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007393 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007394 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007395 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007396 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007397 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007398 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007399 outputs.add(openOutputs.keyAt(i));
7400 }
7401 }
7402 return outputs;
7403}
7404
Mikhail Naganov37977152018-07-11 15:54:44 -07007405void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7406{
7407 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7408 // output is suspended before any tracks are moved to it
7409 checkA2dpSuspend();
7410 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007411 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007412 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007413 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007414 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007415 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7416 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7417 // configuration changes will ultimately be rerouted correctly. We can still avoid
7418 // unnecessary rerouting by caching and reusing the arguments to
7419 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7420 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007421 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007422 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007423 // an event that changed routing likely occurred, inform upper layers
7424 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007425}
7426
François Gaffiec005e562018-11-06 15:04:49 +01007427bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7428 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007429{
François Gaffiec005e562018-11-06 15:04:49 +01007430 return mEngine->getProductStrategyForAttributes(lAttr) ==
7431 mEngine->getProductStrategyForAttributes(rAttr);
7432}
7433
Francois Gaffieff1eb522020-05-06 18:37:04 +02007434void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7435{
7436 for (size_t i = 0; i < mAudioSources.size(); i++) {
7437 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7438 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007439 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007440 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007441 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007442 }
7443 }
7444}
7445
7446void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7447{
7448 for (size_t i = 0; i < mAudioSources.size(); i++) {
7449 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7450 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7451 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7452 disconnectAudioSource(sourceDesc);
7453 }
7454 }
7455}
7456
François Gaffiec005e562018-11-06 15:04:49 +01007457void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7458{
7459 auto psId = mEngine->getProductStrategyForAttributes(attr);
7460
7461 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7462 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007463
François Gaffie11d30102018-11-02 16:09:09 +01007464 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7465 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007466
Eric Laurentc209fe42020-06-05 18:11:23 -07007467 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007468 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007469 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007470 // take into account dynamic audio policies related changes: if a client is now associated
7471 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007472 // invalidate clients on outputs that do not support all the newly selected devices for the
7473 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007474 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007475 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007476 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007477 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007478 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007479
Eric Laurentc209fe42020-06-05 18:11:23 -07007480 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7481 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7482 continue;
7483 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007484 if (!desc->supportsAllDevices(newDevices)) {
7485 invalidatedOutputs.push_back(desc);
7486 break;
7487 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007488 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007489 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007490 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7491 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7492 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007493 if (status == OK) {
7494 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7495 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7496 maxLatency = desc->latency();
7497 }
7498 invalidatedOutputs.push_back(desc);
7499 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007500 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007501 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007502 }
7503 }
7504
Eric Laurent56ed8842022-11-15 16:04:41 +01007505 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007506 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7507 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007508 for (audio_io_handle_t srcOut : srcOutputs) {
7509 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007510 if (desc == nullptr) continue;
7511
7512 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007513 maxLatency = desc->latency();
7514 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007515
Eric Laurent56ed8842022-11-15 16:04:41 +01007516 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007517 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007518 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007519 // a client on a non direct outputs has necessarily a linear PCM format
7520 // so we can call selectOutput() safely
7521 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7522 client->flags(),
7523 client->config().format,
7524 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007525 client->config().sample_rate,
7526 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007527 if (newOutput != srcOut) {
7528 invalidate = true;
7529 break;
7530 }
7531 } else {
7532 sp<IOProfile> profile = getProfileForOutput(newDevices,
7533 client->config().sample_rate,
7534 client->config().format,
7535 client->config().channel_mask,
7536 client->flags(),
7537 true /* directOnly */);
7538 if (profile != desc->mProfile) {
7539 invalidate = true;
7540 break;
7541 }
7542 }
7543 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007544 // mute strategy while moving tracks from one output to another
7545 if (invalidate) {
7546 invalidatedOutputs.push_back(desc);
7547 if (desc->isStrategyActive(psId)) {
7548 setStrategyMute(psId, true, desc);
7549 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7550 newDevices.types());
7551 }
Eric Laurente552edb2014-03-10 17:42:56 -07007552 }
François Gaffiec005e562018-11-06 15:04:49 +01007553 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007554 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007555 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007556 }
Eric Laurente552edb2014-03-10 17:42:56 -07007557 }
7558
Eric Laurent56ed8842022-11-15 16:04:41 +01007559 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7560 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7561 std::to_string(srcOutputs[0]).c_str(),
7562 std::to_string(dstOutputs[0]).c_str());
7563
François Gaffiec005e562018-11-06 15:04:49 +01007564 // Move effects associated to this stream from previous output to new output
7565 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007566 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007567 }
François Gaffiec005e562018-11-06 15:04:49 +01007568 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007569 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007570 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007571 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007572 desc->setTracksInvalidatedStatusByStrategy(psId);
7573 }
Eric Laurente552edb2014-03-10 17:42:56 -07007574 }
7575 }
7576}
7577
Eric Laurente0720872014-03-11 09:30:41 -07007578void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007579{
François Gaffiec005e562018-11-06 15:04:49 +01007580 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7581 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7582 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007583 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007584 }
Eric Laurente552edb2014-03-10 17:42:56 -07007585}
7586
Kevin Rocard153f92d2018-12-18 18:33:28 -08007587void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007588 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007589 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007590 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007591 for (size_t i = 0; i < mOutputs.size(); i++) {
7592 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7593 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007594 sp<AudioPolicyMix> primaryMix;
7595 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007596 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007597 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7598 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7599 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007600 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7601 for (auto &secondaryMix : secondaryMixes) {
7602 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7603 if (outputDesc != nullptr &&
7604 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7605 secondaryDescs.push_back(outputDesc);
7606 }
7607 }
7608
jiabinc44b3462022-12-08 12:52:31 -08007609 if (status != OK &&
7610 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7611 // When it failed to query secondary output, only invalidate the client that is not
7612 // MMAP. The reason is that MMAP stream will not support secondary output.
7613 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007614 } else if (!std::equal(
7615 client->getSecondaryOutputs().begin(),
7616 client->getSecondaryOutputs().end(),
7617 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007618 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7619 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007620 // If the format is not PCM, the tracks should be invalidated to get correct
7621 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007622 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007623 } else {
7624 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7625 std::vector<audio_io_handle_t> secondaryOutputIds;
7626 for (const auto &secondaryDesc: secondaryDescs) {
7627 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7628 weakSecondaryDescs.push_back(secondaryDesc);
7629 }
7630 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7631 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007632 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007633 }
7634 }
7635 }
jiabin10a03f12021-05-07 23:46:28 +00007636 if (!trackSecondaryOutputs.empty()) {
7637 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7638 }
jiabinc44b3462022-12-08 12:52:31 -08007639 if (!clientsToInvalidate.empty()) {
7640 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7641 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007642 }
7643}
7644
Eric Laurent2517af32020-11-25 15:31:27 +01007645bool AudioPolicyManager::isScoRequestedForComm() const {
7646 AudioDeviceTypeAddrVector devices;
7647 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7648 for (const auto &device : devices) {
7649 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7650 return true;
7651 }
7652 }
7653 return false;
7654}
7655
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007656bool AudioPolicyManager::isHearingAidUsedForComm() const {
7657 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7658 true /*fromCache*/);
7659 for (const auto &device : devices) {
7660 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7661 return true;
7662 }
7663 }
7664 return false;
7665}
7666
7667
Eric Laurente0720872014-03-11 09:30:41 -07007668void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007669{
François Gaffie53615e22015-03-19 09:24:12 +01007670 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007671 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007672 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007673 return;
7674 }
7675
Eric Laurent3a4311c2014-03-17 12:00:47 -07007676 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007677 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7678 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007679 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007680
7681 // if suspended, restore A2DP output if:
7682 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007683 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007684 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007685 //
Eric Laurentf732e072016-08-03 19:30:28 -07007686 // if not suspended, suspend A2DP output if:
7687 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007688 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007689 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007690 //
7691 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007692 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007693 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007694 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007695 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007696
7697 mpClientInterface->restoreOutput(a2dpOutput);
7698 mA2dpSuspended = false;
7699 }
7700 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007701 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007702 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007703 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007704 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007705
7706 mpClientInterface->suspendOutput(a2dpOutput);
7707 mA2dpSuspended = true;
7708 }
7709 }
7710}
7711
François Gaffie11d30102018-11-02 16:09:09 +01007712DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7713 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007714{
François Gaffiedb1755b2023-09-01 11:50:35 +02007715 if (outputDesc == nullptr) {
7716 return DeviceVector{};
7717 }
François Gaffie11d30102018-11-02 16:09:09 +01007718
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007719 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007720 if (index >= 0) {
7721 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007722 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007723 ALOGV("%s device %s forced by patch %d", __func__,
7724 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7725 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007726 }
7727 }
7728
Dean Wheatley514b4312020-06-17 21:45:00 +10007729 // Do not retrieve engine device for outputs through MSD
7730 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7731 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7732 return outputDesc->devices();
7733 }
7734
Eric Laurent97ac8712018-07-27 18:59:02 -07007735 // Honor explicit routing requests only if no client using default routing is active on this
7736 // input: a specific app can not force routing for other apps by setting a preferred device.
7737 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007738 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007739 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007740 if (device != nullptr) {
7741 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007742 }
7743
François Gaffiea807ef92018-11-05 10:44:33 +01007744 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7745 // of setForceUse / Default Bus device here
7746 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7747 if (device != nullptr) {
7748 return DeviceVector(device);
7749 }
7750
François Gaffiedb1755b2023-09-01 11:50:35 +02007751 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007752 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7753 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307754 auto hasStreamActive = [&](auto stream) {
7755 return hasStream(streams, stream) && isStreamActive(stream, 0);
7756 };
Eric Laurent484e9272018-06-07 17:29:23 -07007757
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307758 auto doGetOutputDevicesForVoice = [&]() {
7759 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007760 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307761 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007762 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7763 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307764 };
7765
7766 // With low-latency playing on speaker, music on WFD, when the first low-latency
7767 // output is stopped, getNewOutputDevices checks for a product strategy
7768 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007769 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307770 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7771 // stream is associated to the output descriptor.
7772 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7773 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7774 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7775 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007776 // Retrieval of devices for voice DL is done on primary output profile, cannot
7777 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007778 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007779 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7780 break;
7781 }
Eric Laurente552edb2014-03-10 17:42:56 -07007782 }
François Gaffiec005e562018-11-06 15:04:49 +01007783 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007784 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007785}
7786
François Gaffie11d30102018-11-02 16:09:09 +01007787sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7788 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007789{
François Gaffie11d30102018-11-02 16:09:09 +01007790 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007791
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007792 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007793 if (index >= 0) {
7794 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007795 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007796 ALOGV("getNewInputDevice() device %s forced by patch %d",
7797 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7798 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007799 }
7800 }
7801
Eric Laurent97ac8712018-07-27 18:59:02 -07007802 // Honor explicit routing requests only if no client using default routing is active on this
7803 // input: a specific app can not force routing for other apps by setting a preferred device.
7804 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007805 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7806 if (device != nullptr) {
7807 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007808 }
7809
Eric Laurentdc95a252018-04-12 12:46:56 -07007810 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007811 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007812 audio_attributes_t attributes;
7813 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007814 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007815 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7816 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007817 attributes = topClient->attributes();
7818 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007819 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007820 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007821 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7822 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007823 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007824 }
7825
Francois Gaffie716e1432019-01-14 16:58:59 +01007826 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7827 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007828 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007829 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007830 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007831 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007832
Eric Laurente552edb2014-03-10 17:42:56 -07007833 return device;
7834}
7835
Eric Laurent794fde22016-03-11 09:50:45 -08007836bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7837 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007838 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007839}
7840
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007841status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007842 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007843 if (devices == nullptr) {
7844 return BAD_VALUE;
7845 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007846
Andy Hung6d23c0f2022-02-16 09:37:15 -08007847 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007848 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7849 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007850 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007851 for (const auto& device : curDevices) {
7852 devices->push_back(device->getDeviceTypeAddr());
7853 }
7854 return NO_ERROR;
7855}
7856
Eric Laurente0720872014-03-11 09:30:41 -07007857void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007858 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007859 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007860 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007861 updateDevicesAndOutputs();
7862 break;
7863 default:
7864 break;
7865 }
7866}
7867
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007868uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007869
7870 // skip beacon mute management if a dedicated TTS output is available
7871 if (mTtsOutputAvailable) {
7872 return 0;
7873 }
7874
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007875 switch(event) {
7876 case STARTING_OUTPUT:
7877 mBeaconMuteRefCount++;
7878 break;
7879 case STOPPING_OUTPUT:
7880 if (mBeaconMuteRefCount > 0) {
7881 mBeaconMuteRefCount--;
7882 }
7883 break;
7884 case STARTING_BEACON:
7885 mBeaconPlayingRefCount++;
7886 break;
7887 case STOPPING_BEACON:
7888 if (mBeaconPlayingRefCount > 0) {
7889 mBeaconPlayingRefCount--;
7890 }
7891 break;
7892 }
7893
7894 if (mBeaconMuteRefCount > 0) {
7895 // any playback causes beacon to be muted
7896 return setBeaconMute(true);
7897 } else {
7898 // no other playback: unmute when beacon starts playing, mute when it stops
7899 return setBeaconMute(mBeaconPlayingRefCount == 0);
7900 }
7901}
7902
7903uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7904 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7905 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7906 // keep track of muted state to avoid repeating mute/unmute operations
7907 if (mBeaconMuted != mute) {
7908 // mute/unmute AUDIO_STREAM_TTS on all outputs
7909 ALOGV("\t muting %d", mute);
7910 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007911 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7912 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7913 ALOGV("\t no tts volume source available");
7914 return 0;
7915 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007916 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007917 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007918 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007919 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007920 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007921 maxLatency = latency;
7922 }
7923 }
7924 mBeaconMuted = mute;
7925 return maxLatency;
7926 }
7927 return 0;
7928}
7929
Eric Laurente0720872014-03-11 09:30:41 -07007930void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007931{
François Gaffiec005e562018-11-06 15:04:49 +01007932 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007933 mPreviousOutputs = mOutputs;
7934}
7935
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007936uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007937 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007938 uint32_t delayMs)
7939{
7940 // mute/unmute strategies using an incompatible device combination
7941 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7942 // if unmuting, unmute only after the specified delay
7943 if (outputDesc->isDuplicated()) {
7944 return 0;
7945 }
7946
7947 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007948 DeviceVector devices = outputDesc->devices();
7949 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007950
François Gaffiec005e562018-11-06 15:04:49 +01007951 auto productStrategies = mEngine->getOrderedProductStrategies();
7952 for (const auto &productStrategy : productStrategies) {
7953 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7954 DeviceVector curDevices =
7955 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7956 curDevices = curDevices.filter(outputDesc->supportedDevices());
7957 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007958 bool doMute = false;
7959
François Gaffiec005e562018-11-06 15:04:49 +01007960 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007961 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007962 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7963 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007964 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007965 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007966 }
Eric Laurent99401132014-05-07 19:48:15 -07007967 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007968 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007969 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007970 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007971 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007972 continue;
7973 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307974 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007975 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7976 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7977 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007978 if (mute) {
7979 // FIXME: should not need to double latency if volume could be applied
7980 // immediately by the audioflinger mixer. We must account for the delay
7981 // between now and the next time the audioflinger thread for this output
7982 // will process a buffer (which corresponds to one buffer size,
7983 // usually 1/2 or 1/4 of the latency).
7984 if (muteWaitMs < desc->latency() * 2) {
7985 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007986 }
7987 }
7988 }
7989 }
7990 }
7991 }
7992
Eric Laurent99401132014-05-07 19:48:15 -07007993 // temporary mute output if device selection changes to avoid volume bursts due to
7994 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007995 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007996 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007997
Eric Laurentdc462862016-07-19 12:29:53 -07007998 if (muteWaitMs < tempMuteWaitMs) {
7999 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07008000 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008001
8002 // If recommended duration is defined, replace temporary mute duration to avoid
8003 // truncated notifications at beginning, which depends on duration of changing path in HAL.
8004 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
8005 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
8006 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
8007 tempRecommendedMuteDuration : outputDesc->latency() * 4;
8008
François Gaffieaaac0fd2018-11-22 17:56:39 +01008009 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
8010 // make sure that we do not start the temporary mute period too early in case of
8011 // delayed device change
8012 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
8013 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01008014 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07008015 }
8016 }
8017
Eric Laurente552edb2014-03-10 17:42:56 -07008018 // wait for the PCM output buffers to empty before proceeding with the rest of the command
8019 if (muteWaitMs > delayMs) {
8020 muteWaitMs -= delayMs;
8021 usleep(muteWaitMs * 1000);
8022 return muteWaitMs;
8023 }
8024 return 0;
8025}
8026
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308027uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
8028 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01008029 const DeviceVector &devices,
8030 bool force,
8031 int delayMs,
8032 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008033 bool requiresMuteCheck, bool requiresVolumeCheck,
8034 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07008035{
jiabin3ff8d7d2022-12-13 06:27:44 +00008036 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308037 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
8038 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
8039 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008040 uint32_t muteWaitMs;
8041
8042 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308043 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008044 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308045 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008046 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07008047 return muteWaitMs;
8048 }
Eric Laurente552edb2014-03-10 17:42:56 -07008049
8050 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01008051 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008052 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02008053 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008054
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308055 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
8056 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01008057
8058 if (!filteredDevices.isEmpty()) {
8059 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008060 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008061
8062 // if the outputs are not materially active, there is no need to mute.
8063 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01008064 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008065 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308066 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
8067 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008068 muteWaitMs = 0;
8069 }
Eric Laurente552edb2014-03-10 17:42:56 -07008070
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008071 bool outputRouted = outputDesc->isRouted();
8072
Eric Laurent79ea9582020-06-11 18:49:24 -07008073 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8074 // output profile or if new device is not supported AND previous device(s) is(are) still
8075 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02008076 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308077 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8078 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07008079 // restore previous device after evaluating strategy mute state
8080 outputDesc->setDevices(prevDevices);
8081 return muteWaitMs;
8082 }
8083
Eric Laurente552edb2014-03-10 17:42:56 -07008084 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008085 // the requested device is AUDIO_DEVICE_NONE
8086 // OR the requested device is the same as current device
8087 // AND force is not specified
8088 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008089 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008090 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308091 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8092 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8093 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008094 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308095 ALOGV("%s %s setting same device on routed output, force apply volumes",
8096 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008097 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8098 }
Eric Laurente552edb2014-03-10 17:42:56 -07008099 return muteWaitMs;
8100 }
8101
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308102 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8103 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008104
Eric Laurente552edb2014-03-10 17:42:56 -07008105 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008106 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008107 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008108 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008109 PatchBuilder patchBuilder;
8110 patchBuilder.addSource(outputDesc);
8111 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8112 for (const auto &filteredDevice : filteredDevices) {
8113 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008114 }
8115
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008116 // Add half reported latency to delayMs when muteWaitMs is null in order
8117 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008118 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8119 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8120 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008121 }
Eric Laurente552edb2014-03-10 17:42:56 -07008122
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008123 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8124 if (!skipMuteDelay) {
8125 // update stream volumes according to new device
8126 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8127 }
Eric Laurente552edb2014-03-10 17:42:56 -07008128
8129 return muteWaitMs;
8130}
8131
Eric Laurentc75307b2015-03-17 15:29:32 -07008132status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008133 int delayMs,
8134 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008135{
Eric Laurent6a94d692014-05-20 11:18:06 -07008136 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008137 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8138 return INVALID_OPERATION;
8139 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008140 if (patchHandle) {
8141 index = mAudioPatches.indexOfKey(*patchHandle);
8142 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008143 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008144 }
8145 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008146 return INVALID_OPERATION;
8147 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008148 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008149 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008150 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008151 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008152 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008153 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008154 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008155 return status;
8156}
8157
8158status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008159 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008160 bool force,
8161 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008162{
8163 status_t status = NO_ERROR;
8164
Eric Laurent1f2f2232014-06-02 12:01:23 -07008165 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008166 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8167 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008168
François Gaffie11d30102018-11-02 16:09:09 +01008169 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008170 PatchBuilder patchBuilder;
8171 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008172 // AUDIO_SOURCE_HOTWORD is for internal use only:
8173 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008174 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8175 auto result = usecase;
8176 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8177 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8178 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008179 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008180 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008181 if (audio_is_remote_submix_device(device->type())) {
8182 // remote submix HAL does not support audio conversion, need source device
8183 // audio config to match the sink input descriptor audio config, otherwise AIDL
8184 // HAL patching will fail
8185 audio_port_config srcDevicePortConfig = {};
8186 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8187 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8188 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8189 srcDevicePortConfig.format = inputDesc->getFormat();
8190 patchBuilder.addSource(srcDevicePortConfig);
8191 } else {
8192 patchBuilder.addSource(device);
8193 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008194 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008195 }
8196 }
8197 return status;
8198}
8199
Eric Laurent6a94d692014-05-20 11:18:06 -07008200status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8201 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008202{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008203 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008204 ssize_t index;
8205 if (patchHandle) {
8206 index = mAudioPatches.indexOfKey(*patchHandle);
8207 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008208 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008209 }
8210 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008211 return INVALID_OPERATION;
8212 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008213 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008214 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008215 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008216 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008217 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008218 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008219 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008220 return status;
8221}
8222
François Gaffie11d30102018-11-02 16:09:09 +01008223sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008224 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008225 audio_format_t& format,
8226 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008227 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008228{
8229 // Choose an input profile based on the requested capture parameters: select the first available
8230 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008231 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008232
Atneya Nair0f0a8032022-12-12 16:20:12 -08008233 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8234 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8235 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8236
8237 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008238
jiabin2fd710d2022-05-02 23:20:22 +00008239 for (;;) {
8240 sp<IOProfile> firstInexact = nullptr;
jiabin5e02d2b2024-09-23 19:26:19 +00008241 uint32_t inexactSamplingRate = 0;
8242 audio_format_t inexactFormat = AUDIO_FORMAT_INVALID;
8243 audio_channel_mask_t inexactChannelMask = AUDIO_CHANNEL_INVALID;
jiabin2fd710d2022-05-02 23:20:22 +00008244 uint32_t updatedSamplingRate = 0;
8245 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8246 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8247 for (const auto& hwModule : mHwModules) {
8248 for (const auto& profile : hwModule->getInputProfiles()) {
8249 // profile->log();
8250 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008251 if (profile->getCompatibilityScore(
8252 DeviceVector(device),
8253 samplingRate,
8254 &updatedSamplingRate,
8255 format,
8256 &updatedFormat,
8257 channelMask,
8258 &updatedChannelMask,
8259 // FIXME ugly cast
8260 (audio_output_flags_t) flags,
8261 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8262 samplingRate = updatedSamplingRate;
8263 format = updatedFormat;
8264 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008265 return profile;
8266 }
jiabin66acc432024-02-06 00:57:36 +00008267 if (firstInexact == nullptr
8268 && profile->getCompatibilityScore(
8269 DeviceVector(device),
8270 samplingRate,
8271 &updatedSamplingRate,
8272 format,
8273 &updatedFormat,
8274 channelMask,
8275 &updatedChannelMask,
8276 // FIXME ugly cast
8277 (audio_output_flags_t) flags,
8278 false /*exactMatchRequiredForInputFlags*/)
8279 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008280 firstInexact = profile;
jiabin5e02d2b2024-09-23 19:26:19 +00008281 inexactSamplingRate = updatedSamplingRate;
8282 inexactFormat = updatedFormat;
8283 inexactChannelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008284 }
8285 }
8286 }
8287
8288 if (firstInexact != nullptr) {
jiabin5e02d2b2024-09-23 19:26:19 +00008289 samplingRate = inexactSamplingRate;
8290 format = inexactFormat;
8291 channelMask = inexactChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008292 return firstInexact;
8293 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8294 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8295 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8296 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8297 flags = AUDIO_INPUT_FLAG_NONE;
8298 } else { // fail
8299 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8300 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8301 samplingRate, format, channelMask, oriFlags);
8302 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008303 }
8304 }
jiabin2fd710d2022-05-02 23:20:22 +00008305
8306 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008307}
8308
Vlad Popa87e0e582024-05-20 18:49:20 -07008309float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8310 VolumeSource volumeSource,
8311 int index,
8312 const DeviceTypeSet &deviceTypes)
8313{
8314 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8315 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8316 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8317
8318 if (com_android_media_audio_abs_volume_index_fix()) {
8319 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8320 mAbsoluteVolumeDrivingStreams.end()) {
8321 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8322 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8323 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8324 ALOGD("%s: no group matching with %s", __FUNCTION__,
8325 toString(attributesToDriveAbs).c_str());
8326 return volumeDb;
8327 }
8328
8329 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8330 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8331 if (vsToDriveAbs == volumeSource) {
8332 // attenuation is applied by the abs volume controller
Eric Laurent64e868f2024-06-28 16:42:49 +00008333 return (index != 0) ? volumeDbMax : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008334 } else {
8335 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8336 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8337 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8338 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8339 curvesAbs.getVolumeIndexMax());
8340 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8341 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8342 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8343 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8344 return newVolumeDb;
8345 }
8346 }
8347 return volumeDb;
8348 } else {
8349 return volumeDb;
8350 }
8351}
8352
François Gaffieaaac0fd2018-11-22 17:56:39 +01008353float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8354 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008355 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008356 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008357 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008358 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008359{
Vlad Popa9d482762024-06-21 16:40:23 -07008360 float volumeDb;
8361 if (adjustAttenuation) {
8362 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8363 } else {
8364 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8365 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008366 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8367 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8368
8369 if (!computeInternalInteraction) {
8370 return volumeDb;
8371 }
8372
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008373 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8374 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8375 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8376 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008377 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8378 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8379 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8380 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8381 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008382 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008383 mOutputs.isActive(ringVolumeSrc, 0)) {
8384 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008385 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008386 adjustAttenuation,
8387 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008388 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008389 }
8390
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008391 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008392 if ((volumeSource != callVolumeSrc && (isInCall() ||
8393 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008394 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008395 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8396 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008397 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8398 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8399 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008400 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008401 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008402 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008403 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008404 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008405 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008406 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008407 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8408 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8409 // programmatically muted.
8410 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8411 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8412 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008413 bool exemptFromCapping =
8414 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8415 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008416 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8417 volumeSource, volumeDb);
8418 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008419 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8420 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8421 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008422 }
8423 }
Eric Laurente552edb2014-03-10 17:42:56 -07008424 // if a headset is connected, apply the following rules to ring tones and notifications
8425 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008426 // - always attenuate notifications volume by 6dB
8427 // - attenuate ring tones volume by 6dB unless music is not playing and
8428 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008429 // - if music is playing, always limit the volume to current music volume,
8430 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008431 if (!Intersection(deviceTypes,
8432 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8433 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008434 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8435 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008436 ((volumeSource == alarmVolumeSrc ||
8437 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008438 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8439 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8440 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008441 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8442 curves.canBeMuted()) {
8443
Eric Laurente552edb2014-03-10 17:42:56 -07008444 // when the phone is ringing we must consider that music could have been paused just before
8445 // by the music application and behave as if music was active if the last music track was
8446 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008447 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8448 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008449 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008450 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008451 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8452 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008453 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008454 float musicVolDb = computeVolume(musicCurves,
8455 musicVolumeSrc,
8456 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008457 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008458 adjustAttenuation,
8459 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008460 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8461 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8462 if (volumeDb > minVolDb) {
8463 volumeDb = minVolDb;
8464 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008465 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008466 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8467 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008468 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8469 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8470 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8471 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008472 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008473 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008474 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8475 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008476 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8477 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008478 }
8479 }
jiabin9a3361e2019-10-01 09:38:30 -07008480 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008481 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008482 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008483 }
8484 }
8485
François Gaffie43c73442018-11-08 08:21:55 +01008486 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008487}
8488
Eric Laurent3839bc02018-07-10 18:33:34 -07008489int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008490 VolumeSource fromVolumeSource,
8491 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008492{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008493 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008494 return srcIndex;
8495 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008496 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8497 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008498 float minSrc = (float)srcCurves.getVolumeIndexMin();
8499 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8500 float minDst = (float)dstCurves.getVolumeIndexMin();
8501 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008502
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008503 // preserve mute request or correct range
8504 if (srcIndex < minSrc) {
8505 if (srcIndex == 0) {
8506 return 0;
8507 }
8508 srcIndex = minSrc;
8509 } else if (srcIndex > maxSrc) {
8510 srcIndex = maxSrc;
8511 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008512 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8513}
8514
François Gaffieaaac0fd2018-11-22 17:56:39 +01008515status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8516 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008517 int index,
8518 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008519 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008520 int delayMs,
8521 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008522{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008523 // APM is single threaded, and single instance.
8524 static std::set<IVolumeCurves*> invalidCurvesReported;
8525
François Gaffieaaac0fd2018-11-22 17:56:39 +01008526 // do not change actual attributes volume if the attributes is muted
8527 if (outputDesc->isMuted(volumeSource)) {
8528 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8529 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008530 return NO_ERROR;
8531 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008532
Eric Laurentae6e88c2024-01-10 14:42:57 +01008533 bool isVoiceVolSrc;
8534 bool isBtScoVolSrc;
8535 if (!isVolumeConsistentForCalls(
8536 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008537 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008538 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008539 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008540 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008541
jiabin9a3361e2019-10-01 09:38:30 -07008542 if (deviceTypes.empty()) {
8543 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008544 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008545 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008546 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008547 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008548
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008549 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008550 if (!invalidCurvesReported.count(&curves)) {
8551 invalidCurvesReported.insert(&curves);
8552 String8 dump;
8553 curves.dump(&dump);
8554 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8555 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008556 return BAD_VALUE;
8557 }
8558
jiabin9a3361e2019-10-01 09:38:30 -07008559 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
Eric Laurentc32e6692024-10-04 14:32:28 +00008560 const VolumeSource dtmfVolSrc = toVolumeSource(AUDIO_STREAM_DTMF, false);
jiabin9a3361e2019-10-01 09:38:30 -07008561 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008562 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurentc32e6692024-10-04 14:32:28 +00008563 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc
8564 || (isInCall() && (dtmfVolSrc == volumeSource))) &&
chenxin2095559032024-06-15 13:59:29 +08008565 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8566 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008567 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008568 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008569 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008570 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8571 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008572
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008573 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008574 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8575 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8576 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008577 }
Eric Laurente552edb2014-03-10 17:42:56 -07008578 return NO_ERROR;
8579}
8580
Eric Laurentae6e88c2024-01-10 14:42:57 +01008581void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008582 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008583 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008584 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008585 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008586 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008587 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8588 } else {
8589 voiceVolume = index == 0 ? 0.0 : 1.0;
8590 }
8591 if (voiceVolume != mLastVoiceVolume) {
8592 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8593 mLastVoiceVolume = voiceVolume;
8594 }
8595}
8596
8597bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8598 const DeviceTypeSet& deviceTypes,
8599 bool& isVoiceVolSrc,
8600 bool& isBtScoVolSrc,
8601 const char* caller) {
8602 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008603 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8604
Eric Laurentae6e88c2024-01-10 14:42:57 +01008605 const bool isScoRequested = isScoRequestedForComm();
8606 const bool isHAUsed = isHearingAidUsedForComm();
8607
Vlad Popa695b76b2024-06-14 16:49:25 -07008608 if (com_android_media_audio_replace_stream_bt_sco()) {
8609 ALOGV("%s stream bt sco is replaced, no volume consistency check for calls", __func__);
8610 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8611 (isScoRequested || isHAUsed);
8612 return true;
8613 }
8614
8615 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008616 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8617
8618 if ((callVolSrc != btScoVolSrc) &&
8619 ((isVoiceVolSrc && isScoRequested) ||
8620 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8621 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8622 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8623 volumeSource, isScoRequested ? " " : " not ");
8624 return false;
8625 }
8626 return true;
8627}
8628
Eric Laurentc75307b2015-03-17 15:29:32 -07008629void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008630 const DeviceTypeSet& deviceTypes,
8631 int delayMs,
8632 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008633{
jiabincd510522020-01-22 09:40:55 -08008634 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008635 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8636 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8637 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008638 curves.getVolumeIndex(deviceTypes),
8639 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008640 }
8641}
8642
François Gaffiec005e562018-11-06 15:04:49 +01008643void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8644 bool on,
8645 const sp<AudioOutputDescriptor>& outputDesc,
8646 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008647 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008648{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008649 std::vector<VolumeSource> sourcesToMute;
8650 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8651 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8652 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008653 VolumeSource source = toVolumeSource(attributes, false);
8654 if ((source != VOLUME_SOURCE_NONE) &&
8655 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8656 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008657 sourcesToMute.push_back(source);
8658 }
Eric Laurente552edb2014-03-10 17:42:56 -07008659 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008660 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008661 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008662 }
8663
Eric Laurente552edb2014-03-10 17:42:56 -07008664}
8665
François Gaffieaaac0fd2018-11-22 17:56:39 +01008666void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8667 bool on,
8668 const sp<AudioOutputDescriptor>& outputDesc,
8669 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008670 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008671{
jiabin9a3361e2019-10-01 09:38:30 -07008672 if (deviceTypes.empty()) {
8673 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008674 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008675 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008676 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008677 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008678 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008679 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008680 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8681 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008682 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008683 }
8684 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008685 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8686 // ignored
8687 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008688 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008689 if (!outputDesc->isMuted(volumeSource)) {
8690 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008691 return;
8692 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008693 if (outputDesc->decMuteCount(volumeSource) == 0) {
8694 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008695 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008696 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008697 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008698 delayMs);
8699 }
8700 }
8701}
8702
François Gaffie53615e22015-03-19 09:24:12 +01008703bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8704{
François Gaffiec005e562018-11-06 15:04:49 +01008705 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008706 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8707 return true;
8708 }
8709
8710 // has known usage?
8711 switch (paa->usage) {
8712 case AUDIO_USAGE_UNKNOWN:
8713 case AUDIO_USAGE_MEDIA:
8714 case AUDIO_USAGE_VOICE_COMMUNICATION:
8715 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8716 case AUDIO_USAGE_ALARM:
8717 case AUDIO_USAGE_NOTIFICATION:
8718 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8719 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8720 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8721 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8722 case AUDIO_USAGE_NOTIFICATION_EVENT:
8723 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8724 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8725 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8726 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008727 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008728 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008729 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008730 case AUDIO_USAGE_EMERGENCY:
8731 case AUDIO_USAGE_SAFETY:
8732 case AUDIO_USAGE_VEHICLE_STATUS:
8733 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008734 break;
8735 default:
8736 return false;
8737 }
8738 return true;
8739}
8740
François Gaffie2110e042015-03-24 08:41:51 +01008741audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8742{
8743 return mEngine->getForceUse(usage);
8744}
8745
Eric Laurent96d1dda2022-03-14 17:14:19 +01008746bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008747 return isStateInCall(mEngine->getPhoneState());
8748}
8749
Eric Laurent96d1dda2022-03-14 17:14:19 +01008750bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008751 return is_state_in_call(state);
8752}
8753
Eric Laurentf9cccec2022-11-16 19:12:00 +01008754bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008755 audio_mode_t mode = mEngine->getPhoneState();
8756 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008757 || (mode == AUDIO_MODE_CALL_SCREEN)
8758 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008759}
8760
Eric Laurentf9cccec2022-11-16 19:12:00 +01008761bool AudioPolicyManager::isInCallOrScreening() const {
8762 audio_mode_t mode = mEngine->getPhoneState();
8763 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8764}
8765
Eric Laurentd60560a2015-04-10 11:31:20 -07008766void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8767{
8768 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008769 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008770 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008771 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008772 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008773 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008774 }
8775 }
8776
8777 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8778 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8779 bool release = false;
8780 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8781 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8782 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8783 source->ext.device.type == deviceDesc->type()) {
8784 release = true;
8785 }
8786 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008787 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008788 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8789 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8790 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008791 sink->ext.device.type == deviceDesc->type() &&
8792 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8793 || strncmp(sink->ext.device.address, address,
8794 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008795 release = true;
8796 }
8797 }
8798 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008799 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8800 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008801 }
8802 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008803
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008804 mInputs.clearSessionRoutesForDevice(deviceDesc);
8805
Francois Gaffie716e1432019-01-14 16:58:59 +01008806 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008807}
8808
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008809void AudioPolicyManager::modifySurroundFormats(
8810 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008811 std::unordered_set<audio_format_t> enforcedSurround(
8812 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008813 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008814 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008815 allSurround.insert(pair.first);
8816 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8817 }
Phil Burk09bc4612016-02-24 15:58:15 -08008818
8819 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8820 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008821 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008822 // This is the resulting set of formats depending on the surround mode:
8823 // 'all surround' = allSurround
8824 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8825 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8826 // 'manual surround' = mManualSurroundFormats
8827 // AUTO: formats v 'enforced surround'
8828 // ALWAYS: formats v 'all surround' v 'enforced surround'
8829 // NEVER: formats ^ 'non-surround'
8830 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008831
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008832 std::unordered_set<audio_format_t> formatSet;
8833 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8834 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008835 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008836 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008837 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008838 formatSet.insert(*formatIter);
8839 }
8840 }
8841 } else {
8842 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8843 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008844 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008845
jiabin81772902018-04-02 17:52:27 -07008846 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008847 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008848 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8849 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8850 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008851 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008852 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8853 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8854 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008855 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008856 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008857 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008858 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008859 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008860 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008861}
8862
jiabin06e4bab2019-07-29 10:13:34 -07008863void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8864 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008865 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8866 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8867
8868 // If NEVER, then remove support for channelMasks > stereo.
8869 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008870 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8871 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008872 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008873 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008874 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008875 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008876 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008877 }
8878 }
jiabin81772902018-04-02 17:52:27 -07008879 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8880 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8881 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008882 bool supports5dot1 = false;
8883 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008884 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008885 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8886 supports5dot1 = true;
8887 break;
8888 }
8889 }
8890 // If not then add 5.1 support.
8891 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008892 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008893 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008894 }
Phil Burk09bc4612016-02-24 15:58:15 -08008895 }
8896}
8897
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008898void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008899 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008900 const sp<IOProfile>& profile) {
8901 if (!profile->hasDynamicAudioProfile()) {
8902 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008903 }
François Gaffie112b0af2015-11-19 16:13:25 +01008904
jiabin12537fc2023-10-12 17:56:08 +00008905 audio_port_v7 devicePort;
8906 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008907
jiabin12537fc2023-10-12 17:56:08 +00008908 audio_port_v7 mixPort;
8909 profile->toAudioPort(&mixPort);
8910 mixPort.ext.mix.handle = ioHandle;
8911
8912 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8913 if (status != NO_ERROR) {
8914 ALOGE("%s failed to query the attributes of the mix port", __func__);
8915 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008916 }
jiabin12537fc2023-10-12 17:56:08 +00008917
8918 std::set<audio_format_t> supportedFormats;
8919 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8920 supportedFormats.insert(mixPort.audio_profiles[i].format);
8921 }
8922 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8923 mReportedFormatsMap[devDesc] = formats;
8924
8925 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008926 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8927 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008928 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8929 modifySurroundFormats(devDesc, &formats);
8930 size_t modifiedNumProfiles = 0;
8931 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8932 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8933 formats.end()) {
8934 // Skip the format that is not present after modifying surround formats.
8935 continue;
8936 }
8937 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8938 sizeof(struct audio_profile));
8939 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8940 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8941 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8942 modifySurroundChannelMasks(&channels);
8943 std::copy(channels.begin(), channels.end(),
8944 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8945 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8946 }
8947 mixPort.num_audio_profiles = modifiedNumProfiles;
8948 }
8949 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008950}
Eric Laurentd60560a2015-04-10 11:31:20 -07008951
Mikhail Naganovdc769682018-05-04 15:34:08 -07008952status_t AudioPolicyManager::installPatch(const char *caller,
8953 audio_patch_handle_t *patchHandle,
8954 AudioIODescriptorInterface *ioDescriptor,
8955 const struct audio_patch *patch,
8956 int delayMs)
8957{
8958 ssize_t index = mAudioPatches.indexOfKey(
8959 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8960 *patchHandle : ioDescriptor->getPatchHandle());
8961 sp<AudioPatch> patchDesc;
8962 status_t status = installPatch(
8963 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8964 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008965 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008966 }
8967 return status;
8968}
8969
8970status_t AudioPolicyManager::installPatch(const char *caller,
8971 ssize_t index,
8972 audio_patch_handle_t *patchHandle,
8973 const struct audio_patch *patch,
8974 int delayMs,
8975 uid_t uid,
8976 sp<AudioPatch> *patchDescPtr)
8977{
8978 sp<AudioPatch> patchDesc;
8979 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8980 if (index >= 0) {
8981 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008982 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008983 }
8984
8985 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8986 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8987 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8988 if (status == NO_ERROR) {
8989 if (index < 0) {
8990 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008991 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008992 } else {
8993 patchDesc->mPatch = *patch;
8994 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008995 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008996 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008997 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008998 }
8999 nextAudioPortGeneration();
9000 mpClientInterface->onAudioPatchListUpdate();
9001 }
9002 if (patchDescPtr) *patchDescPtr = patchDesc;
9003 return status;
9004}
9005
jiabinbce0c1d2020-10-05 11:20:18 -07009006bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
9007{
9008 const TrackClientVector activeClients = output->getActiveClients();
9009 if (activeClients.empty()) {
9010 return true;
9011 }
9012 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
9013 if (index < 0) {
9014 ALOGE("%s, no audio patch found while there are active clients on output %d",
9015 __func__, output->getId());
9016 return false;
9017 }
9018 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
9019 DeviceVector routedDevices;
9020 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
9021 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
9022 patchDesc->mPatch.sinks[i].id);
9023 if (device == nullptr) {
9024 ALOGE("%s, no audio device found with id(%d)",
9025 __func__, patchDesc->mPatch.sinks[i].id);
9026 return false;
9027 }
9028 routedDevices.add(device);
9029 }
9030 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08009031 if (client->isInvalid()) {
9032 // No need to take care about invalidated clients.
9033 continue;
9034 }
jiabinbce0c1d2020-10-05 11:20:18 -07009035 sp<DeviceDescriptor> preferredDevice =
9036 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
9037 if (mEngine->getOutputDevicesForAttributes(
9038 client->attributes(), preferredDevice, false) == routedDevices) {
9039 return false;
9040 }
9041 }
9042 return true;
9043}
9044
9045sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01009046 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00009047 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
9048 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07009049{
9050 for (const auto& device : devices) {
9051 // TODO: This should be checking if the profile supports the device combo.
9052 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00009053 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
9054 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07009055 return nullptr;
9056 }
9057 }
9058 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
9059 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07009060 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00009061 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009062 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009063 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00009064 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07009065 return nullptr;
9066 }
jiabin14b50cc2023-12-13 19:01:52 +00009067 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
9068 auto portConfig = desc->getConfig();
9069 for (const auto& device : devices) {
9070 device->setPreferredConfig(&portConfig);
9071 }
9072 }
jiabinbce0c1d2020-10-05 11:20:18 -07009073
9074 // Here is where the out_set_parameters() for card & device gets called
9075 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
9076 const audio_devices_t deviceType = device->type();
9077 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00009078 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07009079 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
9080 mpClientInterface->setParameters(output, String8(param));
9081 free(param);
9082 }
jiabin12537fc2023-10-12 17:56:08 +00009083 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07009084 if (!profile->hasValidAudioProfile()) {
9085 ALOGW("%s() missing param", __func__);
9086 desc->close();
9087 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00009088 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
9089 // Reopen the output with the best audio profile picked by APM when the profile supports
9090 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07009091 desc->close();
9092 output = AUDIO_IO_HANDLE_NONE;
9093 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9094 profile->pickAudioProfile(
9095 config.sample_rate, config.channel_mask, config.format);
9096 config.offload_info.sample_rate = config.sample_rate;
9097 config.offload_info.channel_mask = config.channel_mask;
9098 config.offload_info.format = config.format;
9099
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009100 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07009101 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009102 if (status != NO_ERROR) {
9103 return nullptr;
9104 }
9105 }
9106
9107 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07009108 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
9109 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
9110 hwModule->getHalVersionMajor() >= 3) {
9111 setOutputDevices(__func__, desc, devices, true, 0, NULL);
9112 }
baek.kim -61c20122022-07-27 10:05:32 +00009113 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9114 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9115
jiabinbce0c1d2020-10-05 11:20:18 -07009116 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9117 sp<AudioPolicyMix> policyMix;
9118 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9119 policyMix->setOutput(desc);
9120 desc->mPolicyMix = policyMix;
9121 } else {
9122 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009123 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009124 }
9125
baek.kim -61c20122022-07-27 10:05:32 +00009126 } else if (hasPrimaryOutput() && speaker != nullptr
9127 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009128 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9129 // no duplicated output for:
9130 // - direct outputs
9131 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009132 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009133 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9134
9135 //TODO: configure audio effect output stage here
9136
9137 // open a duplicating output thread for the new output and the primary output
9138 sp<SwAudioOutputDescriptor> dupOutputDesc =
9139 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9140 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9141 if (status == NO_ERROR) {
9142 // add duplicated output descriptor
9143 addOutput(duplicatedOutput, dupOutputDesc);
9144 } else {
9145 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9146 mPrimaryOutput->mIoHandle, output);
9147 desc->close();
9148 removeOutput(output);
9149 nextAudioPortGeneration();
9150 return nullptr;
9151 }
9152 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009153 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9154 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9155 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009156 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009157 }
jiabinbce0c1d2020-10-05 11:20:18 -07009158 return desc;
9159}
9160
jiabinf1c73972022-04-14 16:28:52 -07009161status_t AudioPolicyManager::getDevicesForAttributes(
9162 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
wenyu zhang8558a332024-09-09 15:12:48 +00009163 // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9164 // over any usage or content type also present in attr.
9165 if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9166 attr.source != AUDIO_SOURCE_INVALID) {
9167 return getInputDevicesForAttributes(attr, devices);
9168 }
9169
jiabinf1c73972022-04-14 16:28:52 -07009170 // Devices are determined in the following precedence:
9171 //
9172 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9173 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9174 //
9175 // If no such dynamic policy then
9176 // 2) Devices containing an active client using setPreferredDevice
9177 // with same strategy as the attributes.
9178 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9179 //
9180 // If no corresponding active client with setPreferredDevice then
9181 // 3) Devices associated with the strategy determined by the attributes
9182 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9183 //
9184 // See related getOutputForAttrInt().
9185
9186 // check dynamic policies but only for primary descriptors (secondary not used for audible
9187 // audio routing, only used for duplication for playback capture)
9188 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009189 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009190 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009191 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9192 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9193 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009194 if (status != OK) {
9195 return status;
9196 }
9197
9198 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9199 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9200 // as they are unaffected by device/stream volume
9201 // (per SwAudioOutputDescriptor::isFixedVolume()).
9202 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9203 ) {
9204 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9205 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9206 devices.add(deviceDesc);
9207 } else {
9208 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9209 // which selects setPreferredDevice if active. This means forVolume call
9210 // will take an active setPreferredDevice, if such exists.
9211
9212 devices = mEngine->getOutputDevicesForAttributes(
9213 attr, nullptr /* preferredDevice */, false /* fromCache */);
9214 }
9215
9216 if (forVolume) {
9217 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9218 // for single volume control in AudioService (such relationship should exist if
9219 // SPEAKER_SAFE is present).
9220 //
9221 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9222 DeviceVector speakerSafeDevices =
9223 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9224 if (!speakerSafeDevices.isEmpty()) {
9225 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9226 devices.remove(speakerSafeDevices);
9227 }
9228 }
9229
9230 return NO_ERROR;
9231}
9232
wenyu zhang8558a332024-09-09 15:12:48 +00009233status_t AudioPolicyManager::getInputDevicesForAttributes(
9234 const audio_attributes_t &attr, DeviceVector &devices) {
9235 devices = DeviceVector(
9236 mEngine->getInputDeviceForAttributes(attr, 0 /*uid unknown here*/,
9237 AUDIO_SESSION_NONE,
9238 nullptr /* mix */));
9239 return NO_ERROR;
9240}
9241
jiabinf1c73972022-04-14 16:28:52 -07009242status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9243 AudioProfileVector& audioProfiles,
9244 uint32_t flags,
9245 bool isInput) {
9246 for (const auto& hwModule : mHwModules) {
9247 // the MSD module checks for different conditions
9248 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9249 continue;
9250 }
9251 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9252 : hwModule->getOutputProfiles();
9253 for (const auto& profile : ioProfiles) {
9254 if (!profile->areAllDevicesSupported(devices) ||
9255 !profile->isCompatibleProfileForFlags(
9256 flags, false /*exactMatchRequiredForInputFlags*/)) {
9257 continue;
9258 }
9259 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9260 }
9261 }
9262
9263 if (!isInput) {
9264 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9265 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9266 if (msdModule != nullptr) {
9267 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9268 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9269 for (const auto &profile: msdModule->getOutputProfiles()) {
9270 if (!profile->asAudioPort()->isDirectOutput()) {
9271 continue;
9272 }
9273 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9274 }
9275 } else {
9276 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9277 }
9278 }
9279 }
9280
9281 return NO_ERROR;
9282}
9283
jiabin3ff8d7d2022-12-13 06:27:44 +00009284sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9285 const audio_config_t *config,
9286 audio_output_flags_t flags,
9287 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009288 closeOutput(outputDesc->mIoHandle);
9289 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9290 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9291 if (preferredOutput == nullptr) {
9292 ALOGE("%s failed to reopen output device=%d, caller=%s",
9293 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009294 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009295 return preferredOutput;
9296}
9297
9298void AudioPolicyManager::reopenOutputsWithDevices(
9299 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9300 for (const auto& [output, devices] : outputsToReopen) {
9301 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9302 closeOutput(output);
9303 openOutputWithProfileAndDevice(desc->mProfile, devices);
9304 }
jiabina84c3d32022-12-02 18:59:55 +00009305}
9306
jiabinc44b3462022-12-08 12:52:31 -08009307PortHandleVector AudioPolicyManager::getClientsForStream(
9308 audio_stream_type_t streamType) const {
9309 PortHandleVector clients;
9310 for (size_t i = 0; i < mOutputs.size(); ++i) {
9311 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9312 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9313 }
9314 return clients;
9315}
9316
9317void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9318 PortHandleVector clients;
9319 for (auto stream : streams) {
9320 PortHandleVector clientsForStream = getClientsForStream(stream);
9321 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9322 }
9323 mpClientInterface->invalidateTracks(clients);
9324}
9325
jiabin220eea12024-05-17 17:55:20 +00009326void AudioPolicyManager::updateClientsInternalMute(
9327 const sp<android::SwAudioOutputDescriptor> &desc) {
9328 if (!desc->isBitPerfect() ||
9329 !com::android::media::audioserver::
9330 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9331 // This is only used for bit perfect output now.
9332 return;
9333 }
9334 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9335 bool bitPerfectClientInternalMute = false;
9336 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9337 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9338 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9339 bitPerfectClient = client;
9340 continue;
9341 }
9342 bool muted = false;
9343 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9344 // System sound is muted.
9345 muted = true;
9346 } else {
9347 bitPerfectClientInternalMute = true;
9348 }
9349 if (client->setInternalMute(muted)) {
9350 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9351 if (!result.ok()) {
9352 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9353 continue;
9354 }
9355 media::TrackInternalMuteInfo info;
9356 info.portId = result.value();
9357 info.muted = client->getInternalMute();
9358 clientsInternalMute.push_back(std::move(info));
9359 }
9360 }
9361 if (bitPerfectClient != nullptr &&
9362 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9363 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9364 if (result.ok()) {
9365 media::TrackInternalMuteInfo info;
9366 info.portId = result.value();
9367 info.muted = bitPerfectClient->getInternalMute();
9368 clientsInternalMute.push_back(std::move(info));
9369 } else {
9370 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9371 __func__, bitPerfectClient->portId());
9372 }
9373 }
9374 if (!clientsInternalMute.empty()) {
9375 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9376 status != NO_ERROR) {
9377 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9378 }
9379 }
9380}
9381
jiabin7ed22ff2024-10-04 20:51:21 +00009382status_t AudioPolicyManager::getMmapPolicyInfos(AudioMMapPolicyType policyType,
9383 std::vector<AudioMMapPolicyInfo> *policyInfos) {
9384 if (policyType != AudioMMapPolicyType::DEFAULT &&
9385 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9386 return BAD_VALUE;
9387 }
9388 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9389 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9390 return status;
9391 }
9392 }
9393 *policyInfos = mMmapPolicyInfos[policyType];
9394 return NO_ERROR;
9395}
9396
9397status_t AudioPolicyManager::getMmapPolicyForDevice(
9398 AudioMMapPolicyType policyType, AudioMMapPolicyInfo *policyInfo) {
9399 if (policyType != AudioMMapPolicyType::DEFAULT &&
9400 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9401 return BAD_VALUE;
9402 }
9403 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9404 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9405 return status;
9406 }
9407 }
9408 auto it = mMmapPolicyByDeviceType[policyType].find(policyInfo->device.type);
9409 policyInfo->mmapPolicy = it == mMmapPolicyByDeviceType[policyType].end()
9410 ? AudioMMapPolicy::NEVER : it->second;
9411 return NO_ERROR;
9412}
9413
9414status_t AudioPolicyManager::updateMmapPolicyInfos(AudioMMapPolicyType policyType) {
9415 std::vector<AudioMMapPolicyInfo> policyInfos;
9416 if (status_t status = mpClientInterface->getMmapPolicyInfos(policyType, &policyInfos);
9417 status != NO_ERROR) {
9418 ALOGE("%s, failed, error = %d", __func__, status);
9419 return status;
9420 }
9421 std::map<AudioDeviceDescription, AudioMMapPolicy> mmapPolicyByDeviceType;
9422 if (policyInfos.size() == 1 && policyInfos[0].device == AudioDevice()) {
9423 // When there is only one AudioMMapPolicyInfo instance and the device is a default value,
9424 // it indicates the mmap policy is reported via system property. In that case, use the
9425 // routing information to fill details for how mmap is supported for a particular device.
9426 for (const auto &hwModule: mHwModules) {
9427 for (const auto &profile: hwModule->getInputProfiles()) {
9428 if ((profile->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ)
9429 != AUDIO_INPUT_FLAG_MMAP_NOIRQ) {
9430 continue;
9431 }
9432 for (const auto &device: profile->getSupportedDevices()) {
9433 auto deviceDesc =
9434 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9435 if (deviceDesc.ok()) {
9436 mmapPolicyByDeviceType.emplace(
9437 deviceDesc.value(), policyInfos[0].mmapPolicy);
9438 }
9439 }
9440 }
9441 for (const auto &profile: hwModule->getOutputProfiles()) {
9442 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)
9443 != AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
9444 continue;
9445 }
9446 for (const auto &device: profile->getSupportedDevices()) {
9447 auto deviceDesc =
9448 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9449 if (deviceDesc.ok()) {
9450 mmapPolicyByDeviceType.emplace(
9451 deviceDesc.value(), policyInfos[0].mmapPolicy);
9452 }
9453 }
9454 }
9455 }
9456 } else {
9457 for (const auto &info: policyInfos) {
9458 mmapPolicyByDeviceType[info.device.type] = info.mmapPolicy;
9459 }
9460 }
9461 mMmapPolicyByDeviceType.emplace(policyType, mmapPolicyByDeviceType);
9462 mMmapPolicyInfos.emplace(policyType, policyInfos);
9463 return NO_ERROR;
9464}
9465
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009466} // namespace android