blob: 083b81bb3b5e05c5d4707ce20e91e363bab9a8d5 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Jiabin Huangaa6e9e32024-10-21 17:19:28 +000043#include <android/media/audio/common/AudioMMapPolicy.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010044#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080045#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010046#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080047#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070048#include <cutils/bitops.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
Shunkai Yao2dcd60c2024-08-27 21:08:53 +000058#include "SpatializerHelper.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010059#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070060
Eric Laurent3b73df72014-03-11 09:06:29 -070061namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070062
Marvin Raminbdefaf02023-11-01 09:10:32 +010063
64namespace audio_flags = android::media::audiopolicy;
65
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010066using android::media::audio::common::AudioDevice;
67using android::media::audio::common::AudioDeviceAddress;
Jiabin Huangaa6e9e32024-10-21 17:19:28 +000068using android::media::audio::common::AudioDeviceDescription;
69using android::media::audio::common::AudioMMapPolicy;
70using android::media::audio::common::AudioMMapPolicyInfo;
71using android::media::audio::common::AudioMMapPolicyType;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010072using android::media::audio::common::AudioPortDeviceExt;
73using android::media::audio::common::AudioPortExt;
Eric Laurentb2fb4102024-06-21 12:25:26 +000074using com::android::media::audioserver::fix_call_audio_patch;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000075using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070076
Eric Laurentdc462862016-07-19 12:29:53 -070077//FIXME: workaround for truncated touch sounds
78// to be removed when the problem is handled by system UI
79#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070080
81// Largest difference in dB on earpiece in call between the voice volume and another
82// media / notification / system volume.
83constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
84
jiabin06e4bab2019-07-29 10:13:34 -070085template <typename T>
86bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
87{
88 if (left.size() != right.size()) {
89 return false;
90 }
91 for (size_t index = 0; index < right.size(); index++) {
92 if (left[index] != right[index]) {
93 return false;
94 }
95 }
96 return true;
97}
98
99template <typename T>
100bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
101{
102 return !(left == right);
103}
104
Eric Laurente552edb2014-03-10 17:42:56 -0700105// ----------------------------------------------------------------------------
106// AudioPolicyInterface implementation
107// ----------------------------------------------------------------------------
108
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100109status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
110 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
111 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800112 nextAudioPortGeneration();
113 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800114}
115
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
117 audio_policy_dev_state_t state,
118 const char* device_address,
119 const char* device_name,
120 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800121 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100122 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
123 status == OK) {
124 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
125 } else {
126 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
127 return status;
128 }
129}
130
Ping Tsai2a5a5242024-08-16 13:39:10 +0800131status_t AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000132 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200133{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000134 audio_port_v7 devicePort;
135 device->toAudioPort(&devicePort);
Ping Tsai2a5a5242024-08-16 13:39:10 +0800136 status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
137 ALOGE_IF(status != OK, "Error %d while setting connected state %d for device %s", status,
138 static_cast<int>(state), device->getDeviceTypeAddr().toString(false).c_str());
139
140 return status;
François Gaffie44481e72016-04-20 07:49:57 +0200141}
142
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100143status_t AudioPolicyManager::setDeviceConnectionStateInt(
144 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
145 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100146 if (port.ext.getTag() != AudioPortExt::device) {
147 return BAD_VALUE;
148 }
149 audio_devices_t device_type;
150 std::string device_address;
151 if (status_t status = aidl2legacy_AudioDevice_audio_device(
152 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
153 status != OK) {
154 return status;
155 };
156 const char* device_name = port.name.c_str();
157 // connect/disconnect only 1 device at a time
158 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
159 return BAD_VALUE;
160
161 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
162 device_type, device_address.c_str(), device_name, encodedFormat,
163 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000164 if (device == nullptr) {
165 return INVALID_OPERATION;
166 }
167 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
168 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
169 }
170 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100171}
172
François Gaffie11d30102018-11-02 16:09:09 +0100173status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800174 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100175 const char* device_address,
176 const char* device_name,
177 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800178 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100179 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
180 status == OK) {
181 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
182 } else {
183 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
184 return status;
185 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700186}
Paul McLeane743a472015-01-28 11:07:31 -0800187
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700188status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
189 audio_policy_dev_state_t state)
190{
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700192 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700193 SortedVector <audio_io_handle_t> outputs;
194
François Gaffie11d30102018-11-02 16:09:09 +0100195 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700196
Eric Laurente552edb2014-03-10 17:42:56 -0700197 // save a copy of the opened output descriptors before any output is opened or closed
198 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
199 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100200
201 bool wasLeUnicastActive = isLeUnicastActive();
202
Eric Laurente552edb2014-03-10 17:42:56 -0700203 switch (state)
204 {
205 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800206 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700207 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100208 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700209 return INVALID_OPERATION;
210 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800211 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700212 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700213
Eric Laurente552edb2014-03-10 17:42:56 -0700214 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200215 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700216 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700217 }
218
François Gaffie44481e72016-04-20 07:49:57 +0200219 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
220 // parameters on newly connected devices (instead of opening the outputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800221 if (broadcastDeviceConnectionState(
222 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
223 mAvailableOutputDevices.remove(device);
224 mHwModules.cleanUpForDevice(device);
225 ALOGE("%s() device %s format %x connection failed", __func__,
226 device->toString().c_str(), device->getEncodedFormat());
227 return INVALID_OPERATION;
228 }
François Gaffie44481e72016-04-20 07:49:57 +0200229
François Gaffie11d30102018-11-02 16:09:09 +0100230 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
231 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200232
jiabinc0048632023-04-27 22:04:31 +0000233 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700234
235 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700236 return INVALID_OPERATION;
237 }
François Gaffie2110e042015-03-24 08:41:51 +0100238
jiabin1c4794b2020-05-05 10:08:05 -0700239 // Populate encapsulation information when a output device is connected.
240 device->setEncapsulationInfoFromHal(mpClientInterface);
241
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700242 // outputs should never be empty here
243 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
244 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100245 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800246
Eric Laurent3ae5f312015-02-03 17:12:08 -0800247 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700248 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700249 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700250 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100251 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700252 return INVALID_OPERATION;
253 }
254
François Gaffie11d30102018-11-02 16:09:09 +0100255 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700256
jiabinc0048632023-04-27 22:04:31 +0000257 // Notify the HAL to prepare to disconnect device
258 broadcastDeviceConnectionState(
259 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700260
Eric Laurente552edb2014-03-10 17:42:56 -0700261 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100262 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700263
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100264 mOutputs.clearSessionRoutesForDevice(device);
265
François Gaffie11d30102018-11-02 16:09:09 +0100266 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100267
jiabinc0048632023-04-27 22:04:31 +0000268 // Send Disconnect to HALs
269 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
270
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800271 // Reset active device codec
272 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
273
Kriti Dangef6be8f2020-11-05 11:58:19 +0100274 // remove device from mReportedFormatsMap cache
275 mReportedFormatsMap.erase(device);
276
jiabina84c3d32022-12-02 18:59:55 +0000277 // remove preferred mixer configurations
278 mPreferredMixerAttrInfos.erase(device->getId());
279
Eric Laurente552edb2014-03-10 17:42:56 -0700280 } break;
281
282 default:
François Gaffie11d30102018-11-02 16:09:09 +0100283 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700284 return BAD_VALUE;
285 }
286
Eric Laurent736a1022019-03-27 18:28:46 -0700287 // Propagate device availability to Engine
288 setEngineDeviceConnectionState(device, state);
289
Eric Laurentae970022019-01-29 14:25:04 -0800290 // No need to evaluate playback routing when connecting a remote submix
291 // output device used by a dynamic policy of type recorder as no
292 // playback use case is affected.
293 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700294 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800295 for (audio_io_handle_t output : outputs) {
296 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800297 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
298 if (policyMix != nullptr
299 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000300 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800301 doCheckForDeviceAndOutputChanges = false;
302 break;
303 }
304 }
305 }
306
307 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700308 // outputs must be closed after checkOutputForAllStrategies() is executed
309 if (!outputs.isEmpty()) {
310 for (audio_io_handle_t output : outputs) {
311 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100312 // close unused outputs after device disconnection or direct outputs that have
313 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200314 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200315 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
316 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200317 (desc->mDirectOpenCount == 0))
318 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
319 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200320 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700321 closeOutput(output);
322 }
Eric Laurente552edb2014-03-10 17:42:56 -0700323 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700324 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
325 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700326 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700327 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800328 };
329
330 if (doCheckForDeviceAndOutputChanges) {
331 checkForDeviceAndOutputChanges(checkCloseOutputs);
332 } else {
333 checkCloseOutputs();
334 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100335 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100336 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700337 const DeviceVector activeMediaDevices =
338 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000339 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700340 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700341 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530342 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
343 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100344 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700345 // do not force device change on duplicated output because if device is 0, it will
346 // also force a device 0 for the two outputs it is duplicated to which may override
347 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100348 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100349 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700350 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700351 // always force when disconnecting (a non-duplicated device)
352 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000353 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000354 // If the device is using preferred mixer attributes, the output need to reopen
355 // with default configuration when the new selected devices are different from
356 // current routing devices
357 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
358 continue;
359 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530360 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700361 }
jiabinbce0c1d2020-10-05 11:20:18 -0700362 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000363 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700364 desc->supportsDevicesForPlayback(activeMediaDevices)) {
365 // Reopen the output to query the dynamic profiles when there is not active
366 // clients or all active clients will be rerouted. Otherwise, set the flag
367 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
368 // can be reopened to query dynamic profiles when all clients are inactive.
369 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000370 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700371 } else {
372 desc->mPendingReopenToQueryProfiles = true;
373 }
374 }
375 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
376 // Clear the flag that previously set for re-querying profiles.
377 desc->mPendingReopenToQueryProfiles = false;
378 }
379 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000380 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700381
Eric Laurentd60560a2015-04-10 11:31:20 -0700382 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700384 }
385
Eric Laurent96d1dda2022-03-14 17:14:19 +0100386 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
387
Eric Laurent72aa32f2014-05-30 18:51:48 -0700388 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530389 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700390 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700391 } // end if is output device
392
Eric Laurente552edb2014-03-10 17:42:56 -0700393 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700394 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100395 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700396 switch (state)
397 {
398 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700399 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700400 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100401 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700402 return INVALID_OPERATION;
403 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700404
Jaideep Sharma33173202024-06-18 17:46:45 +0530405 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
406
Eric Laurent0dd51852019-04-19 18:18:58 -0700407 if (mAvailableInputDevices.add(device) < 0) {
408 return NO_MEMORY;
409 }
410
François Gaffie44481e72016-04-20 07:49:57 +0200411 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
412 // parameters on newly connected devices (instead of opening the inputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800413 if (broadcastDeviceConnectionState(
414 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
415 mAvailableInputDevices.remove(device);
416 mHwModules.cleanUpForDevice(device);
417 ALOGE("%s() device %s format %x connection failed", __func__,
418 device->toString().c_str(), device->getEncodedFormat());
419 return INVALID_OPERATION;
420 }
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700421 // Propagate device availability to Engine
422 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200423
Eric Laurent0dd51852019-04-19 18:18:58 -0700424 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700425 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
426
Eric Laurent0dd51852019-04-19 18:18:58 -0700427 mAvailableInputDevices.remove(device);
428
jiabinc0048632023-04-27 22:04:31 +0000429 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100430
431 mHwModules.cleanUpForDevice(device);
432
Eric Laurentd4692962014-05-05 18:13:44 -0700433 return INVALID_OPERATION;
434 }
435
Eric Laurentd4692962014-05-05 18:13:44 -0700436 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700437
438 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700439 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700440 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100441 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700442 return INVALID_OPERATION;
443 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700444
François Gaffie11d30102018-11-02 16:09:09 +0100445 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700446
jiabinc0048632023-04-27 22:04:31 +0000447 // Notify the HAL to prepare to disconnect device
448 broadcastDeviceConnectionState(
449 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700450
François Gaffie11d30102018-11-02 16:09:09 +0100451 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700452
453 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100454
jiabinc0048632023-04-27 22:04:31 +0000455 // Set Disconnect to HALs
456 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
457
Kriti Dangef6be8f2020-11-05 11:58:19 +0100458 // remove device from mReportedFormatsMap cache
459 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700460
461 // Propagate device availability to Engine
462 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700463 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700464
465 default:
François Gaffie11d30102018-11-02 16:09:09 +0100466 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700467 return BAD_VALUE;
468 }
469
Eric Laurent0dd51852019-04-19 18:18:58 -0700470 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700471 // As the input device list can impact the output device selection, update
472 // getDeviceForStrategy() cache
473 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700474
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100475 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200476 // Reconnect Audio Source
477 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
478 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
479 checkAudioSourceForAttributes(attributes);
480 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700481 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100482 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700483 }
484
Eric Laurentb52c1522014-05-20 11:27:36 -0700485 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530486 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700487 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700488 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700489
François Gaffie11d30102018-11-02 16:09:09 +0100490 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700491 return BAD_VALUE;
492}
493
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100494status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
495 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800496 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700497 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
498 devDescr->setName(device_name);
499 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100500}
501
Eric Laurent736a1022019-03-27 18:28:46 -0700502void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
503 audio_policy_dev_state_t state) {
504
505 // the Engine does not have to know about remote submix devices used by dynamic audio policies
506 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
507 return;
508 }
509 mEngine->setDeviceConnectionState(device, state);
510}
511
512
Eric Laurente0720872014-03-11 09:30:41 -0700513audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100514 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700515{
Eric Laurent634b7142016-04-20 13:48:02 -0700516 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
518 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700519 (strlen(device_address) != 0)/*matchAddress*/);
520
521 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100522 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700523 device, device_address);
524 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
525 }
François Gaffie53615e22015-03-19 09:24:12 +0100526
Eric Laurent3a4311c2014-03-17 12:00:47 -0700527 DeviceVector *deviceVector;
528
Eric Laurente552edb2014-03-10 17:42:56 -0700529 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700530 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700531 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700532 deviceVector = &mAvailableInputDevices;
533 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100534 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700535 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700536 }
Eric Laurent634b7142016-04-20 13:48:02 -0700537
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800538 return (deviceVector->getDevice(
539 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700540 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800541}
542
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800543status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
544 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800545 const char *device_name,
546 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800547{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800548 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
549 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800550
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800551 // connect/disconnect only 1 device at a time
552 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
553
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800554 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700555 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800556 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800557 // Nothing to do: device is not connected
558 return NO_ERROR;
559 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800560 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800561
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700562 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800563 // configure codecs.
564 // Handle two specific cases by sending a set parameter to
565 // configure A2DP codecs. No need to toggle device state.
566 // Case 1: A2DP active device switches from primary to primary
567 // module
568 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100569 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700570 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800571 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
572 if (availablePrimaryOutputDevices().contains(devDesc) &&
573 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100574 bool isA2dp = audio_is_a2dp_out_device(device);
575 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
576 : String8(AudioParameter::keyReconfigLeSupported);
577 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800578 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100579 int isReconfigSupported;
580 repliedParameters.getInt(supportKey, isReconfigSupported);
581 if (isReconfigSupported) {
582 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
583 : String8(AudioParameter::keyReconfigLe);
584 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800585 param.add(key, String8("true"));
586 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
587 devDesc->setEncodedFormat(encodedFormat);
588 return NO_ERROR;
589 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700590 }
591 }
cnx421bd2dcc42020-07-11 14:58:44 +0800592 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000593 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800594 for (size_t i = 0; i < mOutputs.size(); i++) {
595 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000596 // mute media strategies to avoid sending the music tail into
597 // the earpiece or headset.
598 if (desc->isStrategyActive(musicStrategy)) {
599 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
600 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
601 tempRecommendedMuteDuration : desc->latency() * 4;
602 if (muteWaitMs < tempMuteDurationMs) {
603 muteWaitMs = tempMuteDurationMs;
604 }
605 }
cnx421bd2dcc42020-07-11 14:58:44 +0800606 setStrategyMute(musicStrategy, true, desc);
607 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
608 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
609 nullptr, true /*fromCache*/).types());
610 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000611 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
612 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
613 // happens after the actual device switch.
614 if (muteWaitMs > 0) {
615 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
616 usleep(muteWaitMs * 1000);
617 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800618 // Toggle the device state: UNAVAILABLE -> AVAILABLE
619 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100620 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800621 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800622 device_address, device_name,
623 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800624 if (status != NO_ERROR) {
625 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
626 status);
627 return status;
628 }
629
630 status = setDeviceConnectionState(device,
631 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800632 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800633 if (status != NO_ERROR) {
634 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
635 status);
636 return status;
637 }
638
639 return NO_ERROR;
640}
641
Pattydd807582021-11-04 21:01:03 +0800642status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
643 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800644{
Pattydd807582021-11-04 21:01:03 +0800645 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800646 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800647 std::unordered_set<audio_format_t> formatSet;
648 sp<HwModule> primaryModule =
649 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700650 if (primaryModule == nullptr) {
651 ALOGE("%s() unable to get primary module", __func__);
652 return NO_INIT;
653 }
Pattydd807582021-11-04 21:01:03 +0800654
655 DeviceTypeSet audioDeviceSet;
656
657 switch(device) {
658 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
659 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
660 break;
661 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800662 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
663 break;
664 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
665 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800666 break;
667 default:
668 ALOGE("%s() device type 0x%08x not supported", __func__, device);
669 return BAD_VALUE;
670 }
671
jiabin9a3361e2019-10-01 09:38:30 -0700672 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800673 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800674 for (const auto& device : declaredDevices) {
675 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800676 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800677 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800678 return status;
679}
680
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100681DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
682{
683 DeviceVector rxSinkdevices{};
684 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
685 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
686 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
687 auto rxSinkDevice = rxSinkdevices.itemAt(0);
688 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
689 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
690 // retrieve Rx Source device descriptor
691 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
692 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
693
694 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
695 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
696 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
697 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
698 return DeviceVector(rxSinkDevice);
699 }
700 }
701 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
702 // the device returned is not necessarily reachable via this output
703 // (filter later by setOutputDevices())
704 return getNewOutputDevices(mPrimaryOutput, fromCache);
705}
706
707status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
708{
François Gaffiedb1755b2023-09-01 11:50:35 +0200709 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100710 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
711 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
712 }
713 return INVALID_OPERATION;
714}
715
716status_t AudioPolicyManager::updateCallRoutingInternal(
717 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700718{
719 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100720 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700721 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200722 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700723 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100724 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700725 }
François Gaffie11d30102018-11-02 16:09:09 +0100726
Francois Gaffie716e1432019-01-14 16:58:59 +0100727 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100728 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200729
Eric Laurentb2fb4102024-06-21 12:25:26 +0000730 if (!fix_call_audio_patch()) {
731 disconnectTelephonyAudioSource(mCallRxSourceClient);
732 disconnectTelephonyAudioSource(mCallTxSourceClient);
733 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200734
735 if (rxDevices.isEmpty()) {
736 ALOGW("%s() no selected output device", __func__);
737 return INVALID_OPERATION;
738 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000739 if (txSourceDevice == nullptr) {
740 ALOGE("%s() selected input device not available", __func__);
741 return INVALID_OPERATION;
742 }
François Gaffiec005e562018-11-06 15:04:49 +0100743
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100744 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100745 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700746
François Gaffie9eb18552018-11-05 10:33:26 +0100747 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700748 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100749 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700750 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100751 // retrieve Rx Source and Tx Sink device descriptors
752 sp<DeviceDescriptor> rxSourceDevice =
753 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
754 String8(),
755 AUDIO_FORMAT_DEFAULT);
756 sp<DeviceDescriptor> txSinkDevice =
757 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
758 String8(),
759 AUDIO_FORMAT_DEFAULT);
760
761 // RX and TX Telephony device are declared by Primary Audio HAL
762 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
763 (telephonyRxModule->getHalVersionMajor() >= 3)) {
764 if (rxSourceDevice == 0 || txSinkDevice == 0) {
765 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100766 ALOGE("%s() no telephony Tx and/or RX device", __func__);
767 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100768 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100769 // createAudioPatchInternal now supports both HW / SW bridging
770 createRxPatch = true;
771 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100772 } else {
773 // If the RX device is on the primary HW module, then use legacy routing method for
774 // voice calls via setOutputDevice() on primary output.
775 // Otherwise, create two audio patches for TX and RX path.
776 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
777 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700778 // If the TX device is also on the primary HW module, setOutputDevice() will take care
779 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100780 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
781 (txSinkDevice != 0);
782 }
783 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
784 // Otherwise, create two audio patches for TX and RX path.
785 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000786 if (fix_call_audio_patch()) {
787 disconnectTelephonyAudioSource(mCallRxSourceClient);
788 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200789 if (!hasPrimaryOutput()) {
790 ALOGW("%s() no primary output available", __func__);
791 return INVALID_OPERATION;
792 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530793 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700794 } else { // create RX path audio patch
David Lif85c5e32024-07-01 13:14:10 +0000795 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800796 // If the TX device is on the primary HW module but RX device is
797 // on other HW module, SinkMetaData of telephony input should handle it
798 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700799 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700800 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100801 // terminate active capture if on the same HW module as the call TX source device
802 // FIXME: would be better to refine to only inputs whose profile connects to the
803 // call TX device but this information is not in the audio patch and logic here must be
804 // symmetric to the one in startInput()
805 for (const auto& activeDesc : mInputs.getActiveInputs()) {
806 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
807 closeActiveClients(activeDesc);
808 }
809 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200810 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000811 } else if (fix_call_audio_patch()) {
812 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800813 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100814 if (waitMs != nullptr) {
815 *waitMs = muteWaitMs;
816 }
817 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800818}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700819
Mikhail Naganov100f0122018-11-29 11:22:16 -0800820bool AudioPolicyManager::isDeviceOfModule(
821 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
822 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
823 if (module != 0) {
824 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
825 .indexOf(devDesc) != NAME_NOT_FOUND
826 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
827 .indexOf(devDesc) != NAME_NOT_FOUND;
828 }
829 return false;
830}
831
David Lif85c5e32024-07-01 13:14:10 +0000832void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200833{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000834 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
835
836 if (fix_call_audio_patch()) {
837 if (mCallRxSourceClient != nullptr) {
838 DeviceVector rxDevices =
839 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
840 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
841 "connectTelephonyRxAudioSource(): no device found for call RX source");
842 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
843 if (mCallRxSourceClient->isConnected()
844 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
845 return;
846 }
847 disconnectTelephonyAudioSource(mCallRxSourceClient);
848 }
849 } else {
850 disconnectTelephonyAudioSource(mCallRxSourceClient);
851 }
852
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200853 const struct audio_port_config source = {
854 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
855 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
856 };
Eric Laurent541a2002024-01-15 18:11:42 +0100857 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000858
Eric Laurentccbd7872024-06-20 12:34:15 +0000859 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Lif85c5e32024-07-01 13:14:10 +0000860 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100861 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
862 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000863 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
864 mCallRxSourceClient->srcDevice()->toString().c_str(),
865 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200866 ALOGE_IF(mCallRxSourceClient == nullptr,
867 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200868}
869
Francois Gaffie601801d2021-06-22 13:27:39 +0200870void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200871{
Francois Gaffie601801d2021-06-22 13:27:39 +0200872 if (clientDesc == nullptr) {
873 return;
874 }
875 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
876 "%s error stopping audio source", __func__);
877 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200878}
879
880void AudioPolicyManager::connectTelephonyTxAudioSource(
881 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
882 uint32_t delayMs)
883{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200884 if (srcDevice == nullptr || sinkDevice == nullptr) {
885 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
886 return;
887 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000888
889 if (fix_call_audio_patch()) {
890 if (mCallTxSourceClient != nullptr) {
891 if (mCallTxSourceClient->isConnected()
892 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
893 return;
894 }
895 disconnectTelephonyAudioSource(mCallTxSourceClient);
896 }
897 } else {
898 disconnectTelephonyAudioSource(mCallTxSourceClient);
899 }
900
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200901 PatchBuilder patchBuilder;
902 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000903
Francois Gaffie601801d2021-06-22 13:27:39 +0200904 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200905 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
906
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200907 struct audio_port_config source = {};
908 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100909 mCallTxSourceClient = new SourceClientDescriptor(
910 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000911 mCommunnicationStrategy, toVolumeSource(aa), true,
912 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100913 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
914
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200915 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
916 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200917 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
918 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200919 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000920 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
921 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200922 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200923 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200924 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200925}
926
Eric Laurente0720872014-03-11 09:30:41 -0700927void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700928{
929 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100930 // store previous phone state for management of sonification strategy below
931 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100932 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100933
934 if (mEngine->setPhoneState(state) != NO_ERROR) {
935 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700936 return;
937 }
François Gaffie2110e042015-03-24 08:41:51 +0100938 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700939 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700940 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700941 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800942 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700943 }
944
François Gaffie2110e042015-03-24 08:41:51 +0100945 /**
946 * Switching to or from incall state or switching between telephony and VoIP lead to force
947 * routing command.
948 */
Eric Laurent74b71512019-11-06 17:21:57 -0800949 bool force = ((isStateInCall(oldState) != isStateInCall(state))
950 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700951
952 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700953 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700954
Eric Laurente552edb2014-03-10 17:42:56 -0700955 int delayMs = 0;
956 if (isStateInCall(state)) {
957 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100958 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
959 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700960 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700961 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700962 // mute media and sonification strategies and delay device switch by the largest
963 // latency of any output where either strategy is active.
964 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100965 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
966 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
967 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700968 (delayMs < (int)desc->latency()*2)) {
969 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700970 }
François Gaffiec005e562018-11-06 15:04:49 +0100971 setStrategyMute(musicStrategy, true, desc);
972 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
973 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
974 nullptr, true /*fromCache*/).types());
975 setStrategyMute(sonificationStrategy, true, desc);
976 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
977 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
978 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700979 }
980 }
981
François Gaffiedb1755b2023-09-01 11:50:35 +0200982 if (state == AUDIO_MODE_IN_CALL) {
983 (void)updateCallRouting(false /*fromCache*/, delayMs);
984 } else {
985 if (oldState == AUDIO_MODE_IN_CALL) {
986 disconnectTelephonyAudioSource(mCallRxSourceClient);
987 disconnectTelephonyAudioSource(mCallTxSourceClient);
988 }
989 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100990 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
991 // force routing command to audio hardware when ending call
992 // even if no device change is needed
993 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
994 rxDevices = mPrimaryOutput->devices();
995 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530996 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700997 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700998 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700999
jiabin3ff8d7d2022-12-13 06:27:44 +00001000 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001001 // reevaluate routing on all outputs in case tracks have been started during the call
1002 for (size_t i = 0; i < mOutputs.size(); i++) {
1003 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01001004 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00001005 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
1006 && desc->mPreferredAttrInfo != nullptr) {
1007 // If the output is using preferred mixer attributes and the audio mode is not normal,
1008 // the output need to reopen with default configuration.
1009 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
1010 continue;
1011 }
Francois Gaffie601801d2021-06-22 13:27:39 +02001012 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
1013 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05301014 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +02001015 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001016 }
1017 }
jiabin3ff8d7d2022-12-13 06:27:44 +00001018 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001019
Eric Laurent96d1dda2022-03-14 17:14:19 +01001020 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
1021
Eric Laurente552edb2014-03-10 17:42:56 -07001022 if (isStateInCall(state)) {
1023 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001024 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001025 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001026 }
1027
1028 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001029 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1030 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001031}
1032
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001033audio_mode_t AudioPolicyManager::getPhoneState() {
1034 return mEngine->getPhoneState();
1035}
1036
Eric Laurente0720872014-03-11 09:30:41 -07001037void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001038 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001039{
François Gaffie2110e042015-03-24 08:41:51 +01001040 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001041 if (config == mEngine->getForceUse(usage)) {
1042 return;
1043 }
Eric Laurente552edb2014-03-10 17:42:56 -07001044
François Gaffie2110e042015-03-24 08:41:51 +01001045 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1046 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1047 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001048 }
François Gaffie2110e042015-03-24 08:41:51 +01001049 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1050 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1051 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001052
1053 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001054 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001055
Eric Laurent22fcda22019-05-17 16:28:47 -07001056 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1057 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001058 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001059 }
1060
Eric Laurentdc462862016-07-19 12:29:53 -07001061 //FIXME: workaround for truncated touch sounds
1062 // to be removed when the problem is handled by system UI
1063 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001064 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1065 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1066 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001067
1068 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001069 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001070}
1071
Eric Laurente0720872014-03-11 09:30:41 -07001072void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001073{
1074 ALOGV("setSystemProperty() property %s, value %s", property, value);
1075}
1076
Dorin Drimusecc9f422022-03-09 17:57:40 +01001077// Find an MSD output profile compatible with the parameters passed.
1078// When "directOnly" is set, restrict search to profiles for direct outputs.
1079sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1080 const DeviceVector& devices,
1081 uint32_t samplingRate,
1082 audio_format_t format,
1083 audio_channel_mask_t channelMask,
1084 audio_output_flags_t flags,
1085 bool directOnly)
1086{
1087 flags = getRelevantFlags(flags, directOnly);
1088
1089 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1090 if (msdModule != nullptr) {
1091 // for the msd module check if there are patches to the output devices
1092 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1093 HwModuleCollection modules;
1094 modules.add(msdModule);
1095 return searchCompatibleProfileHwModules(
1096 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1097 flags, directOnly);
1098 }
1099 }
1100 return nullptr;
1101}
1102
Michael Chana94fbb22018-04-24 14:31:19 +10001103// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1104// search to profiles for direct outputs.
1105sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001106 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001107 uint32_t samplingRate,
1108 audio_format_t format,
1109 audio_channel_mask_t channelMask,
1110 audio_output_flags_t flags,
1111 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001112{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001113 flags = getRelevantFlags(flags, directOnly);
1114
1115 return searchCompatibleProfileHwModules(
1116 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1117}
1118
1119audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1120 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001121 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001122 // only retain flags that will drive the direct output profile selection
1123 // if explicitly requested
1124 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001125 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001126 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1127 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001128 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001129 return flags;
1130}
Eric Laurent861a6282015-05-18 15:40:16 -07001131
Dorin Drimusecc9f422022-03-09 17:57:40 +01001132sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1133 const HwModuleCollection& hwModules,
1134 const DeviceVector& devices,
1135 uint32_t samplingRate,
1136 audio_format_t format,
1137 audio_channel_mask_t channelMask,
1138 audio_output_flags_t flags,
1139 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001140 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001141 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001142 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001143 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001144 samplingRate, NULL /*updatedSamplingRate*/,
1145 format, NULL /*updatedFormat*/,
1146 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001147 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001148 continue;
1149 }
1150 // reject profiles not corresponding to a device currently available
1151 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1152 continue;
1153 }
1154 // reject profiles if connected device does not support codec
1155 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1156 continue;
1157 }
1158 if (!directOnly) {
1159 return curProfile;
1160 }
1161
1162 // when searching for direct outputs, if several profiles are compatible, give priority
1163 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001164 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001165 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001166 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001167 }
1168 profile = curProfile;
1169 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1170 break;
1171 }
Eric Laurente552edb2014-03-10 17:42:56 -07001172 }
1173 }
Eric Laurent861a6282015-05-18 15:40:16 -07001174 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001175}
1176
Eric Laurentfa0f6742021-08-17 18:39:44 +02001177sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001178 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001179{
1180 for (const auto& hwModule : mHwModules) {
1181 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001182 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001183 continue;
1184 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001185 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001186 // reject profiles not corresponding to a device currently available
1187 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1188 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1189 continue;
1190 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001191 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1192 != devices.size()) {
1193 continue;
1194 }
1195 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001196 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1197 return curProfile;
1198 }
1199 }
1200 return nullptr;
1201}
1202
Eric Laurentf4e63452017-11-06 19:31:46 +00001203audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001204{
François Gaffiec005e562018-11-06 15:04:49 +01001205 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001206
1207 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1208 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1209 // format, flags, etc. This may result in some discrepancy for functions that utilize
1210 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1211 // and AudioSystem::getOutputSamplingRate().
1212
François Gaffie11d30102018-11-02 16:09:09 +01001213 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001214 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov806170e2024-09-05 17:26:50 -07001215 if (stream == AUDIO_STREAM_MUSIC && mConfig->useDeepBufferForMedia()) {
Mingyu Shih75563d32023-05-24 04:47:40 +08001216 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1217 }
1218 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001219
François Gaffie11d30102018-11-02 16:09:09 +01001220 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1221 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001222 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001223}
1224
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001225status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1226 const audio_attributes_t *srcAttr,
1227 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001228{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001229 if (srcAttr != NULL) {
1230 if (!isValidAttributes(srcAttr)) {
1231 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1232 __func__,
1233 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1234 srcAttr->tags);
1235 return BAD_VALUE;
1236 }
1237 *dstAttr = *srcAttr;
1238 } else {
1239 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1240 ALOGE("%s: invalid stream type", __func__);
1241 return BAD_VALUE;
1242 }
François Gaffiec005e562018-11-06 15:04:49 +01001243 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001244 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001245
1246 // Only honor audibility enforced when required. The client will be
1247 // forced to reconnect if the forced usage changes.
1248 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001249 dstAttr->flags = static_cast<audio_flags_mask_t>(
1250 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001251 }
1252
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001253 return NO_ERROR;
1254}
1255
Kevin Rocard153f92d2018-12-18 18:33:28 -08001256status_t AudioPolicyManager::getOutputForAttrInt(
1257 audio_attributes_t *resultAttr,
1258 audio_io_handle_t *output,
1259 audio_session_t session,
1260 const audio_attributes_t *attr,
1261 audio_stream_type_t *stream,
1262 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001263 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001264 audio_output_flags_t *flags,
Robert Wufb971192024-10-30 21:54:35 +00001265 DeviceIdVector *selectedDeviceIds,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001266 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001267 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001268 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001269 bool *isSpatialized,
1270 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001271{
François Gaffiec005e562018-11-06 15:04:49 +01001272 DeviceVector outputDevices;
Robert Wufb971192024-10-30 21:54:35 +00001273 audio_port_handle_t requestedPortId = getFirstDeviceId(*selectedDeviceIds);
1274 selectedDeviceIds->clear();
François Gaffie11d30102018-11-02 16:09:09 +01001275 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001276 const sp<DeviceDescriptor> requestedDevice =
1277 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1278
Eric Laurent8a1095a2019-11-08 14:44:16 -08001279 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001280 *isSpatialized = false;
1281
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001282 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1283 if (status != NO_ERROR) {
1284 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001285 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001286 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001287 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001288 }
François Gaffiec005e562018-11-06 15:04:49 +01001289 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001290
François Gaffiec005e562018-11-06 15:04:49 +01001291 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1292 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001293
Oscar Azucena873d10f2023-01-12 18:34:42 -08001294 bool usePrimaryOutputFromPolicyMixes = false;
1295
Kevin Rocard153f92d2018-12-18 18:33:28 -08001296 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1297 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1298 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001299 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001300 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1301 .channel_mask = config->channel_mask,
1302 .format = config->format,
1303 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001304 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001305 mAvailableOutputDevices, requestedDevice, primaryMix,
1306 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001307 if (status != OK) {
1308 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001309 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001310
Kevin Rocard153f92d2018-12-18 18:33:28 -08001311 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001312 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungdb27c442024-08-14 11:37:57 -07001313 && (!audio_is_linear_pcm(config->format) ||
1314 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001315 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001316 return BAD_VALUE;
1317 }
1318 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001319 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001320 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1321 primaryMix->mDeviceAddress,
1322 AUDIO_FORMAT_DEFAULT);
1323 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001324 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001325 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1326 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001327 // if a direct output can be opened to deliver the track's multi-channel content to the
1328 // output rather than being downmixed by the primary output, then use this direct
1329 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1330 // mix.
1331 bool tryDirectForChannelMask = policyDesc != nullptr
1332 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1333 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001334 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001335 audio_io_handle_t newOutput;
1336 status = openDirectOutput(
1337 *stream, session, config,
1338 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangf6e304f2024-07-09 23:06:58 -07001339 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001340 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001341 policyDesc = mOutputs.valueFor(newOutput);
1342 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001343 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001344 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001345 policyDesc = nullptr;
1346 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001347 }
1348 if (policyDesc != nullptr) {
1349 policyDesc->mPolicyMix = primaryMix;
1350 *output = policyDesc->mIoHandle;
Robert Wufb971192024-10-30 21:54:35 +00001351 if (policyMixDevice != nullptr) {
1352 selectedDeviceIds->push_back(policyMixDevice->getId());
1353 }
jiabin24ff57a2023-11-27 21:06:51 +00001354 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1355 // Remove direct flag as it is not on a direct output.
1356 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1357 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001358
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001359 ALOGV("getOutputForAttr() returns output %d", *output);
1360 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1361 *outputType = API_OUT_MIX_PLAYBACK;
1362 } else {
1363 *outputType = API_OUTPUT_LEGACY;
1364 }
1365 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001366 } else {
1367 if (policyMixDevice != nullptr) {
1368 ALOGE("%s, try to use primary mix but no output found", __func__);
1369 return INVALID_OPERATION;
1370 }
1371 // Fallback to default engine selection as the selected primary mix device is not
1372 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001373 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001374 }
François Gaffiec005e562018-11-06 15:04:49 +01001375 // Virtual sources must always be dynamicaly or explicitly routed
1376 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1377 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1378 return BAD_VALUE;
1379 }
1380 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1381 // in order to let the choice of the order to future vendor engine
1382 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001383
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001384 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001385 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001386 }
1387
Nadav Barb2f18162018-07-18 13:01:53 +03001388 // Set incall music only if device was explicitly set, and fallback to the device which is
1389 // chosen by the engine if not.
1390 // FIXME: provide a more generic approach which is not device specific and move this back
1391 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001392 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001393 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001394 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001395 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001396 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001397 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001398 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001399 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001400 }
1401 }
1402
François Gaffiec005e562018-11-06 15:04:49 +01001403 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1404 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1405 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001406
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001407 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001408 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001409 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001410 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001411 ALOGV("%s() Using MSD devices %s instead of devices %s",
1412 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001413 } else {
1414 *output = AUDIO_IO_HANDLE_NONE;
1415 }
1416 }
1417 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001418 sp<PreferredMixerAttributesInfo> info = nullptr;
1419 if (outputDevices.size() == 1) {
1420 info = getPreferredMixerAttributesInfo(
1421 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001422 mEngine->getProductStrategyForAttributes(*resultAttr),
1423 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001424 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1425 // and it is currently active.
1426 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001427 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001428 info = nullptr;
1429 }
jiabin8a096672024-09-18 18:20:24 +00001430
1431 if (info != nullptr && info->isBitPerfect() &&
1432 (*flags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
1433 AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1434 // Reject direct request if a preferred mixer config in use is bit-perfect.
1435 ALOGD("%s reject direct request as bit-perfect mixer attributes is active",
1436 __func__);
1437 return BAD_VALUE;
1438 }
1439
jiabin220eea12024-05-17 17:55:20 +00001440 if (com::android::media::audioserver::
1441 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1442 if (info != nullptr && info->getUid() == uid &&
1443 info->configMatches(*config) &&
1444 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1445 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1446 [this, &outputDevices](audio_usage_t usage) {
1447 return mOutputs.isUsageActiveOnDevice(
1448 usage, outputDevices[0]); }))) {
1449 // Bit-perfect request is not allowed when the phone mode is not normal or
1450 // there is any higher priority user case active.
1451 return INVALID_OPERATION;
1452 }
1453 }
jiabina84c3d32022-12-02 18:59:55 +00001454 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001455 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001456 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001457 // The client will be active if the client is currently preferred mixer owner and the
1458 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001459 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001460 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001461 && info->getUid() == uid
1462 && *output != AUDIO_IO_HANDLE_NONE
1463 // When bit-perfect output is selected for the preferred mixer attributes owner,
1464 // only need to consider the config matches.
1465 && mOutputs.valueFor(*output)->isConfigurationMatched(
1466 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001467
1468 if (*isBitPerfect) {
1469 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1470 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001471 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001472 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001473 AudioProfileVector profiles;
1474 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1475 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001476 const auto channels = profiles[0]->getChannels();
1477 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1478 config->channel_mask = *channels.begin();
1479 }
1480 const auto sampleRates = profiles[0]->getSampleRates();
1481 if (!sampleRates.empty() &&
1482 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1483 config->sample_rate = *sampleRates.begin();
1484 }
jiabinf1c73972022-04-14 16:28:52 -07001485 config->format = profiles[0]->getFormat();
1486 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001487 return INVALID_OPERATION;
1488 }
Paul McLeanaa981192015-03-21 09:55:15 -07001489
Michael Chan6fb34492020-12-08 15:44:49 +11001490 for (auto &outputDevice : outputDevices) {
Robert Wufb971192024-10-30 21:54:35 +00001491 if (std::find(selectedDeviceIds->begin(), selectedDeviceIds->end(),
1492 outputDevice->getId()) == selectedDeviceIds->end()) {
1493 selectedDeviceIds->push_back(outputDevice->getId());
1494 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
1495 std::swap(selectedDeviceIds->front(), selectedDeviceIds->back());
1496 }
Michael Chan6fb34492020-12-08 15:44:49 +11001497 }
1498 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001499
Eric Laurent8a1095a2019-11-08 14:44:16 -08001500 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1501 *outputType = API_OUTPUT_TELEPHONY_TX;
1502 } else {
1503 *outputType = API_OUTPUT_LEGACY;
1504 }
1505
Robert Wufb971192024-10-30 21:54:35 +00001506 ALOGV("%s returns output %d selectedDeviceIds %s", __func__, *output,
1507 toString(*selectedDeviceIds).c_str());
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001508
1509 return NO_ERROR;
1510}
1511
1512status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1513 audio_io_handle_t *output,
1514 audio_session_t session,
1515 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001516 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001517 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001518 audio_output_flags_t *flags,
Robert Wufb971192024-10-30 21:54:35 +00001519 DeviceIdVector *selectedDeviceIds,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001520 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001521 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001522 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001523 bool *isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +00001524 bool *isBitPerfect,
Vlad Popa1e865e62024-08-15 19:11:42 -07001525 float *volume,
1526 bool *muted)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001527{
1528 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1529 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1530 return INVALID_OPERATION;
1531 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001532 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001533 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001534 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001535 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001536 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Robert Wufb971192024-10-30 21:54:35 +00001537 DeviceIdVector requestedDeviceIds = *selectedDeviceIds;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001538
1539 // Prevent from storing invalid requested device id in clients
Robert Wufb971192024-10-30 21:54:35 +00001540 DeviceIdVector sanitizedRequestedPortIds;
1541 for (auto deviceId : *selectedDeviceIds) {
1542 if (mAvailableOutputDevices.getDeviceFromId(deviceId) != nullptr) {
1543 sanitizedRequestedPortIds.push_back(deviceId);
1544 }
1545 }
1546 *selectedDeviceIds = sanitizedRequestedPortIds;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001547
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001548 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Robert Wufb971192024-10-30 21:54:35 +00001549 config, flags, selectedDeviceIds, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001550 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1551 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001552 if (status != NO_ERROR) {
1553 return status;
1554 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001555 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001556 if (secondaryOutputs != nullptr) {
1557 for (auto &secondaryMix : secondaryMixes) {
1558 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1559 if (outputDesc != nullptr &&
1560 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1561 secondaryOutputs->push_back(outputDesc->mIoHandle);
1562 weakSecondaryOutputDescs.push_back(outputDesc);
1563 }
1564 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001565 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001566
Eric Laurent8fc147b2018-07-22 19:13:55 -07001567 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001568 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001569 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001570 };
jiabin4ef93452019-09-10 14:29:54 -07001571 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001572
Eric Laurentc209fe42020-06-05 18:11:23 -07001573 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Robert Wufb971192024-10-30 21:54:35 +00001574 // TODO(b/367816690): Add device id sets to TrackClientDescriptor
Eric Laurent8fc147b2018-07-22 19:13:55 -07001575 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001576 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Robert Wufb971192024-10-30 21:54:35 +00001577 getFirstDeviceId(sanitizedRequestedPortIds), *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001578 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001579 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001580 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001581 std::move(weakSecondaryOutputDescs),
1582 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001583 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001584
Andy Hung6b137d12024-08-27 22:35:17 +00001585 *volume = Volume::DbToAmpl(outputDesc->getCurVolume(toVolumeSource(resultAttr)));
Vlad Popa1e865e62024-08-15 19:11:42 -07001586 *muted = outputDesc->isMutedByGroup(toVolumeSource(resultAttr));
Andy Hung6b137d12024-08-27 22:35:17 +00001587
Robert Wufb971192024-10-30 21:54:35 +00001588 ALOGV("%s() returns output %d requestedPortIds %s selectedDeviceIds %s for port ID %d",
1589 __func__, *output, toString(requestedDeviceIds).c_str(),
1590 toString(*selectedDeviceIds).c_str(), *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001591
Eric Laurente83b55d2014-11-14 10:06:21 -08001592 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001593}
1594
Eric Laurentc529cf62020-04-17 18:19:10 -07001595status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1596 audio_session_t session,
1597 const audio_config_t *config,
1598 audio_output_flags_t flags,
1599 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001600 audio_io_handle_t *output,
1601 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001602
1603 *output = AUDIO_IO_HANDLE_NONE;
1604
1605 // skip direct output selection if the request can obviously be attached to a mixed output
1606 // and not explicitly requested
1607 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1608 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1609 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1610 return NAME_NOT_FOUND;
1611 }
1612
Mikhail Naganov806170e2024-09-05 17:26:50 -07001613 // Reject flag combinations that do not make sense. Note that the requested flags might not
1614 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1615 // combine the requested flags with its own flags, yielding an unsupported combination.
1616 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1617 return NAME_NOT_FOUND;
1618 }
1619
Eric Laurentc529cf62020-04-17 18:19:10 -07001620 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1621 // This prevents creating an offloaded track and tearing it down immediately after start
1622 // when audioflinger detects there is an active non offloadable effect.
1623 // FIXME: We should check the audio session here but we do not have it in this context.
1624 // This may prevent offloading in rare situations where effects are left active by apps
1625 // in the background.
1626 sp<IOProfile> profile;
1627 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1628 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1629 profile = getProfileForOutput(
1630 devices, config->sample_rate, config->format, config->channel_mask,
1631 flags, true /* directOnly */);
1632 }
1633
1634 if (profile == nullptr) {
1635 return NAME_NOT_FOUND;
1636 }
1637
1638 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1639 for (size_t i = 0; i < mOutputs.size(); i++) {
1640 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1641 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1642 // reuse direct output if currently open by the same client
1643 // and configured with same parameters
1644 if ((config->sample_rate == desc->getSamplingRate()) &&
1645 (config->format == desc->getFormat()) &&
1646 (config->channel_mask == desc->getChannelMask()) &&
1647 (session == desc->mDirectClientSession)) {
1648 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301649 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001650 mOutputs.keyAt(i), session);
1651 *output = mOutputs.keyAt(i);
1652 return NO_ERROR;
1653 }
1654 }
1655 }
1656
1657 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001658 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301659 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1660 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001661 return NAME_NOT_FOUND;
1662 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1663 // MMAP gracefully handles lack of an exclusive track resource by mixing
1664 // above the audio framework. For AAudio to know that the limit is reached,
1665 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301666 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1667 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001668 return NAME_NOT_FOUND;
1669 } else {
1670 // Close outputs on this profile, if available, to free resources for this request
1671 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1672 const auto desc = mOutputs.valueAt(i);
1673 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301674 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1675 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001676 closeOutput(desc->mIoHandle);
1677 }
1678 }
1679 }
1680 }
1681
1682 // Unable to close streams to find free resources for this request
1683 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301684 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1685 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001686 return NAME_NOT_FOUND;
1687 }
1688
Atneya Nairb16666a2023-12-11 20:18:33 -08001689 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001690
Michael Chan6fb34492020-12-08 15:44:49 +11001691 // An MSD patch may be using the only output stream that can service this request. Release
1692 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001693 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001694
Eric Laurentf1f22e72021-07-13 14:04:14 +02001695 status_t status =
Dean Wheatleydfb67b82024-01-23 09:36:29 +11001696 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001697 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001698
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001699 // only accept an output with the requested parameters, unless the format can be IEC61937
1700 // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1701 const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1702 && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1703 && audio_has_proportional_frames(outputDesc->getFormat());
Eric Laurentc529cf62020-04-17 18:19:10 -07001704 if (status != NO_ERROR ||
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001705 (!ignoreRequestedParametersCheck &&
1706 ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1707 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1708 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001709 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1710 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1711 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1712 config->channel_mask, outputDesc->getChannelMask());
1713 if (*output != AUDIO_IO_HANDLE_NONE) {
1714 outputDesc->close();
1715 }
1716 // fall back to mixer output if possible when the direct output could not be open
1717 if (audio_is_linear_pcm(config->format) &&
1718 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1719 return NAME_NOT_FOUND;
1720 }
1721 *output = AUDIO_IO_HANDLE_NONE;
1722 return BAD_VALUE;
1723 }
1724 outputDesc->mDirectOpenCount = 1;
1725 outputDesc->mDirectClientSession = session;
1726
1727 addOutput(*output, outputDesc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07001728 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
1729 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
1730 hwModule->getHalVersionMajor() >= 3) {
1731 setOutputDevices(__func__, outputDesc, devices, true, 0, NULL);
1732 }
Eric Laurentc529cf62020-04-17 18:19:10 -07001733 mPreviousOutputs = mOutputs;
1734 ALOGV("%s returns new direct output %d", __func__, *output);
1735 mpClientInterface->onAudioPortListUpdate();
1736 return NO_ERROR;
1737}
1738
François Gaffie11d30102018-11-02 16:09:09 +01001739audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1740 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001741 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001742 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001743 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001744 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001745 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001746 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001747 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001748{
Andy Hungc88b0642018-04-27 15:42:35 -07001749 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001750
jiabine375d412019-02-26 12:54:53 -08001751 // Discard haptic channel mask when forcing muting haptic channels.
1752 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001753 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1754 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001755
Eric Laurente552edb2014-03-10 17:42:56 -07001756 // open a direct output if required by specified parameters
1757 //force direct flag if offload flag is set: offloading implies a direct output stream
1758 // and all common behaviors are driven by checking only the direct flag
1759 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001760 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1761 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001762 }
Nadav Bar766fb022018-01-07 12:18:03 +02001763 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1764 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001765 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001766
1767 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1768
Eric Laurente83b55d2014-11-14 10:06:21 -08001769 // only allow deep buffering for music stream type
1770 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001771 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001772 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov806170e2024-09-05 17:26:50 -07001773 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001774 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001775 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001776 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001777 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001778 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001779 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001780 audio_is_linear_pcm(config->format) &&
1781 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001782 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001783 AUDIO_OUTPUT_FLAG_DIRECT);
1784 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001785 }
Eric Laurente552edb2014-03-10 17:42:56 -07001786
Carter Hsua3abb402021-10-26 11:11:20 +08001787 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1788 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1789 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1790 }
1791
Eric Laurentf9230d52024-01-26 18:49:09 +01001792 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001793 // was specified and offload or direct playback is not explicitly requested, and there is no
1794 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001795 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001796 if (mSpatializerOutput != nullptr &&
1797 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1798 prefMixerConfigInfo == nullptr &&
1799 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1800 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001801 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001802 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001803 }
1804
Eric Laurentc529cf62020-04-17 18:19:10 -07001805 audio_config_t directConfig = *config;
1806 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001807
1808 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1809 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001810 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001811 return output;
1812 }
1813
Eric Laurent14cbfca2016-03-17 09:42:16 -07001814 // A request for HW A/V sync cannot fallback to a mixed output because time
1815 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001816 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001817 return AUDIO_IO_HANDLE_NONE;
1818 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001819 // A request for Tuner cannot fallback to a mixed output
1820 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1821 return AUDIO_IO_HANDLE_NONE;
1822 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001823
Eric Laurente552edb2014-03-10 17:42:56 -07001824 // ignoring channel mask due to downmix capability in mixer
1825
1826 // open a non direct output
1827
1828 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001829 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001830 // get which output is suitable for the specified stream. The actual
1831 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001832 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001833 if (prefMixerConfigInfo != nullptr) {
1834 for (audio_io_handle_t outputHandle : outputs) {
1835 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1836 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1837 output = outputHandle;
1838 break;
1839 }
1840 }
1841 if (output == AUDIO_IO_HANDLE_NONE) {
1842 // No output open with the preferred profile. Open a new one.
1843 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1844 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1845 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1846 config.format = prefMixerConfigInfo->getConfigBase().format;
1847 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1848 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1849 &config, prefMixerConfigInfo->getFlags());
1850 if (preferredOutput == nullptr) {
1851 ALOGE("%s failed to open output with preferred mixer config", __func__);
1852 } else {
1853 output = preferredOutput->mIoHandle;
1854 }
1855 }
1856 } else {
1857 // at this stage we should ignore the DIRECT flag as no direct output could be
1858 // found earlier
1859 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001860 if (com::android::media::audioserver::
1861 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1862 // If the preferred mixer attributes is null, do not select the bit-perfect output
1863 // unless the bit-perfect output is the only output.
1864 // The bit-perfect output can exist while the passed in preferred mixer attributes
1865 // info is null when it is a high priority client. The high priority clients are
1866 // ringtone or alarm, which is not a bit-perfect use case.
1867 size_t i = 0;
1868 while (i < outputs.size() && outputs.size() > 1) {
1869 auto desc = mOutputs.valueFor(outputs[i]);
1870 // The output descriptor must not be null here.
1871 if (desc->isBitPerfect()) {
1872 outputs.removeItemsAt(i);
1873 } else {
1874 i += 1;
1875 }
1876 }
1877 }
jiabina84c3d32022-12-02 18:59:55 +00001878 output = selectOutput(
1879 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1880 }
Eric Laurente552edb2014-03-10 17:42:56 -07001881 }
François Gaffie11d30102018-11-02 16:09:09 +01001882 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001883 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001884 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001885
Eric Laurente552edb2014-03-10 17:42:56 -07001886 return output;
1887}
1888
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001889sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001890 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1891 mAvailableInputDevices);
1892 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1893}
1894
1895DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1896 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1897 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001898}
1899
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001900const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001901 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001902 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1903 if (msdModule != 0) {
1904 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1905 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1906 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1907 const struct audio_port_config *source = &patch->mPatch.sources[j];
1908 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1909 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001910 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001911 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001912 }
1913 }
1914 }
1915 return msdPatches;
1916}
1917
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001918bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1919 ssize_t index = mAudioPatches.indexOfKey(handle);
1920 if (index < 0) {
1921 return false;
1922 }
1923 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1924 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1925 if (msdModule == nullptr) {
1926 return false;
1927 }
1928 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1929 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1930 return true;
1931 }
1932 index = getMsdOutputPatches().indexOfKey(handle);
1933 if (index < 0) {
1934 return false;
1935 }
1936 return true;
1937}
1938
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001939status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1940 const InputProfileCollection &inputProfiles,
1941 const OutputProfileCollection &outputProfiles,
1942 const sp<DeviceDescriptor> &sourceDevice,
1943 const sp<DeviceDescriptor> &sinkDevice,
1944 AudioProfileVector& sourceProfiles,
1945 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001946 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001947 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001948 return NO_INIT;
1949 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001950 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001951 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001952 return NO_INIT;
1953 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001954 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001955 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1956 inProfile->supportsDevice(sourceDevice)) {
1957 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001958 }
1959 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001960 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001961 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001962 outProfile->supportsDevice(sinkDevice)) {
1963 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001964 }
1965 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001966 return NO_ERROR;
1967}
1968
1969status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1970 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1971 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1972{
Dean Wheatley16809da2022-12-09 14:55:46 +11001973 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1974 static const std::vector<audio_format_t> formatsOrder = {{
1975 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001976 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1977 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001978 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1979 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1980 // preferred).
1981 std::vector<audio_channel_mask_t> masks = {{
1982 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1983 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1984 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1985 // insert index masks (higher counts most preferred) as preferred over position masks
1986 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1987 masks.insert(
1988 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1989 }
1990 return masks;
1991 }();
1992
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001993 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001994 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1995 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001996 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001997 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1998 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001999 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002000 }
2001 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
2002 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
2003 sinkConfig->format = bestSinkConfig.format;
2004 // For encoded streams force direct flag to prevent downstream mixing.
2005 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2006 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11002007 if (audio_is_iec61937_compatible(sinkConfig->format)) {
2008 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002009 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11002010 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
2011 // raw and IEC61937 framed streams.
2012 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2013 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
2014 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002015 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
2016 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11002017 sourceConfig->channel_mask =
2018 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
2019 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
2020 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002021 sourceConfig->format = bestSinkConfig.format;
2022 // Copy input stream directly without any processing (e.g. resampling).
2023 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2024 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
2025 if (hwAvSync) {
2026 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2027 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
2028 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2029 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
2030 }
2031 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
2032 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
2033 sinkConfig->config_mask |= config_mask;
2034 sourceConfig->config_mask |= config_mask;
2035 return NO_ERROR;
2036}
2037
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002038PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
2039 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002040{
2041 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002042 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
2043 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
2044 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
2045 if (deviceModule == nullptr) {
2046 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
2047 return patchBuilder;
2048 }
2049 const InputProfileCollection inputProfiles = msdIsSource ?
2050 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
2051 const OutputProfileCollection outputProfiles = msdIsSource ?
2052 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2053
2054 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2055 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2056 device : getMsdAudioOutDevices().itemAt(0);
2057 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2058
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002059 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2060 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002061 AudioProfileVector sourceProfiles;
2062 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002063 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2064 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002065 for (auto hwAvSync : { true, false }) {
2066 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2067 sourceProfiles, sinkProfiles) != NO_ERROR) {
2068 continue;
2069 }
2070 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2071 &sinkConfig) == NO_ERROR) {
2072 // Found a matching config. Re-create PatchBuilder with this config.
2073 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2074 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002075 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002076 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002077 " supporting PCM format conversion.", __func__);
2078 return patchBuilder;
2079}
2080
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002081status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002082 DeviceVector devices;
2083 if (outputDevices != nullptr && outputDevices->size() > 0) {
2084 devices.add(*outputDevices);
2085 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002086 // Use media strategy for unspecified output device. This should only
2087 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2088 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002089 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002090 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002091 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002092 }
Michael Chan6fb34492020-12-08 15:44:49 +11002093 std::vector<PatchBuilder> patchesToCreate;
2094 for (auto i = 0u; i < devices.size(); ++i) {
2095 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002096 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002097 }
2098 // Retain only the MSD patches associated with outputDevices request.
2099 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002100 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002101 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2102 auto retainedPatch = false;
2103 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2104 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2105 patchesToRemove.removeItemsAt(i);
2106 retainedPatch = true;
2107 break;
2108 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002109 }
Michael Chan6fb34492020-12-08 15:44:49 +11002110 if (retainedPatch) {
2111 it = patchesToCreate.erase(it);
2112 continue;
2113 }
2114 ++it;
2115 }
2116 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2117 return NO_ERROR;
2118 }
2119 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2120 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002121 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002122 }
Michael Chan6fb34492020-12-08 15:44:49 +11002123 status_t status = NO_ERROR;
2124 for (const auto &p : patchesToCreate) {
2125 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2126 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2127 char message[256];
2128 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2129 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2130 currStatus == NO_ERROR ? "Success" : "Error",
2131 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2132 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2133 if (currStatus == NO_ERROR) {
2134 ALOGD("%s", message);
2135 } else {
2136 ALOGE("%s", message);
2137 if (status == NO_ERROR) {
2138 status = currStatus;
2139 }
2140 }
2141 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002142 return status;
2143}
2144
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002145void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2146 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002147 for (size_t i = 0; i < msdPatches.size(); i++) {
2148 const auto& patch = msdPatches[i];
2149 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2150 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2151 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2152 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2153 releaseAudioPatch(patch->getHandle(), mUidCached);
2154 break;
2155 }
2156 }
2157 }
2158}
2159
Dorin Drimus94d94412022-02-02 09:05:02 +01002160bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002161 DeviceVector devicesToCheck =
2162 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002163 AudioPatchCollection msdPatches = getMsdOutputPatches();
2164 for (size_t i = 0; i < msdPatches.size(); i++) {
2165 const auto& patch = msdPatches[i];
2166 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2167 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2168 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2169 const auto& foundDevice = devicesToCheck.getDevice(
2170 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2171 if (foundDevice != nullptr) {
2172 devicesToCheck.remove(foundDevice);
2173 if (devicesToCheck.isEmpty()) {
2174 return true;
2175 }
2176 }
2177 }
2178 }
2179 }
2180 return false;
2181}
2182
Eric Laurente0720872014-03-11 09:30:41 -07002183audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002184 audio_output_flags_t flags,
2185 audio_format_t format,
2186 audio_channel_mask_t channelMask,
2187 uint32_t samplingRate,
2188 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002189{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002190 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2191 "%s called with format %#x", __func__, format);
2192
jiabinebb6af42020-06-09 17:31:17 -07002193 // Return the output that haptic-generating attached to when 1) session id is specified,
2194 // 2) haptic-generating effect exists for given session id and 3) the output that
2195 // haptic-generating effect attached to is in given outputs.
2196 if (sessionId != AUDIO_SESSION_NONE) {
2197 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2198 sessionId, FX_IID_HAPTICGENERATOR);
2199 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2200 return hapticGeneratingOutput;
2201 }
2202 }
2203
Eric Laurent16c66dd2019-05-01 17:54:10 -07002204 // Flags disqualifying an output: the match must happen before calling selectOutput()
2205 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2206 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2207
2208 // Flags expressing a functional request: must be honored in priority over
2209 // other criteria
2210 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2211 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002212 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2213 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002214 // Flags expressing a performance request: have lower priority than serving
2215 // requested sampling rate or channel mask
2216 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2217 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2218 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2219
2220 const audio_output_flags_t functionalFlags =
2221 (audio_output_flags_t)(flags & kFunctionalFlags);
2222 const audio_output_flags_t performanceFlags =
2223 (audio_output_flags_t)(flags & kPerformanceFlags);
2224
2225 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2226
Eric Laurente552edb2014-03-10 17:42:56 -07002227 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002228 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002229 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002230 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002231 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002232 // with tiebreak preferring the minimum number of extra functional flags
2233 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002234 // 3: the output supporting the exact channel mask
2235 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002236 // 5: the output with the highest sampling rate if the requested sample rate is
2237 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002238 // 6: the output with the highest number of requested performance flags
2239 // 7: the output with the bit depth the closest to the requested one
2240 // 8: the primary output
2241 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002242
Eric Laurent16c66dd2019-05-01 17:54:10 -07002243 // matching criteria values in priority order for best matching output so far
2244 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002245
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002246 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002247 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2248 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2249 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002250
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002251 for (audio_io_handle_t output : outputs) {
2252 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002253 // matching criteria values in priority order for current output
2254 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002255
Eric Laurent16c66dd2019-05-01 17:54:10 -07002256 if (outputDesc->isDuplicated()) {
2257 continue;
2258 }
2259 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2260 continue;
2261 }
Eric Laurent8838a382014-09-08 16:44:28 -07002262
Eric Laurent16c66dd2019-05-01 17:54:10 -07002263 // If haptic channel is specified, use the haptic output if present.
2264 // When using haptic output, same audio format and sample rate are required.
2265 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002266 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002267 // skip if haptic channel specified but output does not support it, or output support haptic
2268 // but there is no haptic channel requested AND no orphan haptic effect exist
2269 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2270 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002271 continue;
2272 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002273 // In the case of audio-coupled-haptic playback, there is no format conversion and
2274 // resampling in the framework, same format/channel/sampleRate for client and the output
2275 // thread is required. In the case of HapticGenerator effect, do not require format
2276 // matching.
2277 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2278 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002279 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002280 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002281 }
2282
2283 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002284 const int matchingFunctionalFlags =
2285 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2286 const int totalFunctionalFlags =
2287 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2288 // Prefer matching functional flags, but subtract unnecessary functional flags.
2289 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002290
2291 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002292 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2293 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002294 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2295 channelCount <= outputChannelCount) {
2296 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002297 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2298 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002299 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002300 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002301 currentMatchCriteria[3] = outputChannelCount;
2302 }
2303
2304 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002305 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002306 int diff; // avoid unsigned integer overflow.
2307 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2308
2309 // prefer the closest output sampling rate greater than or equal to target
2310 // if none exists, prefer the closest output sampling rate less than target.
2311 //
2312 // criteria is offset to make non-negative.
2313 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002314 }
2315
2316 // performance flags match
2317 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2318
2319 // format match
2320 if (format != AUDIO_FORMAT_INVALID) {
2321 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002322 PolicyAudioPort::kFormatDistanceMax -
2323 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002324 }
2325
2326 // primary output match
2327 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2328
2329 // compare match criteria by priority then value
2330 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2331 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2332 bestMatchCriteria = currentMatchCriteria;
2333 bestOutput = output;
2334
2335 std::stringstream result;
2336 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2337 std::ostream_iterator<int>(result, " "));
2338 ALOGV("%s new bestOutput %d criteria %s",
2339 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002340 }
2341 }
2342
Eric Laurent16c66dd2019-05-01 17:54:10 -07002343 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002344}
2345
Eric Laurent8fc147b2018-07-22 19:13:55 -07002346status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002347{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002348 ALOGV("%s portId %d", __FUNCTION__, portId);
2349
2350 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2351 if (outputDesc == 0) {
2352 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002353 return BAD_VALUE;
2354 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002355 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002356
Eric Laurent8fc147b2018-07-22 19:13:55 -07002357 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002358 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002359
jiabin220eea12024-05-17 17:55:20 +00002360 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2361 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2362 && outputDesc->isBitPerfect()) {
2363 // Usually, APM selects bit-perfect output for high priority use cases only when
2364 // bit-perfect output is the only output that can be routed to the selected device.
2365 // However, here is no need to play high priority use cases such as ringtone and alarm
2366 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2367 // can attach to new output.
2368 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2369 __func__, client->stream());
2370 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2371 return DEAD_OBJECT;
2372 }
2373
Eric Laurent733ce942017-12-07 12:18:25 -08002374 status_t status = outputDesc->start();
2375 if (status != NO_ERROR) {
2376 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002377 }
2378
Eric Laurent97ac8712018-07-27 18:59:02 -07002379 uint32_t delayMs;
2380 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002381
2382 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002383 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002384 if (status == DEAD_OBJECT) {
2385 sp<SwAudioOutputDescriptor> desc =
2386 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2387 if (desc == nullptr) {
2388 // This is not common, it may indicate something wrong with the HAL.
2389 ALOGE("%s unable to open output with default config", __func__);
2390 return status;
2391 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002392 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002393 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002394 }
jiabina84c3d32022-12-02 18:59:55 +00002395
2396 // If the client is the first one active on preferred mixer parameters, reopen the output
2397 // if the current mixer parameters doesn't match the preferred one.
2398 if (outputDesc->devices().size() == 1) {
2399 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2400 outputDesc->devices()[0]->getId(), client->strategy());
2401 if (info != nullptr && info->getUid() == client->uid()) {
2402 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2403 info->getConfigBase(), info->getFlags())) {
2404 stopSource(outputDesc, client);
2405 outputDesc->stop();
2406 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2407 config.channel_mask = info->getConfigBase().channel_mask;
2408 config.sample_rate = info->getConfigBase().sample_rate;
2409 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002410 sp<SwAudioOutputDescriptor> desc =
2411 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2412 if (desc == nullptr) {
2413 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002414 }
jiabin220eea12024-05-17 17:55:20 +00002415 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002416 // Intentionally return error to let the client side resending request for
2417 // creating and starting.
2418 return DEAD_OBJECT;
2419 }
2420 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002421 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002422 // If it is first bit-perfect client, reroute all clients that will be routed to
2423 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2424 PortHandleVector clientsToInvalidate;
jiabine6b87492024-09-18 23:36:14 +00002425 std::vector<sp<SwAudioOutputDescriptor>> outputsToResetDevice;
jiabine3d1f552023-06-14 17:42:17 +00002426 for (size_t i = 0; i < mOutputs.size(); i++) {
jiabinfedb92e2024-09-16 21:36:30 +00002427 if (mOutputs[i] == outputDesc || (!mOutputs[i]->devices().isEmpty() &&
2428 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty())) {
jiabine3d1f552023-06-14 17:42:17 +00002429 continue;
2430 }
jiabine6b87492024-09-18 23:36:14 +00002431 if (mOutputs[i]->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
2432 outputsToResetDevice.push_back(mOutputs[i]);
2433 }
jiabine3d1f552023-06-14 17:42:17 +00002434 for (const auto& c : mOutputs[i]->getClientIterable()) {
2435 clientsToInvalidate.push_back(c->portId());
2436 }
2437 }
2438 if (!clientsToInvalidate.empty()) {
2439 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2440 __func__);
2441 mpClientInterface->invalidateTracks(clientsToInvalidate);
2442 }
jiabine6b87492024-09-18 23:36:14 +00002443 for (const auto& output : outputsToResetDevice) {
2444 resetOutputDevice(output, 0 /*delayMs*/, nullptr /*patchHandle*/);
2445 }
jiabine3d1f552023-06-14 17:42:17 +00002446 }
jiabina84c3d32022-12-02 18:59:55 +00002447 }
2448 }
2449
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002450 if (client->hasPreferredDevice()) {
2451 // playback activity with preferred device impacts routing occurred, inform upper layers
2452 mpClientInterface->onRoutingUpdated();
2453 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002454 if (delayMs != 0) {
2455 usleep(delayMs * 1000);
2456 }
2457
jiabin220eea12024-05-17 17:55:20 +00002458 if (status == NO_ERROR &&
2459 outputDesc->mPreferredAttrInfo != nullptr &&
2460 outputDesc->isBitPerfect() &&
2461 com::android::media::audioserver::
2462 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2463 // A new client is started on bit-perfect output, update all clients internal mute.
2464 updateClientsInternalMute(outputDesc);
2465 }
2466
Eric Laurentc75307b2015-03-17 15:29:32 -07002467 return status;
2468}
2469
Eric Laurent96d1dda2022-03-14 17:14:19 +01002470bool AudioPolicyManager::isLeUnicastActive() const {
2471 if (isInCall()) {
2472 return true;
2473 }
2474 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2475}
2476
2477bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2478 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2479 return false;
2480 }
2481 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2482 ALOGV("%s active %d", __func__, active);
2483 return active;
2484}
2485
Eric Laurent97ac8712018-07-27 18:59:02 -07002486status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2487 const sp<TrackClientDescriptor>& client,
2488 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002489{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002490 // cannot start playback of STREAM_TTS if any other output is being used
2491 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002492
2493 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002494 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002495 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002496 auto clientStrategy = client->strategy();
2497 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002498 if (stream == AUDIO_STREAM_TTS) {
2499 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002500 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002501 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002502 return INVALID_OPERATION;
2503 } else {
2504 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2505 }
2506 } else {
2507 // some playback other than beacon starts
2508 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2509 }
2510
Eric Laurent77305a62016-07-25 16:39:22 -07002511 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002512 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002513 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002514
François Gaffie11d30102018-11-02 16:09:09 +01002515 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002516 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002517 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002518 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002519 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002520 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002521 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002522 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002523 } else {
2524 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002525 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002526 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2527 AUDIO_FORMAT_DEFAULT);
2528 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2529 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002530 }
2531
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002532 // requiresMuteCheck is false when we can bypass mute strategy.
2533 // It covers a common case when there is no materially active audio
2534 // and muting would result in unnecessary delay and dropped audio.
2535 const uint32_t outputLatencyMs = outputDesc->latency();
2536 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002537 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002538
Eric Laurente552edb2014-03-10 17:42:56 -07002539 // increment usage count for this stream on the requested output:
2540 // NOTE that the usage count is the same for duplicated output and hardware output which is
2541 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002542 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002543
2544 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002545 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002546 // Preferred device may be exclusive, use only if no other active clients on this output
2547 devices = DeviceVector(
2548 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2549 } else {
2550 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2551 }
François Gaffie11d30102018-11-02 16:09:09 +01002552 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002553 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002554 }
2555 }
Eric Laurente552edb2014-03-10 17:42:56 -07002556
François Gaffiec005e562018-11-06 15:04:49 +01002557 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002558 selectOutputForMusicEffects();
2559 }
2560
François Gaffie1c878552018-11-22 16:53:21 +01002561 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002562 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002563 if (devices.isEmpty()) {
2564 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002565 }
François Gaffiec005e562018-11-06 15:04:49 +01002566 bool shouldWait =
2567 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2568 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2569 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002570 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002571 const bool needToCloseBitPerfectOutput =
2572 (com::android::media::audioserver::
2573 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2574 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2575 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002576 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002577 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002578 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002579 // An output has a shared device if
2580 // - managed by the same hw module
2581 // - supports the currently selected device
2582 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002583 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002584
Eric Laurent77305a62016-07-25 16:39:22 -07002585 // force a device change if any other output is:
2586 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002587 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002588 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002589 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002590 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002591 // change the device currently selected by the other output.
2592 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002593 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002594 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002595 force = true;
2596 }
2597 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002598 // a notification so that audio focus effect can propagate, or that a mute/unmute
2599 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002600 const uint32_t latencyMs = desc->latency();
2601 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2602
2603 if (shouldWait && isActive && (waitMs < latencyMs)) {
2604 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002605 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002606
2607 // Require mute check if another output is on a shared device
2608 // and currently active to have proper drain and avoid pops.
2609 // Note restoring AudioTracks onto this output needs to invoke
2610 // a volume ramp if there is no mute.
2611 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002612
2613 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2614 outputsToReopen.push_back(desc);
2615 }
Eric Laurente552edb2014-03-10 17:42:56 -07002616 }
2617 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002618
jiabin220eea12024-05-17 17:55:20 +00002619 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002620 // If the output is open with preferred mixer attributes, but the routed device is
2621 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2622 // changed.
2623 return DEAD_OBJECT;
2624 }
jiabin220eea12024-05-17 17:55:20 +00002625 for (auto& outputToReopen : outputsToReopen) {
2626 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2627 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002628 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302629 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2630 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002631
Eric Laurente552edb2014-03-10 17:42:56 -07002632 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002633 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002634 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002635 curves.getVolumeIndex(outputDesc->devices().types()),
Vlad Popa1e865e62024-08-15 19:11:42 -07002636 outputDesc, outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002637 outputDesc->useHwGain() /*force*/)) {
2638 // request AudioService to reinitialize the volume curves asynchronously
2639 ALOGE("checkAndSetVolume failed, requesting volume range init");
2640 mpClientInterface->onVolumeRangeInitRequest();
2641 };
Eric Laurente552edb2014-03-10 17:42:56 -07002642
2643 // update the outputs if starting an output with a stream that can affect notification
2644 // routing
2645 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002646
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002647 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002648 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002649 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002650 }
Eric Laurentdc462862016-07-19 12:29:53 -07002651
2652 if (waitMs > muteWaitMs) {
2653 *delayMs = waitMs - muteWaitMs;
2654 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002655
2656 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2657 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2658 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2659 // change occurs after the MixerThread starts and causes a stream volume
2660 // glitch.
2661 //
2662 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002663 }
Eric Laurentdc462862016-07-19 12:29:53 -07002664
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002665 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002666 mEngine->getForceUse(
2667 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002668 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002669 }
2670
Eric Laurent97ac8712018-07-27 18:59:02 -07002671 // Automatically enable the remote submix input when output is started on a re routing mix
2672 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002673 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2674 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002675 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2676 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2677 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002678 "remote-submix",
2679 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002680 }
2681
Eric Laurent96d1dda2022-03-14 17:14:19 +01002682 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2683
Eric Laurente552edb2014-03-10 17:42:56 -07002684 return NO_ERROR;
2685}
2686
Eric Laurent96d1dda2022-03-14 17:14:19 +01002687void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2688 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2689 bool isUnicastActive = isLeUnicastActive();
2690
2691 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002692 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002693 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2694 for (size_t i = 0; i < mOutputs.size(); i++) {
2695 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2696 if (desc != ignoredOutput && desc->isActive()
2697 && ((isUnicastActive &&
2698 !desc->devices().
2699 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2700 || (wasUnicastActive &&
2701 !desc->devices().getDevicesFromTypes(
2702 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2703 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2704 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002705 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002706 // If the device is using preferred mixer attributes, the output need to reopen
2707 // with default configuration when the new selected devices are different from
2708 // current routing devices.
2709 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2710 continue;
2711 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302712 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002713 // re-apply device specific volume if not done by setOutputDevice()
2714 if (!force) {
2715 applyStreamVolumes(desc, newDevices.types(), delayMs);
2716 }
2717 }
2718 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002719 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002720 }
2721}
2722
Eric Laurent8fc147b2018-07-22 19:13:55 -07002723status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002724{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002725 ALOGV("%s portId %d", __FUNCTION__, portId);
2726
2727 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2728 if (outputDesc == 0) {
2729 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002730 return BAD_VALUE;
2731 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002732 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002733
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002734 if (client->hasPreferredDevice(true)) {
2735 // playback activity with preferred device impacts routing occurred, inform upper layers
2736 mpClientInterface->onRoutingUpdated();
2737 }
2738
Eric Laurent97ac8712018-07-27 18:59:02 -07002739 ALOGV("stopOutput() output %d, stream %d, session %d",
2740 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002741
Eric Laurent97ac8712018-07-27 18:59:02 -07002742 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002743
Eric Laurent733ce942017-12-07 12:18:25 -08002744 if (status == NO_ERROR ) {
2745 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002746 } else {
2747 return status;
2748 }
2749
2750 if (outputDesc->devices().size() == 1) {
2751 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2752 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002753 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002754 if (info != nullptr && info->getUid() == client->uid()) {
2755 info->decreaseActiveClient();
2756 if (info->getActiveClientCount() == 0) {
2757 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002758 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002759 }
2760 }
jiabin220eea12024-05-17 17:55:20 +00002761 if (com::android::media::audioserver::
2762 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2763 !outputReopened && outputDesc->isBitPerfect()) {
2764 // Only need to update the clients' internal mute when the output is bit-perfect and it
2765 // is not reopened.
2766 updateClientsInternalMute(outputDesc);
2767 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002768 }
2769 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002770}
2771
Eric Laurent97ac8712018-07-27 18:59:02 -07002772status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2773 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002774{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002775 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002776 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002777 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002778 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002779
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002780 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2781
François Gaffie1c878552018-11-22 16:53:21 +01002782 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2783 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002784 // Automatically disable the remote submix input when output is stopped on a
2785 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002786 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002787 if (isSingleDeviceType(
2788 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002789 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002790 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002791 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2792 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002793 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002794 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002795 }
2796 }
2797 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002798 if (client->hasPreferredDevice(true) &&
2799 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002800 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002801 forceDeviceUpdate = true;
2802 }
2803
Eric Laurente552edb2014-03-10 17:42:56 -07002804 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002805 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002806
Eric Laurente552edb2014-03-10 17:42:56 -07002807 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002808 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002809 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002810 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002811
2812 // If the routing does not change, if an output is routed on a device using HwGain
2813 // (aka setAudioPortConfig) and there are still active clients following different
2814 // volume group(s), force reapply volume
2815 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2816 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2817
Eric Laurente552edb2014-03-10 17:42:56 -07002818 // delay the device switch by twice the latency because stopOutput() is executed when
2819 // the track stop() command is received and at that time the audio track buffer can
2820 // still contain data that needs to be drained. The latency only covers the audio HAL
2821 // and kernel buffers. Also the latency does not always include additional delay in the
2822 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302823 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002824 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002825
2826 // force restoring the device selection on other active outputs if it differs from the
2827 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002828 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002829 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002830 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002831 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002832 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002833 desc->isActive() &&
2834 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002835 (newDevices != desc->devices())) {
2836 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2837 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002838
jiabin220eea12024-05-17 17:55:20 +00002839 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002840 // If the device is using preferred mixer attributes, the output need to
2841 // reopen with default configuration when the new selected devices are
2842 // different from current routing devices.
2843 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2844 continue;
2845 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302846 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002847
Eric Laurent57de36c2016-09-28 16:59:11 -07002848 // re-apply device specific volume if not done by setOutputDevice()
2849 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002850 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002851 }
Eric Laurente552edb2014-03-10 17:42:56 -07002852 }
2853 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002854 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002855 // update the outputs if stopping one with a stream that can affect notification routing
2856 handleNotificationRoutingForStream(stream);
2857 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002858
2859 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2860 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002861 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002862 }
2863
François Gaffiec005e562018-11-06 15:04:49 +01002864 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002865 selectOutputForMusicEffects();
2866 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002867
2868 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2869
Eric Laurente552edb2014-03-10 17:42:56 -07002870 return NO_ERROR;
2871 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002872 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002873 return INVALID_OPERATION;
2874 }
2875}
2876
jiabinbce0c1d2020-10-05 11:20:18 -07002877bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002878{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002879 ALOGV("%s portId %d", __FUNCTION__, portId);
2880
2881 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2882 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002883 // If an output descriptor is closed due to a device routing change,
2884 // then there are race conditions with releaseOutput from tracks
2885 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2886 // destroyed shortly thereafter.
2887 //
2888 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002889 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002890 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002891 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002892
2893 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002894
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302895 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2896 if (outputDesc->isClientActive(client)) {
2897 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2898 stopOutput(portId);
2899 }
2900
Eric Laurent8fc147b2018-07-22 19:13:55 -07002901 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2902 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002903 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002904 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002905 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002906 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002907 if (--outputDesc->mDirectOpenCount == 0) {
2908 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002909 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002910 }
2911 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302912
Andy Hung39efb7a2018-09-26 15:39:28 -07002913 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002914 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2915 // The output is pending reopened to query dynamic profiles and
2916 // there is no active clients
2917 closeOutput(outputDesc->mIoHandle);
2918 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2919 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2920 if (newOutputDesc == nullptr) {
2921 ALOGE("%s failed to open output", __func__);
2922 }
2923 return true;
2924 }
2925 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002926}
2927
Eric Laurentcaf7f482014-11-25 17:50:47 -08002928status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2929 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002930 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002931 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002932 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002933 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002934 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002935 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002936 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002937 audio_port_handle_t *portId,
2938 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002939{
François Gaffiec005e562018-11-06 15:04:49 +01002940 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002941 "flags %#x attributes=%s requested device ID %d",
2942 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2943 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002944
Eric Laurentad2e7b92017-09-14 20:06:42 -07002945 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002946 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002947 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002948 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002949 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002950 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002951 sp<RecordClientDescriptor> clientDesc;
2952 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002953 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002954 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002955
2956 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2957 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2958 return INVALID_OPERATION;
2959 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002960
Francois Gaffie716e1432019-01-14 16:58:59 +01002961 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2962 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002963 }
2964
Paul McLean466dc8e2015-04-17 13:15:36 -06002965 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002966 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002967 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002968
Eric Laurentad2e7b92017-09-14 20:06:42 -07002969 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2970 // possible
2971 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2972 *input != AUDIO_IO_HANDLE_NONE) {
2973 ssize_t index = mInputs.indexOfKey(*input);
2974 if (index < 0) {
2975 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2976 status = BAD_VALUE;
2977 goto error;
2978 }
2979 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002980 RecordClientVector clients = inputDesc->getClientsForSession(session);
2981 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002982 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2983 status = BAD_VALUE;
2984 goto error;
2985 }
2986 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2987 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002988 // corresponds to a new client and is only permitted from the same UID.
2989 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002990 if (clients.size() > 1) {
2991 for (const auto& client : clients) {
2992 // The client map is ordered by key values (portId) and portIds are allocated
2993 // incrementaly. So the first client in this list is the one opened by audio flinger
2994 // when the mmap stream is created and should be ignored as it does not correspond
2995 // to an actual client
2996 if (client == *clients.cbegin()) {
2997 continue;
2998 }
2999 if (uid != client->uid() && !client->isSilenced()) {
3000 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
3001 uid, client->portId(), client->uid());
3002 status = INVALID_OPERATION;
3003 goto error;
3004 }
Eric Laurent331679c2018-04-16 17:03:16 -07003005 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003006 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003007 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01003008 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07003009
Eric Laurentfecbceb2021-02-09 14:46:43 +01003010 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003011 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003012 }
3013
3014 *input = AUDIO_IO_HANDLE_NONE;
3015 *inputType = API_INPUT_INVALID;
3016
Francois Gaffie716e1432019-01-14 16:58:59 +01003017 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02003018 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003019 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003020 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003021 ALOGW("%s could not find input mix for attr %s",
3022 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07003023 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01003024 }
jiabinc1de2df2019-05-07 14:26:40 -07003025 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
3026 String8(attr->tags + strlen("addr=")),
3027 AUDIO_FORMAT_DEFAULT);
3028 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07003029 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07003030 __func__, attributes.source, attributes.tags);
3031 status = BAD_VALUE;
3032 goto error;
3033 }
3034
Kevin Rocard25f9b052019-02-27 15:08:54 -08003035 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
3036 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
3037 } else {
3038 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
3039 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01003040 if (virtualDeviceId) {
3041 *virtualDeviceId = policyMix->mVirtualDeviceId;
3042 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003043 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003044 if (explicitRoutingDevice != nullptr) {
3045 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07003046 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01003047 // Prevent from storing invalid requested device id in clients
3048 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003049 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08003050 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
3051 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07003052 }
François Gaffie11d30102018-11-02 16:09:09 +01003053 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003054 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003055 status = BAD_VALUE;
3056 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08003057 }
Alden DSouzab7d20782021-02-08 08:51:42 -08003058 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
3059 *inputType = API_INPUT_MIX_CAPTURE;
3060 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01003061 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3062 // there is an external policy, but this input is attached to a mix of recorders,
3063 // meaning it receives audio injected into the framework, so the recorder doesn't
3064 // know about it and is therefore considered "legacy"
3065 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003066
3067 if (virtualDeviceId) {
3068 *virtualDeviceId = policyMix->mVirtualDeviceId;
3069 }
François Gaffie11d30102018-11-02 16:09:09 +01003070 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003071 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003072 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003073 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003074 } else {
3075 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003076 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003077
Eric Laurent599c7582015-12-07 18:05:55 -08003078 }
3079
François Gaffiec005e562018-11-06 15:04:49 +01003080 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003081 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003082 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003083 AudioProfileVector profiles;
3084 status_t ret = getProfilesForDevices(
3085 DeviceVector(device), profiles, flags, true /*isInput*/);
3086 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003087 const auto channels = profiles[0]->getChannels();
3088 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3089 config->channel_mask = *channels.begin();
3090 }
3091 const auto sampleRates = profiles[0]->getSampleRates();
3092 if (!sampleRates.empty() &&
3093 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3094 config->sample_rate = *sampleRates.begin();
3095 }
jiabinf1c73972022-04-14 16:28:52 -07003096 config->format = profiles[0]->getFormat();
3097 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003098 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003099 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003100
Marvin Ramine5a122d2023-12-07 13:57:59 +01003101
3102 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3103 *virtualDeviceId = policyMix->mVirtualDeviceId;
3104 }
3105
Eric Laurent8f42ea12018-08-08 09:08:25 -07003106exit:
3107
François Gaffiec005e562018-11-06 15:04:49 +01003108 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3109 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003110
Francois Gaffie716e1432019-01-14 16:58:59 +01003111 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003112 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003113 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003114
Mikhail Naganov2996f672019-04-18 12:29:59 -07003115 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003116 requestedDeviceId, attributes.source, flags,
3117 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003118 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003119 // Move (if found) effect for the client session to its input
3120 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003121 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003122
3123 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3124 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003125
Eric Laurent599c7582015-12-07 18:05:55 -08003126 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003127
3128error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003129 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003130}
3131
3132
François Gaffie11d30102018-11-02 16:09:09 +01003133audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003134 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003135 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003136 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003137 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003138 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003139{
3140 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003141 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003142 bool isSoundTrigger = false;
3143
François Gaffiec005e562018-11-06 15:04:49 +01003144 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003145 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3146 if (index >= 0) {
3147 input = mSoundTriggerSessions.valueFor(session);
3148 isSoundTrigger = true;
3149 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3150 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3151 } else {
3152 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003153 }
François Gaffiec005e562018-11-06 15:04:49 +01003154 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003155 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003156 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003157 }
3158
Carter Hsua3abb402021-10-26 11:11:20 +08003159 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3160 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3161 }
3162
Eric Laurentfe231122017-11-17 17:48:06 -08003163 // sampling rate and flags may be updated by getInputProfile
3164 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3165 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003166 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003167 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003168 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003169 // find a compatible input profile (not necessarily identical in parameters)
3170 sp<IOProfile> profile = getInputProfile(
3171 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3172 if (profile == nullptr) {
3173 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003174 }
jiabin2fd710d2022-05-02 23:20:22 +00003175
Glenn Kasten05ddca52016-02-11 08:17:12 -08003176 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003177 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003178 if (samplingRate == 0) {
3179 samplingRate = profileSamplingRate;
3180 }
Eric Laurente552edb2014-03-10 17:42:56 -07003181
Eric Laurent322b4d22015-04-03 15:57:54 -07003182 if (profile->getModuleHandle() == 0) {
3183 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003184 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003185 }
3186
Eric Laurentec376dc2021-04-08 20:41:22 +02003187 // Reuse an already opened input if a client with the same session ID already exists
3188 // on that input
3189 for (size_t i = 0; i < mInputs.size(); i++) {
3190 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3191 if (desc->mProfile != profile) {
3192 continue;
3193 }
3194 RecordClientVector clients = desc->clientsList();
3195 for (const auto &client : clients) {
3196 if (session == client->session()) {
3197 return desc->mIoHandle;
3198 }
3199 }
3200 }
3201
Eric Laurentc71b11b2024-06-03 12:54:53 +00003202 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003203 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003204 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3205 // First pick best candidate for preemption (there may not be any):
3206 // - Preempt and input if:
3207 // - It has only strictly lower priority use cases than the new client
3208 // - It has equal priority use cases than the new client, was not
3209 // opened thanks to preemption or has been active since opened.
3210 // - Order the preemption candidates by inactive first and priority second
3211 sp<AudioInputDescriptor> closeCandidate;
3212 int leastCloseRank = INT_MAX;
3213 static const int sCloseActive = 0x100;
3214
3215 for (size_t i = 0; i < mInputs.size(); i++) {
3216 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3217 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003218 continue;
3219 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003220 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3221 if (topPrioClient == nullptr) {
3222 continue;
3223 }
3224 int topPrio = source_priority(topPrioClient->source());
3225 if (topPrio < source_priority(attributes.source)
3226 || (topPrio == source_priority(attributes.source)
3227 && !desc->isPreemptor())) {
3228 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3229 if (closeRank < leastCloseRank) {
3230 leastCloseRank = closeRank;
3231 closeCandidate = desc;
3232 }
3233 }
3234 }
3235
3236 if (closeCandidate != nullptr) {
3237 closeInput(closeCandidate->mIoHandle);
3238 // Mark the new input as being issued from a preemption
3239 // so that is will not be preempted later
3240 isPreemptor = true;
3241 } else {
3242 // Then pick the best reusable input (There is always one)
3243 // The order of preference is:
3244 // 1) active inputs with same use case as the new client
3245 // 2) inactive inputs with same use case
3246 // 3) active inputs with different use cases
3247 // 4) inactive inputs with different use cases
3248 sp<AudioInputDescriptor> reuseCandidate;
3249 int leastReuseRank = INT_MAX;
3250 static const int sReuseDifferentUseCase = 0x100;
3251
3252 for (size_t i = 0; i < mInputs.size(); i++) {
3253 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3254 if (desc->mProfile != profile) {
3255 continue;
3256 }
3257 int reuseRank = sReuseDifferentUseCase;
3258 for (const auto& client: desc->getClientIterable()) {
3259 if (client->source() == attributes.source) {
3260 reuseRank = 0;
3261 break;
3262 }
3263 }
3264 reuseRank += desc->isActive() ? 0 : 1;
3265 if (reuseRank < leastReuseRank) {
3266 leastReuseRank = reuseRank;
3267 reuseCandidate = desc;
3268 }
3269 }
3270 return reuseCandidate->mIoHandle;
3271 }
3272 } else { // fix_input_sharing_logic()
3273 for (size_t i = 0; i < mInputs.size(); ) {
3274 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3275 if (desc->mProfile != profile) {
3276 i++;
3277 continue;
3278 }
3279 // if sound trigger, reuse input if used by other sound trigger on same session
3280 // else
3281 // reuse input if active client app is not in IDLE state
3282 //
3283 RecordClientVector clients = desc->clientsList();
3284 bool doClose = false;
3285 for (const auto& client : clients) {
3286 if (isSoundTrigger != client->isSoundTrigger()) {
3287 continue;
3288 }
3289 if (client->isSoundTrigger()) {
3290 if (session == client->session()) {
3291 return desc->mIoHandle;
3292 }
3293 continue;
3294 }
3295 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003296 return desc->mIoHandle;
3297 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003298 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003299 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003300 if (doClose) {
3301 closeInput(desc->mIoHandle);
3302 } else {
3303 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003304 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003305 }
3306 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003307 }
3308
Eric Laurentc71b11b2024-06-03 12:54:53 +00003309 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3310 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003311
Eric Laurentfe231122017-11-17 17:48:06 -08003312 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3313 lConfig.sample_rate = profileSamplingRate;
3314 lConfig.channel_mask = profileChannelMask;
3315 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003316
François Gaffie11d30102018-11-02 16:09:09 +01003317 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003318
3319 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003320 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003321 (profileSamplingRate != lConfig.sample_rate) ||
3322 !audio_formats_match(profileFormat, lConfig.format) ||
3323 (profileChannelMask != lConfig.channel_mask)) {
3324 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003325 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003326 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003327 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003328 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003329 }
Eric Laurent599c7582015-12-07 18:05:55 -08003330 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003331 }
3332
Eric Laurentc722f302014-12-10 11:21:49 -08003333 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003334
Eric Laurent599c7582015-12-07 18:05:55 -08003335 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003336 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003337
Eric Laurent599c7582015-12-07 18:05:55 -08003338 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003339}
3340
Eric Laurent4eb58f12018-12-07 16:41:02 -08003341status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003342{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003343 ALOGV("%s portId %d", __FUNCTION__, portId);
3344
3345 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3346 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003347 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003348 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003349 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003350 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003351 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003352 if (client->active()) {
3353 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3354 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003355 }
3356
Eric Laurent8f42ea12018-08-08 09:08:25 -07003357 audio_session_t session = client->session();
3358
Eric Laurent4eb58f12018-12-07 16:41:02 -08003359 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003360
Eric Laurent4eb58f12018-12-07 16:41:02 -08003361 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003362
Eric Laurent4eb58f12018-12-07 16:41:02 -08003363 status_t status = inputDesc->start();
3364 if (status != NO_ERROR) {
3365 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003366 }
Eric Laurente552edb2014-03-10 17:42:56 -07003367
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003368 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003369 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003370 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003371
Eric Laurent8f42ea12018-08-08 09:08:25 -07003372 // indicate active capture to sound trigger service if starting capture from a mic on
3373 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003374 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003375 if (device != nullptr) {
3376 status = setInputDevice(input, device, true /* force */);
3377 } else {
3378 ALOGW("%s no new input device can be found for descriptor %d",
3379 __FUNCTION__, inputDesc->getId());
3380 status = BAD_VALUE;
3381 }
Eric Laurente552edb2014-03-10 17:42:56 -07003382
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003383 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003384 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003385 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003386 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003387 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3388 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003389 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003390 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003391
François Gaffie11d30102018-11-02 16:09:09 +01003392 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3393 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003394 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003395 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003396 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003397
Eric Laurent8f42ea12018-08-08 09:08:25 -07003398 // automatically enable the remote submix output when input is started if not
3399 // used by a policy mix of type MIX_TYPE_RECORDERS
3400 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003401 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003402 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003403 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003404 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003405 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3406 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003407 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003408 if (address != "") {
3409 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3410 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003411 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003412 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003413 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003414 } else if (status != NO_ERROR) {
3415 // Restore client activity state.
3416 inputDesc->setClientActive(client, false);
3417 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003418 }
3419
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003420 ALOGV("%s input %d source = %d status = %d exit",
3421 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003422
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003423 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003424}
3425
Eric Laurent8fc147b2018-07-22 19:13:55 -07003426status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003427{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003428 ALOGV("%s portId %d", __FUNCTION__, portId);
3429
3430 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3431 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003432 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003433 return BAD_VALUE;
3434 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003435 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003436 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003437 if (!client->active()) {
3438 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003439 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003440 }
Carter Hsue6139d52021-07-08 10:30:20 +08003441 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003442 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003443
Eric Laurent8f42ea12018-08-08 09:08:25 -07003444 inputDesc->stop();
3445 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003446 auto current_source = inputDesc->source();
3447 setInputDevice(input, getNewInputDevice(inputDesc),
3448 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003449 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003450 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003451 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003452 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003453 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3454 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003455 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003456 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003457
3458 // automatically disable the remote submix output when input is stopped if not
3459 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003460 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003461 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003462 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003463 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003464 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3465 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003466 }
3467 if (address != "") {
3468 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3469 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003470 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003471 }
3472 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003473 resetInputDevice(input);
3474
3475 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3476 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003477 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3478 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003479 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003480 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003481 }
3482 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003483 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003484 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003485}
3486
Eric Laurent8fc147b2018-07-22 19:13:55 -07003487void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003488{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003489 ALOGV("%s portId %d", __FUNCTION__, portId);
3490
3491 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3492 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003493 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003494 return;
3495 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003496 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003497 audio_io_handle_t input = inputDesc->mIoHandle;
3498
Eric Laurent8f42ea12018-08-08 09:08:25 -07003499 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003500
Andy Hung39efb7a2018-09-26 15:39:28 -07003501 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003502
3503 // If no more clients are present in this session, park effects to an orphan chain
3504 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3505 if (clientsOnSession.size() == 0) {
3506 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3507 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003508 if (inputDesc->getClientCount() > 0) {
3509 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003510 return;
3511 }
3512
Eric Laurent05b90f82014-08-27 15:32:29 -07003513 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003514 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003515 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003516}
3517
Eric Laurent8f42ea12018-08-08 09:08:25 -07003518void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003519{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003520 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003521
3522 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003523 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003524 }
3525}
3526
Eric Laurent8f42ea12018-08-08 09:08:25 -07003527void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3528{
3529 stopInput(portId);
3530 releaseInput(portId);
3531}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003532
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003533bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3534 if (input->clientsList().size() == 0
3535 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3536 return true;
3537 }
3538 for (const auto& client : input->clientsList()) {
3539 sp<DeviceDescriptor> device =
3540 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3541 client->session());
3542 if (!input->supportedDevices().contains(device)) {
3543 return true;
3544 }
3545 }
3546 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3547 return false;
3548}
3549
Eric Laurent0dd51852019-04-19 18:18:58 -07003550void AudioPolicyManager::checkCloseInputs() {
3551 // After connecting or disconnecting an input device, close input if:
3552 // - it has no client (was just opened to check profile) OR
3553 // - none of its supported devices are connected anymore OR
3554 // - one of its clients cannot be routed to one of its supported
3555 // devices anymore. Otherwise update device selection
3556 std::vector<audio_io_handle_t> inputsToClose;
3557 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003558 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003559 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003560 }
3561 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003562 for (const audio_io_handle_t handle : inputsToClose) {
3563 ALOGV("%s closing input %d", __func__, handle);
3564 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003565 }
Eric Laurentd4692962014-05-05 18:13:44 -07003566}
3567
Vlad Popa87e0e582024-05-20 18:49:20 -07003568status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3569 const char *address __unused,
3570 bool enabled,
3571 audio_stream_type_t streamToDriveAbs)
3572{
Vlad Popa08502d82024-10-22 20:17:47 -07003573 ALOGI("%s: deviceType 0x%X, enabled %d, streamToDriveAbs %d", __func__, deviceType, enabled,
3574 streamToDriveAbs);
3575
Vlad Popaa536eb32024-07-18 16:00:35 -07003576 if (!enabled) {
3577 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3578 return NO_ERROR;
3579 }
3580
Vlad Popa87e0e582024-05-20 18:49:20 -07003581 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3582 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3583 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3584 toString(streamToDriveAbs).c_str());
3585 return BAD_VALUE;
3586 }
3587
Vlad Popaa536eb32024-07-18 16:00:35 -07003588 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
Vlad Popa87e0e582024-05-20 18:49:20 -07003589 return NO_ERROR;
3590}
3591
François Gaffie251c7f02018-11-07 10:41:08 +01003592void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003593{
3594 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003595 if (indexMin < 0 || indexMax < 0) {
3596 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3597 return;
3598 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003599 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003600
3601 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003602 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3603 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003604 continue;
3605 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003606 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003607 }
Eric Laurente552edb2014-03-10 17:42:56 -07003608}
3609
Eric Laurente0720872014-03-11 09:30:41 -07003610status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003611 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003612 bool muted,
François Gaffie53615e22015-03-19 09:24:12 +01003613 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003614{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003615 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003616 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3617 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3618 return NO_ERROR;
3619 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303620 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3621 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Vlad Popa1e865e62024-08-15 19:11:42 -07003622 return setVolumeIndexForAttributes(attributes, index, muted, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003623}
3624
Eric Laurente0720872014-03-11 09:30:41 -07003625status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003626 int *index,
3627 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003628{
François Gaffiec005e562018-11-06 15:04:49 +01003629 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3630 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003631 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003632 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003633 deviceTypes = mEngine->getOutputDevicesForStream(
3634 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003635 }
jiabin9a3361e2019-10-01 09:38:30 -07003636 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003637}
3638
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003639status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003640 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003641 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003642 audio_devices_t device)
3643{
3644 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003645 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3646 if (group == VOLUME_GROUP_NONE) {
3647 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003648 return BAD_VALUE;
3649 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003650 ALOGV("%s: group %d matching with %s index %d",
3651 __FUNCTION__, group, toString(attributes).c_str(), index);
Eric Laurentc86a3e12024-10-10 14:26:43 +00003652 if (mEngine->getStreamTypeForAttributes(attributes) == AUDIO_STREAM_PATCH) {
3653 ALOGV("%s: cannot change volume for PATCH stream, attrs: %s",
3654 __FUNCTION__, toString(attributes).c_str());
3655 return NO_ERROR;
3656 }
François Gaffiecfe17322018-11-07 13:41:29 +01003657 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003658 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003659 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003660 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3661 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3662 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3663 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003664 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3665
Vlad Popa1e865e62024-08-15 19:11:42 -07003666
3667 status = setVolumeCurveIndex(index, muted, device, curves);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003668 if (status != NO_ERROR) {
3669 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3670 return status;
3671 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003672
jiabin9a3361e2019-10-01 09:38:30 -07003673 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003674 auto curCurvAttrs = curves.getAttributes();
3675 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3676 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003677 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003678 } else if (!curves.getStreamTypes().empty()) {
3679 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003680 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003681 } else {
3682 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3683 return BAD_VALUE;
3684 }
jiabin9a3361e2019-10-01 09:38:30 -07003685 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3686 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003687
François Gaffiecfe17322018-11-07 13:41:29 +01003688 // update volume on all outputs and streams matching the following:
3689 // - The requested stream (or a stream matching for volume control) is active on the output
3690 // - The device (or devices) selected by the engine for this stream includes
3691 // the requested device
3692 // - For non default requested device, currently selected device on the output is either the
3693 // requested device or one of the devices selected by the engine for this stream
3694 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3695 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003696 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003697 for (size_t i = 0; i < mOutputs.size(); i++) {
3698 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003699 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003700
jiabin9a3361e2019-10-01 09:38:30 -07003701 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3702 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003703 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003704
3705 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003706 continue;
3707 }
3708 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3709 curDevices.find(device) == curDevices.end()) {
3710 continue;
3711 }
3712 bool applyVolume = false;
3713 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3714 curSrcDevices.insert(device);
3715 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003716 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3717 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003718 } else {
3719 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3720 }
3721 if (!applyVolume) {
3722 continue; // next output
3723 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003724 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3725 // If a higher priority strategy is active, and the output is routed to a device with a
3726 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003727 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003728 applyVolume = false;
Vlad Popa1e865e62024-08-15 19:11:42 -07003729 bool swMute = com_android_media_audio_ring_my_car() ? curves.isMuted() : (index == 0);
Francois Gaffie593634d2021-06-22 13:31:31 +02003730 // If the volume source is active with higher priority source, ensure at least Sw Muted
Vlad Popa1e865e62024-08-15 19:11:42 -07003731 desc->setSwMute(swMute, vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003732 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3733 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3734 false /*preferredDevice*/);
3735 if (activeClients.empty()) {
3736 continue;
3737 }
3738 bool isPreempted = false;
3739 bool isHigherPriority = productStrategy < strategy;
3740 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003741 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003742 ALOGV("%s: Strategy=%d (\nrequester:\n"
3743 " group %d, volumeGroup=%d attributes=%s)\n"
3744 " higher priority source active:\n"
3745 " volumeGroup=%d attributes=%s) \n"
3746 " on output %zu, bailing out", __func__, productStrategy,
3747 group, group, toString(attributes).c_str(),
3748 client->volumeSource(), toString(client->attributes()).c_str(), i);
3749 applyVolume = false;
3750 isPreempted = true;
3751 break;
3752 }
3753 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003754 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003755 applyVolume = true;
3756 }
3757 }
3758 if (isPreempted || applyVolume) {
3759 break;
3760 }
3761 }
3762 if (!applyVolume) {
3763 continue; // next output
3764 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003765 }
François Gaffieed91f582020-01-31 10:35:37 +01003766 //FIXME: workaround for truncated touch sounds
3767 // delayed volume change for system stream to be removed when the problem is
3768 // handled by system UI
Vlad Popa1e865e62024-08-15 19:11:42 -07003769 status_t volStatus = checkAndSetVolume(curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003770 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003771 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3772 if (volStatus != NO_ERROR) {
3773 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003774 }
3775 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003776
3777 // update voice volume if the an active call route exists
3778 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3779 && (curSrcDevices.find(
3780 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3781 != curSrcDevices.end())) {
3782 bool isVoiceVolSrc;
3783 bool isBtScoVolSrc;
3784 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3785 isVoiceVolSrc, isBtScoVolSrc, __func__)
3786 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003787 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3788 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3789 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003790 }
3791 }
3792
François Gaffiecfe17322018-11-07 13:41:29 +01003793 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3794 return status;
3795}
3796
François Gaffieaaac0fd2018-11-22 17:56:39 +01003797status_t AudioPolicyManager::setVolumeCurveIndex(int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003798 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003799 audio_devices_t device,
3800 IVolumeCurves &volumeCurves)
3801{
3802 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3803 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003804 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3805 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003806 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303807 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3808 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003809 return BAD_VALUE;
3810 }
3811 if (!audio_is_output_device(device)) {
3812 return BAD_VALUE;
3813 }
3814
3815 // Force max volume if stream cannot be muted
3816 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3817
Vlad Popa1e865e62024-08-15 19:11:42 -07003818 ALOGV("%s device %08x, index %d, muted %d", __FUNCTION__ , device, index, muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003819 volumeCurves.addCurrentVolumeIndex(device, index);
Vlad Popa1e865e62024-08-15 19:11:42 -07003820 volumeCurves.setIsMuted(muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003821 return NO_ERROR;
3822}
3823
3824status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3825 int &index,
3826 audio_devices_t device)
3827{
3828 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3829 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003830 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003831 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003832 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003833 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003834 }
jiabin9a3361e2019-10-01 09:38:30 -07003835 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003836}
3837
3838status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3839 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003840 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003841{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003842 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003843 return BAD_VALUE;
3844 }
jiabin9a3361e2019-10-01 09:38:30 -07003845 index = curves.getVolumeIndex(deviceTypes);
3846 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003847 return NO_ERROR;
3848}
3849
3850status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3851 int &index)
3852{
3853 index = getVolumeCurves(attr).getVolumeIndexMin();
3854 return NO_ERROR;
3855}
3856
3857status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3858 int &index)
3859{
3860 index = getVolumeCurves(attr).getVolumeIndexMax();
3861 return NO_ERROR;
3862}
3863
Eric Laurent36829f92017-04-07 19:04:42 -07003864audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003865{
3866 // select one output among several suitable for global effects.
3867 // The priority is as follows:
3868 // 1: An offloaded output. If the effect ends up not being offloadable,
3869 // AudioFlinger will invalidate the track and the offloaded output
3870 // will be closed causing the effect to be moved to a PCM output.
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003871 // 2: Spatializer output if the stereo spatializer feature enabled
3872 // 3: A deep buffer output
3873 // 4: The primary output
3874 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003875
François Gaffiec005e562018-11-06 15:04:49 +01003876 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3877 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003878 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003879
Eric Laurent36829f92017-04-07 19:04:42 -07003880 if (outputs.size() == 0) {
3881 return AUDIO_IO_HANDLE_NONE;
3882 }
Eric Laurente552edb2014-03-10 17:42:56 -07003883
Eric Laurent36829f92017-04-07 19:04:42 -07003884 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3885 bool activeOnly = true;
3886
3887 while (output == AUDIO_IO_HANDLE_NONE) {
3888 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003889 audio_io_handle_t outputSpatializer = AUDIO_IO_HANDLE_NONE;
Eric Laurent36829f92017-04-07 19:04:42 -07003890 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3891 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3892
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003893 for (audio_io_handle_t outputLoop : outputs) {
3894 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputLoop);
Eric Laurent83d17c22019-04-02 17:10:01 -07003895 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003896 continue;
3897 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003898 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003899 activeOnly, outputLoop, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003900 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003901 outputOffloaded = outputLoop;
3902 }
3903 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
3904 if (SpatializerHelper::isStereoSpatializationFeatureEnabled()) {
3905 outputSpatializer = outputLoop;
3906 }
Eric Laurent36829f92017-04-07 19:04:42 -07003907 }
3908 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003909 outputDeepBuffer = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003910 }
3911 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003912 outputPrimary = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003913 }
3914 }
3915 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3916 output = outputOffloaded;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003917 } else if (outputSpatializer != AUDIO_IO_HANDLE_NONE) {
3918 output = outputSpatializer;
Eric Laurent36829f92017-04-07 19:04:42 -07003919 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3920 output = outputDeepBuffer;
3921 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3922 output = outputPrimary;
3923 } else {
3924 output = outputs[0];
3925 }
3926 activeOnly = false;
3927 }
3928
3929 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003930 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3931 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003932 mMusicEffectOutput = output;
3933 }
3934
3935 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003936 return output;
3937}
3938
Eric Laurent36829f92017-04-07 19:04:42 -07003939audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3940{
3941 return selectOutputForMusicEffects();
3942}
3943
Eric Laurente0720872014-03-11 09:30:41 -07003944status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003945 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003946 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003947 int session,
3948 int id)
3949{
Shunkai Yao29d10572024-03-19 04:31:47 +00003950 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003951 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003952 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003953 index = mInputs.indexOfKey(io);
3954 if (index < 0) {
3955 ALOGW("registerEffect() unknown io %d", io);
3956 return INVALID_OPERATION;
3957 }
Eric Laurente552edb2014-03-10 17:42:56 -07003958 }
3959 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003960 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3961 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3962 || strategy == PRODUCT_STRATEGY_NONE));
3963 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003964}
3965
Eric Laurentc241b0d2018-11-28 09:08:49 -08003966status_t AudioPolicyManager::unregisterEffect(int id)
3967{
3968 if (mEffects.getEffect(id) == nullptr) {
3969 return INVALID_OPERATION;
3970 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003971 if (mEffects.isEffectEnabled(id)) {
3972 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3973 setEffectEnabled(id, false);
3974 }
3975 return mEffects.unregisterEffect(id);
3976}
3977
3978status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3979{
3980 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3981 if (effect == nullptr) {
3982 return INVALID_OPERATION;
3983 }
3984
3985 status_t status = mEffects.setEffectEnabled(id, enabled);
3986 if (status == NO_ERROR) {
3987 mInputs.trackEffectEnabled(effect, enabled);
3988 }
3989 return status;
3990}
3991
Eric Laurent6c796322019-04-09 14:13:17 -07003992
3993status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3994{
3995 mEffects.moveEffects(ids, io);
3996 return NO_ERROR;
3997}
3998
Eric Laurentc75307b2015-03-17 15:29:32 -07003999bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
4000{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01004001 auto vs = toVolumeSource(stream, false);
4002 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07004003}
4004
4005bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
4006{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01004007 auto vs = toVolumeSource(stream, false);
4008 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07004009}
4010
Eric Laurente0720872014-03-11 09:30:41 -07004011bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07004012{
4013 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004014 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08004015 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004016 return true;
4017 }
4018 }
4019 return false;
4020}
4021
Eric Laurent275e8e92014-11-30 15:14:47 -08004022// Register a list of custom mixes with their attributes and format.
4023// When a mix is registered, corresponding input and output profiles are
4024// added to the remote submix hw module. The profile contains only the
4025// parameters (sampling rate, format...) specified by the mix.
4026// The corresponding input remote submix device is also connected.
4027//
4028// When a remote submix device is connected, the address is checked to select the
4029// appropriate profile and the corresponding input or output stream is opened.
4030//
4031// When capture starts, getInputForAttr() will:
4032// - 1 look for a mix matching the address passed in attribtutes tags if any
4033// - 2 if none found, getDeviceForInputSource() will:
4034// - 2.1 look for a mix matching the attributes source
4035// - 2.2 if none found, default to device selection by policy rules
4036// At this time, the corresponding output remote submix device is also connected
4037// and active playback use cases can be transferred to this mix if needed when reconnecting
4038// after AudioTracks are invalidated
4039//
4040// When playback starts, getOutputForAttr() will:
4041// - 1 look for a mix matching the address passed in attribtutes tags if any
4042// - 2 if none found, look for a mix matching the attributes usage
4043// - 3 if none found, default to device and output selection by policy rules.
4044
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004045status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08004046{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004047 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
4048 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004049 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004050 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01004051 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004052 // examine each mix's route type
4053 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004054 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08004055 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
4056 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
4057 ALOGE("Unsupported Policy Mix %zu of %zu: "
4058 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
4059 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004060 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08004061 break;
4062 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08004063 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
4064 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07004065 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004066 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
4067 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004068 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004069 rSubmixModule = mHwModules.getModuleFromName(
4070 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4071 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004072 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08004073 i);
4074 res = INVALID_OPERATION;
4075 break;
4076 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004077 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004078
Eric Laurent97ac8712018-07-27 18:59:02 -07004079 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004080 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004081 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004082 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004083 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4084 } else {
4085 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4086 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004087 }
François Gaffie036e1e92015-03-19 10:16:24 +01004088
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004089 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004090 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004091 res = INVALID_OPERATION;
4092 break;
4093 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004094 audio_config_t outputConfig = mix.mFormat;
4095 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004096 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4097 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004098 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4099 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004100 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004101 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4102 audio_is_linear_pcm(outputConfig.format)
4103 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004104 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004105 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4106 audio_is_linear_pcm(inputConfig.format)
4107 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004108
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004109 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004110 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004111 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004112 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004113 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004114 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004115 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004116 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4117 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004118 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004119 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004120 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004121
4122 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4123 mix.mDeviceType, mix.mDeviceAddress,
4124 String8(), AUDIO_FORMAT_DEFAULT);
4125 if (device == nullptr) {
4126 res = INVALID_OPERATION;
4127 break;
4128 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004129
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004130 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004131 // First try to find an already opened output supporting the device
4132 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004133 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004134
Eric Laurentc529cf62020-04-17 18:19:10 -07004135 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004136 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004137 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004138 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004139 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004140 } else {
4141 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004142 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004143 }
4144 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004145 // If no output found, try to find a direct output profile supporting the device
4146 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4147 sp<HwModule> module = mHwModules[i];
4148 for (size_t j = 0;
4149 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4150 j++) {
4151 sp<IOProfile> profile = module->getOutputProfiles()[j];
4152 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4153 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4154 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004155 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004156 res = INVALID_OPERATION;
4157 } else {
4158 foundOutput = true;
4159 }
4160 }
4161 }
4162 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004163 if (res != NO_ERROR) {
4164 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004165 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004166 res = INVALID_OPERATION;
4167 break;
4168 } else if (!foundOutput) {
4169 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004170 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004171 res = INVALID_OPERATION;
4172 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004173 } else {
4174 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004175 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004176 }
Eric Laurentc722f302014-12-10 11:21:49 -08004177 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004178 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004179 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004180 if (audio_flags::audio_mix_ownership()) {
4181 // Only unregister mixes that were actually registered to not accidentally unregister
4182 // mixes that already existed previously.
4183 unregisterPolicyMixes(registeredMixes);
4184 registeredMixes.clear();
4185 } else {
4186 unregisterPolicyMixes(mixes);
4187 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004188 } else if (checkOutputs) {
4189 checkForDeviceAndOutputChanges();
4190 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004191 }
4192 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004193}
4194
4195status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4196{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004197 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004198 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004199 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004200 sp<HwModule> rSubmixModule;
4201 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004202 for (const auto& mix : mixes) {
4203 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004204
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004205 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004206 rSubmixModule = mHwModules.getModuleFromName(
4207 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4208 if (rSubmixModule == 0) {
4209 res = INVALID_OPERATION;
4210 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004211 }
4212 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004213
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004214 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004215
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004216 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004217 res = INVALID_OPERATION;
4218 continue;
4219 }
4220
Marvin Ramin0783e202024-03-05 12:45:50 +01004221 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004222 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004223 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4224 status_t currentRes =
4225 setDeviceConnectionStateInt(device,
4226 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4227 address.c_str(),
4228 "remote-submix",
4229 AUDIO_FORMAT_DEFAULT);
4230 if (!audio_flags::audio_mix_ownership()) {
4231 res = currentRes;
4232 }
4233 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004234 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004235 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004236 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004237 }
4238 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004239 }
jiabin5740f082019-08-19 15:08:30 -07004240 rSubmixModule->removeOutputProfile(address.c_str());
4241 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004242
Kevin Rocard153f92d2018-12-18 18:33:28 -08004243 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004244 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004245 res = INVALID_OPERATION;
4246 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004247 } else {
4248 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004249 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004250 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004251 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004252
4253 if (res == NO_ERROR && checkOutputs) {
4254 checkForDeviceAndOutputChanges();
4255 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004256 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004257 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004258}
4259
Marvin Raminbdefaf02023-11-01 09:10:32 +01004260status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4261 if (!audio_flags::audio_mix_test_api()) {
4262 return INVALID_OPERATION;
4263 }
4264
4265 _aidl_return.clear();
4266 _aidl_return.reserve(mPolicyMixes.size());
4267 for (const auto &policyMix: mPolicyMixes) {
4268 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4269 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4270 policyMix->mCbFlags);
4271 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004272 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004273 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004274 }
4275
Vlad Popaa5d73f32024-03-08 16:05:38 -08004276 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004277 return OK;
4278}
4279
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004280status_t AudioPolicyManager::updatePolicyMix(
4281 const AudioMix& mix,
4282 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4283 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4284 if (res == NO_ERROR) {
4285 checkForDeviceAndOutputChanges();
4286 updateCallAndOutputRouting();
4287 }
4288 return res;
4289}
4290
Mikhail Naganov100f0122018-11-29 11:22:16 -08004291void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4292{
4293 size_t i = 0;
4294 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4295 for (const auto& fmt : mManualSurroundFormats) {
4296 if (i++ != 0) dst->append(", ");
4297 std::string sfmt;
4298 FormatConverter::toString(fmt, sfmt);
4299 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4300 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4301 }
4302}
4303
Eric Laurentc529cf62020-04-17 18:19:10 -07004304// Returns true if all devices types match the predicate and are supported by one HW module
4305bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004306 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004307 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004308 const char *context,
4309 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004310 for (size_t i = 0; i < devices.size(); i++) {
4311 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004312 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004313 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004314 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004315 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004316 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004317 return false;
4318 }
4319 }
4320 return true;
4321}
4322
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004323void AudioPolicyManager::changeOutputDevicesMuteState(
4324 const AudioDeviceTypeAddrVector& devices) {
4325 ALOGVV("%s() num devices %zu", __func__, devices.size());
4326
4327 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4328 getSoftwareOutputsForDevices(devices);
4329
4330 for (size_t i = 0; i < outputs.size(); i++) {
4331 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4332 DeviceVector prevDevices = outputDesc->devices();
4333 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4334 }
4335}
4336
4337std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4338 const AudioDeviceTypeAddrVector& devices) const
4339{
4340 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4341 DeviceVector deviceDescriptors;
4342 for (size_t j = 0; j < devices.size(); j++) {
4343 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4344 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4345 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4346 ALOGE("%s: device type %#x address %s not supported or not an output device",
4347 __func__, devices[j].mType, devices[j].getAddress());
4348 continue;
4349 }
4350 deviceDescriptors.add(desc);
4351 }
4352 for (size_t i = 0; i < mOutputs.size(); i++) {
4353 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4354 continue;
4355 }
4356 outputs.push_back(mOutputs.valueAt(i));
4357 }
4358 return outputs;
4359}
4360
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004361status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004362 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004363 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004364 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4365 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004366 }
4367 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004368 if (res != NO_ERROR) {
4369 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4370 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004371 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004372
4373 checkForDeviceAndOutputChanges();
4374 updateCallAndOutputRouting();
4375
4376 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004377}
4378
4379status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4380 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004381 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4382 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004383 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004384 __FUNCTION__, uid);
4385 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004386 }
4387
Eric Laurentc529cf62020-04-17 18:19:10 -07004388 checkForDeviceAndOutputChanges();
4389 updateCallAndOutputRouting();
4390
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004391 return res;
4392}
4393
Eric Laurent2517af32020-11-25 15:31:27 +01004394
jiabin0a488932020-08-07 17:32:40 -07004395status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4396 device_role_t role,
4397 const AudioDeviceTypeAddrVector &devices) {
4398 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4399 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004400
Eric Laurentc529cf62020-04-17 18:19:10 -07004401 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004402 return BAD_VALUE;
4403 }
jiabin0a488932020-08-07 17:32:40 -07004404 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004405 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004406 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4407 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004408 return status;
4409 }
4410
4411 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004412
4413 bool forceVolumeReeval = false;
4414 // FIXME: workaround for truncated touch sounds
4415 // to be removed when the problem is handled by system UI
4416 uint32_t delayMs = 0;
4417 if (strategy == mCommunnicationStrategy) {
4418 forceVolumeReeval = true;
4419 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4420 updateInputRouting();
4421 }
4422 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004423
4424 return NO_ERROR;
4425}
4426
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004427void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4428 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004429{
4430 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004431 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004432 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004433 // Only apply special touch sound delay once
4434 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004435 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004436 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004437 for (size_t i = 0; i < mOutputs.size(); i++) {
4438 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4439 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004440 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4441 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004442 // As done in setDeviceConnectionState, we could also fix default device issue by
4443 // preventing the force re-routing in case of default dev that distinguishes on address.
4444 // Let's give back to engine full device choice decision however.
jiabin2361ed82024-09-20 17:36:31 +00004445 bool newDevicesNotEmpty = !newDevices.isEmpty();
4446 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()
4447 && newDevicesNotEmpty) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004448 // If the device is using preferred mixer attributes, the output need to reopen
4449 // with default configuration when the new selected devices are different from
4450 // current routing devices.
4451 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4452 continue;
4453 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304454
jiabin2361ed82024-09-20 17:36:31 +00004455 waitMs = setOutputDevices(__func__, outputDesc, newDevices,
4456 newDevicesNotEmpty /*force*/, delayMs,
4457 nullptr /*patchHandle*/, !skipDelays /*requiresMuteCheck*/,
4458 !newDevicesNotEmpty /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004459 // Only apply special touch sound delay once
4460 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004461 }
4462 if (forceVolumeReeval && !newDevices.isEmpty()) {
4463 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4464 }
4465 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004466 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004467 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004468}
4469
Eric Laurent2517af32020-11-25 15:31:27 +01004470void AudioPolicyManager::updateInputRouting() {
4471 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304472 // Skip for hotword recording as the input device switch
4473 // is handled within sound trigger HAL
4474 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4475 continue;
4476 }
Eric Laurent2517af32020-11-25 15:31:27 +01004477 auto newDevice = getNewInputDevice(activeDesc);
4478 // Force new input selection if the new device can not be reached via current input
4479 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4480 setInputDevice(activeDesc->mIoHandle, newDevice);
4481 } else {
4482 closeInput(activeDesc->mIoHandle);
4483 }
4484 }
4485}
4486
Paul Wang5d7cdb52022-11-22 09:45:06 +00004487status_t
4488AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4489 device_role_t role,
4490 const AudioDeviceTypeAddrVector &devices) {
4491 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4492 dumpAudioDeviceTypeAddrVector(devices).c_str());
4493
Eric Laurent78fedbf2023-03-09 14:40:44 +01004494 if (!areAllDevicesSupported(
4495 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004496 return BAD_VALUE;
4497 }
4498 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4499 if (status != NO_ERROR) {
4500 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4501 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4502 return status;
4503 }
4504
4505 checkForDeviceAndOutputChanges();
4506
4507 bool forceVolumeReeval = false;
4508 // TODO(b/263479999): workaround for truncated touch sounds
4509 // to be removed when the problem is handled by system UI
4510 uint32_t delayMs = 0;
4511 if (strategy == mCommunnicationStrategy) {
4512 forceVolumeReeval = true;
4513 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4514 updateInputRouting();
4515 }
4516 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4517
4518 return NO_ERROR;
4519}
4520
4521status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4522 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004523{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004524 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004525
Paul Wang5d7cdb52022-11-22 09:45:06 +00004526 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004527 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004528 ALOGW_IF(status != NAME_NOT_FOUND,
4529 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004530 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004531 return status;
4532 }
4533
4534 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004535
4536 bool forceVolumeReeval = false;
4537 // FIXME: workaround for truncated touch sounds
4538 // to be removed when the problem is handled by system UI
4539 uint32_t delayMs = 0;
4540 if (strategy == mCommunnicationStrategy) {
4541 forceVolumeReeval = true;
4542 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4543 updateInputRouting();
4544 }
4545 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004546
4547 return NO_ERROR;
4548}
4549
jiabin0a488932020-08-07 17:32:40 -07004550status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4551 device_role_t role,
4552 AudioDeviceTypeAddrVector &devices) {
4553 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004554}
4555
Jiabin Huang3b98d322020-09-03 17:54:16 +00004556status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4557 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4558 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4559 dumpAudioDeviceTypeAddrVector(devices).c_str());
4560
Mikhail Naganov55773032020-10-01 15:08:13 -07004561 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004562 return BAD_VALUE;
4563 }
4564 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4565 ALOGW_IF(status != NO_ERROR,
4566 "Engine could not set preferred devices %s for audio source %d role %d",
4567 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4568
Wenyu Zhang47655d22024-10-01 12:24:53 +00004569 if (status == NO_ERROR) {
4570 updateInputRouting();
4571 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004572 return status;
4573}
4574
4575status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4576 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4577 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4578 dumpAudioDeviceTypeAddrVector(devices).c_str());
4579
Mikhail Naganov55773032020-10-01 15:08:13 -07004580 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004581 return BAD_VALUE;
4582 }
4583 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4584 ALOGW_IF(status != NO_ERROR,
4585 "Engine could not add preferred devices %s for audio source %d role %d",
4586 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4587
Eric Laurent2517af32020-11-25 15:31:27 +01004588 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004589 return status;
4590}
4591
4592status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4593 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4594{
4595 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4596 dumpAudioDeviceTypeAddrVector(devices).c_str());
4597
Eric Laurent78fedbf2023-03-09 14:40:44 +01004598 if (!areAllDevicesSupported(
4599 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004600 return BAD_VALUE;
4601 }
4602
4603 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4604 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004605 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004606 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004607 if (status == NO_ERROR) {
4608 updateInputRouting();
4609 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004610 return status;
4611}
4612
4613status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4614 device_role_t role) {
4615 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4616
4617 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004618 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004619 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004620 if (status == NO_ERROR) {
4621 updateInputRouting();
4622 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004623 return status;
4624}
4625
4626status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4627 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4628 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4629}
4630
Oscar Azucena90e77632019-11-27 17:12:28 -08004631status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004632 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004633 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004634 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4635 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004636 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004637 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4638 if (status != NO_ERROR) {
4639 ALOGE("%s() could not set device affinity for userId %d",
4640 __FUNCTION__, userId);
4641 return status;
4642 }
4643
4644 // reevaluate outputs for all devices
4645 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004646 changeOutputDevicesMuteState(devices);
4647 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4648 true /* skipDelays */);
4649 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004650
4651 return NO_ERROR;
4652}
4653
4654status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004655 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004656 AudioDeviceTypeAddrVector devices;
4657 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004658 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4659 if (status != NO_ERROR) {
4660 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4661 __FUNCTION__, userId);
4662 return status;
4663 }
4664
4665 // reevaluate outputs for all devices
4666 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004667 changeOutputDevicesMuteState(devices);
4668 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4669 true /* skipDelays */);
4670 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004671
4672 return NO_ERROR;
4673}
4674
Andy Hungc29d82b2018-10-05 12:23:17 -07004675void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004676{
Andy Hungc29d82b2018-10-05 12:23:17 -07004677 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004678 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004679 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004680 std::string stateLiteral;
4681 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004682 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004683 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4684 "communications", "media", "record", "dock", "system",
4685 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4686 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4687 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004688 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4689 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4690 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4691 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4692 dst->append(" (MANUAL: ");
4693 dumpManualSurroundFormats(dst);
4694 dst->append(")");
4695 }
4696 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004697 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004698 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4699 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004700 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004701 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004702
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004703 dst->append("\n");
4704 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4705 dst->append("\n");
4706 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004707 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004708 mOutputs.dump(dst);
4709 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004710 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004711 mAudioPatches.dump(dst);
4712 mPolicyMixes.dump(dst);
4713 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004714
Kevin Rocardb99cc752019-03-21 20:52:24 -07004715 dst->appendFormat(" AllowedCapturePolicies:\n");
4716 for (auto& policy : mAllowedCapturePolicies) {
4717 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4718 }
4719
jiabina84c3d32022-12-02 18:59:55 +00004720 dst->appendFormat(" Preferred mixer audio configuration:\n");
4721 for (const auto it : mPreferredMixerAttrInfos) {
4722 dst->appendFormat(" - device port id: %d\n", it.first);
4723 for (const auto preferredMixerInfoIt : it.second) {
4724 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4725 preferredMixerInfoIt.second->dump(dst);
4726 }
4727 }
4728
François Gaffiec005e562018-11-06 15:04:49 +01004729 dst->appendFormat("\nPolicy Engine dump:\n");
4730 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004731
4732 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4733 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4734 dst->appendFormat(" - device type: %s, driving stream %d\n",
4735 dumpDeviceTypes({it.first}).c_str(),
4736 mEngine->getVolumeGroupForAttributes(it.second));
4737 }
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00004738
4739 // dump mmap policy by device
4740 dst->appendFormat("\nMmap policy:\n");
4741 for (const auto& [policyType, policyByDevice] : mMmapPolicyByDeviceType) {
4742 std::stringstream ss;
4743 ss << '{';
4744 for (const auto& [deviceType, policy] : policyByDevice) {
4745 ss << deviceType.toString() << ":" << toString(policy) << " ";
4746 }
4747 ss << '}';
4748 dst->appendFormat(" - %s: %s\n", toString(policyType).c_str(), ss.str().c_str());
4749 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004750}
4751
4752status_t AudioPolicyManager::dump(int fd)
4753{
4754 String8 result;
4755 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004756 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004757 return NO_ERROR;
4758}
4759
Kevin Rocardb99cc752019-03-21 20:52:24 -07004760status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4761{
4762 mAllowedCapturePolicies[uid] = capturePolicy;
4763 return NO_ERROR;
4764}
4765
Eric Laurente552edb2014-03-10 17:42:56 -07004766// This function checks for the parameters which can be offloaded.
4767// This can be enhanced depending on the capability of the DSP and policy
4768// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004769audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004770{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004771 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004772 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004773 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004774 offloadInfo.format,
4775 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4776 offloadInfo.has_video);
4777
jiabin2b9d5a12021-12-10 01:06:29 +00004778 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004779 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004780 }
4781
4782 // See if there is a profile to support this.
4783 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004784 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004785 offloadInfo.sample_rate,
4786 offloadInfo.format,
4787 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004788 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4789 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004790 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4791 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4792 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004793 if (profile == nullptr) {
4794 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4795 }
4796 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4797 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4798 }
4799 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004800}
4801
Michael Chana94fbb22018-04-24 14:31:19 +10004802bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4803 const audio_attributes_t& attributes) {
4804 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004805 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004806 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4807 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004808 config.sample_rate,
4809 config.format,
4810 config.channel_mask,
4811 output_flags,
4812 true /* directOnly */);
4813 ALOGV("%s() profile %sfound with name: %s, "
4814 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4815 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004816 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004817 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004818
4819 // also try the MSD module if compatible profile not found
4820 if (profile == nullptr) {
4821 profile = getMsdProfileForOutput(outputDevices,
4822 config.sample_rate,
4823 config.format,
4824 config.channel_mask,
4825 output_flags,
4826 true /* directOnly */);
4827 ALOGV("%s() MSD profile %sfound with name: %s, "
4828 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4829 __FUNCTION__, profile != 0 ? "" : "NOT ",
4830 (profile != 0 ? profile->getTagName().c_str() : "null"),
4831 config.sample_rate, config.format, config.channel_mask, output_flags);
4832 }
4833 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004834}
4835
jiabin2b9d5a12021-12-10 01:06:29 +00004836bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4837 bool durationIgnored) {
4838 if (mMasterMono) {
4839 return false; // no offloading if mono is set.
4840 }
4841
4842 // Check if offload has been disabled
4843 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4844 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4845 return false;
4846 }
4847
4848 // Check if stream type is music, then only allow offload as of now.
4849 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4850 {
4851 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4852 return false;
4853 }
4854
4855 //TODO: enable audio offloading with video when ready
4856 const bool allowOffloadWithVideo =
4857 property_get_bool("audio.offload.video", false /* default_value */);
4858 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4859 ALOGV("%s: has_video == true, returning false", __func__);
4860 return false;
4861 }
4862
4863 //If duration is less than minimum value defined in property, return false
4864 const int min_duration_secs = property_get_int32(
4865 "audio.offload.min.duration.secs", -1 /* default_value */);
4866 if (!durationIgnored) {
4867 if (min_duration_secs >= 0) {
4868 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4869 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4870 __func__, min_duration_secs);
4871 return false;
4872 }
4873 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4874 ALOGV("%s: Offload denied by duration < default min(=%u)",
4875 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4876 return false;
4877 }
4878 }
4879
4880 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4881 // creating an offloaded track and tearing it down immediately after start when audioflinger
4882 // detects there is an active non offloadable effect.
4883 // FIXME: We should check the audio session here but we do not have it in this context.
4884 // This may prevent offloading in rare situations where effects are left active by apps
4885 // in the background.
4886 if (mEffects.isNonOffloadableEffectEnabled()) {
4887 return false;
4888 }
4889
4890 return true;
4891}
4892
4893audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4894 const audio_config_t *config) {
4895 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4896 offloadInfo.format = config->format;
4897 offloadInfo.sample_rate = config->sample_rate;
4898 offloadInfo.channel_mask = config->channel_mask;
4899 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4900 offloadInfo.has_video = false;
4901 offloadInfo.is_streaming = false;
4902 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4903
4904 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4905 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4906 audio_flags_to_audio_output_flags(attr->flags, &flags);
4907 // only retain flags that will drive compressed offload or passthrough
4908 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4909 if (offloadPossible) {
4910 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4911 }
4912 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4913
Dorin Drimusfae3c642022-03-17 18:36:30 +01004914 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin8a096672024-09-18 18:20:24 +00004915 if (std::any_of(engineOutputDevices.begin(), engineOutputDevices.end(),
4916 [this, attr](sp<DeviceDescriptor> device) {
4917 return getPreferredMixerAttributesInfo(
4918 device->getId(),
4919 mEngine->getProductStrategyForAttributes(*attr),
4920 true /*activeBitPerfectPreferred*/) != nullptr;
4921 })) {
4922 // Bit-perfect playback is active on one of the selected devices, direct output will
4923 // be rejected at this instant.
4924 return AUDIO_DIRECT_NOT_SUPPORTED;
4925 }
jiabin2b9d5a12021-12-10 01:06:29 +00004926 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004927 DeviceVector outputDevices = engineOutputDevices;
4928 // the MSD module checks for different conditions and output devices
4929 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4930 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4931 continue;
4932 }
4933 outputDevices = getMsdAudioOutDevices();
4934 }
jiabin2b9d5a12021-12-10 01:06:29 +00004935 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004936 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004937 config->sample_rate, nullptr /*updatedSamplingRate*/,
4938 config->format, nullptr /*updatedFormat*/,
4939 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004940 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004941 continue;
4942 }
4943 // reject profiles not corresponding to a device currently available
4944 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4945 continue;
4946 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004947 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4948 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004949 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004950 != AUDIO_DIRECT_NOT_SUPPORTED) {
4951 // Already reports offload gapless supported. No need to report offload support.
4952 continue;
4953 }
4954 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4955 != AUDIO_OUTPUT_FLAG_NONE) {
4956 // If offload gapless is reported, no need to report offload support.
4957 directMode = (audio_direct_mode_t) ((directMode &
4958 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4959 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4960 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004961 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004962 }
4963 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004964 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004965 }
4966 }
4967 }
4968 return directMode;
4969}
4970
Dorin Drimusf2196d82022-01-03 12:11:18 +01004971status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4972 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004973 if (mEffects.isNonOffloadableEffectEnabled()) {
4974 return OK;
4975 }
jiabinf1c73972022-04-14 16:28:52 -07004976 DeviceVector devices;
4977 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004978 if (status != OK) {
4979 return status;
4980 }
4981 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4982 if (devices.empty()) {
4983 return OK; // no output devices for the attributes
4984 }
jiabinf1c73972022-04-14 16:28:52 -07004985 return getProfilesForDevices(devices, audioProfilesVector,
4986 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004987}
4988
jiabina84c3d32022-12-02 18:59:55 +00004989status_t AudioPolicyManager::getSupportedMixerAttributes(
4990 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4991 ALOGV("%s, portId=%d", __func__, portId);
4992 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4993 if (deviceDescriptor == nullptr) {
4994 ALOGE("%s the requested device is currently unavailable", __func__);
4995 return BAD_VALUE;
4996 }
jiabin96daffc2023-05-11 17:51:55 +00004997 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4998 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4999 deviceDescriptor->type());
5000 return BAD_VALUE;
5001 }
jiabina84c3d32022-12-02 18:59:55 +00005002 for (const auto& hwModule : mHwModules) {
5003 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5004 if (curProfile->supportsDevice(deviceDescriptor)) {
5005 curProfile->toSupportedMixerAttributes(&mixerAttrs);
5006 }
5007 }
5008 }
5009 return NO_ERROR;
5010}
5011
5012status_t AudioPolicyManager::setPreferredMixerAttributes(
5013 const audio_attributes_t *attr,
5014 audio_port_handle_t portId,
5015 uid_t uid,
5016 const audio_mixer_attributes_t *mixerAttributes) {
5017 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
5018 "mixerBehavior=%d}, uid=%d, portId=%u",
5019 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
5020 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
5021 mixerAttributes->mixer_behavior, uid, portId);
5022 if (attr->usage != AUDIO_USAGE_MEDIA) {
5023 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
5024 return BAD_VALUE;
5025 }
5026 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5027 if (deviceDescriptor == nullptr) {
5028 ALOGE("%s the requested device is currently unavailable", __func__);
5029 return BAD_VALUE;
5030 }
5031 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5032 ALOGE("%s(%d), type=%d, is not a usb output device",
5033 __func__, portId, deviceDescriptor->type());
5034 return BAD_VALUE;
5035 }
5036
5037 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5038 audio_flags_to_audio_output_flags(attr->flags, &flags);
5039 flags = (audio_output_flags_t) (flags |
5040 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
5041 sp<IOProfile> profile = nullptr;
5042 DeviceVector devices(deviceDescriptor);
5043 for (const auto& hwModule : mHwModules) {
5044 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5045 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00005046 && curProfile->getCompatibilityScore(
5047 devices,
5048 mixerAttributes->config.sample_rate,
5049 nullptr /*updatedSamplingRate*/,
5050 mixerAttributes->config.format,
5051 nullptr /*updatedFormat*/,
5052 mixerAttributes->config.channel_mask,
5053 nullptr /*updatedChannelMask*/,
jiabin91beb492024-10-16 21:53:36 +00005054 flags)
jiabin66acc432024-02-06 00:57:36 +00005055 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00005056 profile = curProfile;
5057 break;
5058 }
5059 }
5060 }
5061 if (profile == nullptr) {
5062 ALOGE("%s, there is no compatible profile found", __func__);
5063 return BAD_VALUE;
5064 }
5065
5066 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
5067 sp<PreferredMixerAttributesInfo>::make(
5068 uid, portId, profile, flags, *mixerAttributes);
5069 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5070 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
5071
5072 // If 1) there is any client from the preferred mixer configuration owner that is currently
5073 // active and matches the strategy and 2) current output is on the preferred device and the
5074 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
5075 // configuration.
5076 std::vector<audio_io_handle_t> outputsToReopen;
5077 for (size_t i = 0; i < mOutputs.size(); i++) {
5078 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00005079 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
5080 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00005081 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00005082 } else {
5083 for (const auto &client: output->getActiveClients()) {
5084 if (client->uid() == uid && client->strategy() == strategy) {
5085 client->setIsInvalid();
5086 outputsToReopen.push_back(output->mIoHandle);
5087 }
jiabina84c3d32022-12-02 18:59:55 +00005088 }
5089 }
5090 }
5091 }
5092 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5093 config.sample_rate = mixerAttributes->config.sample_rate;
5094 config.channel_mask = mixerAttributes->config.channel_mask;
5095 config.format = mixerAttributes->config.format;
5096 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005097 sp<SwAudioOutputDescriptor> desc =
5098 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5099 if (desc == nullptr) {
5100 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5101 continue;
5102 }
jiabin220eea12024-05-17 17:55:20 +00005103 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005104 }
5105
5106 return NO_ERROR;
5107}
5108
5109sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005110 audio_port_handle_t devicePortId,
5111 product_strategy_t strategy,
5112 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005113 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5114 if (it == mPreferredMixerAttrInfos.end()) {
5115 return nullptr;
5116 }
jiabind9a58d32023-06-01 17:57:30 +00005117 if (activeBitPerfectPreferred) {
5118 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005119 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005120 return info;
5121 }
5122 }
jiabina84c3d32022-12-02 18:59:55 +00005123 }
jiabind9a58d32023-06-01 17:57:30 +00005124 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5125 return strategyMatchedMixerAttrInfoIt == it->second.end()
5126 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005127}
5128
5129status_t AudioPolicyManager::getPreferredMixerAttributes(
5130 const audio_attributes_t *attr,
5131 audio_port_handle_t portId,
5132 audio_mixer_attributes_t* mixerAttributes) {
5133 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5134 portId, mEngine->getProductStrategyForAttributes(*attr));
5135 if (info == nullptr) {
5136 return NAME_NOT_FOUND;
5137 }
5138 *mixerAttributes = info->getMixerAttributes();
5139 return NO_ERROR;
5140}
5141
5142status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5143 audio_port_handle_t portId,
5144 uid_t uid) {
5145 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5146 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5147 if (preferredMixerAttrInfo == nullptr) {
5148 return NAME_NOT_FOUND;
5149 }
5150 if (preferredMixerAttrInfo->getUid() != uid) {
5151 ALOGE("%s, requested uid=%d, owned uid=%d",
5152 __func__, uid, preferredMixerAttrInfo->getUid());
5153 return PERMISSION_DENIED;
5154 }
5155 mPreferredMixerAttrInfos[portId].erase(strategy);
5156 if (mPreferredMixerAttrInfos[portId].empty()) {
5157 mPreferredMixerAttrInfos.erase(portId);
5158 }
5159
5160 // Reconfig existing output
5161 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5162 for (size_t i = 0; i < mOutputs.size(); i++) {
5163 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5164 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5165 }
5166 }
5167 for (const auto output : potentialOutputsToReopen) {
5168 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5169 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5170 preferredMixerAttrInfo->getFlags())) {
5171 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5172 }
5173 }
5174 return NO_ERROR;
5175}
5176
Eric Laurent6a94d692014-05-20 11:18:06 -07005177status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5178 audio_port_type_t type,
5179 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005180 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005181 unsigned int *generation)
5182{
jiabin19cdba52020-11-24 11:28:58 -08005183 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5184 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005185 return BAD_VALUE;
5186 }
5187 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005188 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005189 *num_ports = 0;
5190 }
5191
5192 size_t portsWritten = 0;
5193 size_t portsMax = *num_ports;
5194 *num_ports = 0;
5195 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005196 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5197 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005198 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005199 for (const auto& dev : mAvailableOutputDevices) {
5200 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005201 continue;
5202 }
5203 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005204 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005205 }
5206 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005207 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005208 }
5209 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005210 for (const auto& dev : mAvailableInputDevices) {
5211 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005212 continue;
5213 }
5214 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005215 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005216 }
5217 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005218 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005219 }
5220 }
5221 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5222 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5223 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5224 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5225 }
5226 *num_ports += mInputs.size();
5227 }
5228 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005229 size_t numOutputs = 0;
5230 for (size_t i = 0; i < mOutputs.size(); i++) {
5231 if (!mOutputs[i]->isDuplicated()) {
5232 numOutputs++;
5233 if (portsWritten < portsMax) {
5234 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5235 }
5236 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005237 }
Eric Laurent84c70242014-06-23 08:46:27 -07005238 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005239 }
5240 }
jiabina84c3d32022-12-02 18:59:55 +00005241
Eric Laurent6a94d692014-05-20 11:18:06 -07005242 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005243 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005244 return NO_ERROR;
5245}
5246
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005247status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5248 std::vector<media::AudioPortFw>* _aidl_return) {
5249 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5250 audio_port_v7 port;
5251 dev->toAudioPort(&port);
5252 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5253 _aidl_return->push_back(std::move(aidlPort));
5254 return OK;
5255 };
5256
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005257 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005258 for (const auto& dev : module->getDeclaredDevices()) {
5259 if (role == media::AudioPortRole::NONE ||
5260 ((role == media::AudioPortRole::SOURCE)
5261 == audio_is_input_device(dev->type()))) {
5262 RETURN_STATUS_IF_ERROR(pushPort(dev));
5263 }
5264 }
5265 }
5266 return OK;
5267}
5268
jiabin19cdba52020-11-24 11:28:58 -08005269status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005270{
Eric Laurent99fcae42018-05-17 16:59:18 -07005271 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5272 return BAD_VALUE;
5273 }
5274 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5275 if (dev != 0) {
5276 dev->toAudioPort(port);
5277 return NO_ERROR;
5278 }
5279 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5280 if (dev != 0) {
5281 dev->toAudioPort(port);
5282 return NO_ERROR;
5283 }
5284 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5285 if (out != 0) {
5286 out->toAudioPort(port);
5287 return NO_ERROR;
5288 }
5289 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5290 if (in != 0) {
5291 in->toAudioPort(port);
5292 return NO_ERROR;
5293 }
5294 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005295}
5296
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005297status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5298 audio_patch_handle_t *handle,
5299 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005300{
François Gaffieafd4cea2019-11-18 15:50:22 +01005301 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005302 if (handle == NULL || patch == NULL) {
5303 return BAD_VALUE;
5304 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005305 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005306 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005307 return BAD_VALUE;
5308 }
5309 // only one source per audio patch supported for now
5310 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 return INVALID_OPERATION;
5312 }
Eric Laurent874c42872014-08-08 15:13:39 -07005313 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005314 return INVALID_OPERATION;
5315 }
Eric Laurent874c42872014-08-08 15:13:39 -07005316 for (size_t i = 0; i < patch->num_sinks; i++) {
5317 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5318 return INVALID_OPERATION;
5319 }
5320 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005321
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005322 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5323 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5324 if (srcDevice == nullptr || sinkDevice == nullptr) {
5325 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5326 return BAD_VALUE;
5327 }
5328 ALOGV("%s between source %s and sink %s", __func__,
5329 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5330 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5331 // Default attributes, default volume priority, not to infer with non raw audio patches.
5332 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5333 const struct audio_port_config *source = &patch->sources[0];
5334 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005335 new SourceClientDescriptor(
5336 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5337 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005338 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005339 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005340
5341 status_t status =
5342 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5343
5344 if (status != NO_ERROR) {
5345 return INVALID_OPERATION;
5346 }
5347 mAudioSources.add(portId, sourceDesc);
5348 return NO_ERROR;
5349}
5350
5351status_t AudioPolicyManager::connectAudioSourceToSink(
5352 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5353 const struct audio_patch *patch,
5354 audio_patch_handle_t &handle,
5355 uid_t uid, uint32_t delayMs)
5356{
5357 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5358 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5359 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5360 return INVALID_OPERATION;
5361 }
5362 sourceDesc->connect(handle, sinkDevice);
5363 if (isMsdPatch(handle)) {
5364 return NO_ERROR;
5365 }
5366 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5367 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5368 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5369 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5370 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5371 goto FailurePatchAdded;
5372 }
5373 status = swOutput->start();
5374 if (status != NO_ERROR) {
5375 goto FailureSourceAdded;
5376 }
5377 swOutput->addClient(sourceDesc);
5378 status = startSource(swOutput, sourceDesc, &delayMs);
5379 if (status != NO_ERROR) {
5380 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5381 goto FailureSourceActive;
5382 }
5383 if (delayMs != 0) {
5384 usleep(delayMs * 1000);
5385 }
5386 return NO_ERROR;
5387
5388FailureSourceActive:
5389 swOutput->stop();
5390 releaseOutput(sourceDesc->portId());
5391FailureSourceAdded:
5392 sourceDesc->setSwOutput(nullptr);
5393FailurePatchAdded:
5394 releaseAudioPatchInternal(handle);
5395 return INVALID_OPERATION;
5396}
5397
5398status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5399 audio_patch_handle_t *handle,
5400 uid_t uid, uint32_t delayMs,
5401 const sp<SourceClientDescriptor>& sourceDesc)
5402{
5403 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005404 sp<AudioPatch> patchDesc;
5405 ssize_t index = mAudioPatches.indexOfKey(*handle);
5406
François Gaffieafd4cea2019-11-18 15:50:22 +01005407 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5408 patch->sources[0].role,
5409 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005410#if LOG_NDEBUG == 0
5411 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005412 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5413 patch->sinks[i].role,
5414 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005415 }
5416#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005417
5418 if (index >= 0) {
5419 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005420 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5421 __func__, mUidCached, patchDesc->getUid(), uid);
5422 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005423 return INVALID_OPERATION;
5424 }
5425 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005426 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005427 }
5428
5429 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005430 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005431 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005432 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005433 return BAD_VALUE;
5434 }
Eric Laurent84c70242014-06-23 08:46:27 -07005435 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5436 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005437 if (patchDesc != 0) {
5438 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005439 ALOGV("%s source id differs for patch current id %d new id %d",
5440 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005441 return BAD_VALUE;
5442 }
5443 }
Eric Laurent874c42872014-08-08 15:13:39 -07005444 DeviceVector devices;
5445 for (size_t i = 0; i < patch->num_sinks; i++) {
5446 // Only support mix to devices connection
5447 // TODO add support for mix to mix connection
5448 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005449 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005450 return INVALID_OPERATION;
5451 }
5452 sp<DeviceDescriptor> devDesc =
5453 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5454 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005455 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005456 return BAD_VALUE;
5457 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005458
jiabin66acc432024-02-06 00:57:36 +00005459 if (outputDesc->mProfile->getCompatibilityScore(
5460 DeviceVector(devDesc),
5461 patch->sources[0].sample_rate,
5462 nullptr, // updatedSamplingRate
5463 patch->sources[0].format,
5464 nullptr, // updatedFormat
5465 patch->sources[0].channel_mask,
5466 nullptr, // updatedChannelMask
5467 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005468 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005469 return INVALID_OPERATION;
5470 }
5471 devices.add(devDesc);
5472 }
5473 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005474 return INVALID_OPERATION;
5475 }
Eric Laurent874c42872014-08-08 15:13:39 -07005476
Eric Laurent6a94d692014-05-20 11:18:06 -07005477 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005478 ALOGV("%s setting device %s on output %d",
5479 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305480 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005481 index = mAudioPatches.indexOfKey(*handle);
5482 if (index >= 0) {
5483 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005484 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005485 }
5486 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005487 patchDesc->setUid(uid);
5488 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005489 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005490 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005491 return INVALID_OPERATION;
5492 }
5493 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5494 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5495 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005496 // only one sink supported when connecting an input device to a mix
5497 if (patch->num_sinks > 1) {
5498 return INVALID_OPERATION;
5499 }
François Gaffie53615e22015-03-19 09:24:12 +01005500 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005501 if (inputDesc == NULL) {
5502 return BAD_VALUE;
5503 }
5504 if (patchDesc != 0) {
5505 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5506 return BAD_VALUE;
5507 }
5508 }
François Gaffie11d30102018-11-02 16:09:09 +01005509 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005510 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005511 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005512 return BAD_VALUE;
5513 }
5514
jiabin66acc432024-02-06 00:57:36 +00005515 if (inputDesc->mProfile->getCompatibilityScore(
5516 DeviceVector(device),
5517 patch->sinks[0].sample_rate,
5518 nullptr, /*updatedSampleRate*/
5519 patch->sinks[0].format,
5520 nullptr, /*updatedFormat*/
5521 patch->sinks[0].channel_mask,
5522 nullptr, /*updatedChannelMask*/
5523 // FIXME for the parameter type,
5524 // and the NONE
5525 (audio_output_flags_t)
5526 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005527 return INVALID_OPERATION;
5528 }
5529 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005530 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005531 device->toString().c_str(), inputDesc->mIoHandle);
5532 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005533 index = mAudioPatches.indexOfKey(*handle);
5534 if (index >= 0) {
5535 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005536 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005537 }
5538 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005539 patchDesc->setUid(uid);
5540 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005541 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005542 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005543 return INVALID_OPERATION;
5544 }
5545 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5546 // device to device connection
5547 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005548 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005549 return BAD_VALUE;
5550 }
5551 }
François Gaffie11d30102018-11-02 16:09:09 +01005552 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005553 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005554 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005555 return BAD_VALUE;
5556 }
Eric Laurent874c42872014-08-08 15:13:39 -07005557
Eric Laurent6a94d692014-05-20 11:18:06 -07005558 //update source and sink with our own data as the data passed in the patch may
5559 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005560 PatchBuilder patchBuilder;
5561 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005562
5563 // if first sink is to MSD, establish single MSD patch
5564 if (getMsdAudioOutDevices().contains(
5565 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5566 ALOGV("%s patching to MSD", __FUNCTION__);
5567 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5568 goto installPatch;
5569 }
5570
François Gaffieafd4cea2019-11-18 15:50:22 +01005571 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5572 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005573
Eric Laurent874c42872014-08-08 15:13:39 -07005574 for (size_t i = 0; i < patch->num_sinks; i++) {
5575 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005576 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005577 return INVALID_OPERATION;
5578 }
François Gaffie11d30102018-11-02 16:09:09 +01005579 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005580 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005581 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005582 return BAD_VALUE;
5583 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005584 audio_port_config sinkPortConfig = {};
5585 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5586 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005587
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005588 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5589 // volume management purpose (tracking activity)
5590 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5591 // in config XML to reach the sink so that is can be declared as available.
5592 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005593 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005594 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005595 // take care of dynamic routing for SwOutput selection,
5596 audio_attributes_t attributes = sourceDesc->attributes();
5597 audio_stream_type_t stream = sourceDesc->stream();
5598 audio_attributes_t resultAttr;
5599 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5600 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005601 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5602 config.channel_mask =
5603 (audio_channel_mask_get_representation(sourceMask)
5604 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5605 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005606 config.format = sourceDesc->config().format;
5607 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Robert Wufb971192024-10-30 21:54:35 +00005608 DeviceIdVector selectedDeviceIds;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005609 bool isRequestedDeviceForExclusiveUse = false;
5610 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005611 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005612 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005613 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5614 &stream, sourceDesc->uid(), &config, &flags,
Robert Wufb971192024-10-30 21:54:35 +00005615 &selectedDeviceIds, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005616 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005617 if (output == AUDIO_IO_HANDLE_NONE) {
5618 ALOGV("%s no output for device %s",
5619 __FUNCTION__, sinkDevice->toString().c_str());
5620 return INVALID_OPERATION;
5621 }
5622 outputDesc = mOutputs.valueFor(output);
5623 if (outputDesc->isDuplicated()) {
5624 ALOGE("%s output is duplicated", __func__);
5625 return INVALID_OPERATION;
5626 }
François Gaffie7e39df22022-04-26 12:48:49 +02005627 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5628 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005629 } else {
5630 // Same for "raw patches" aka created from createAudioPatch API
5631 SortedVector<audio_io_handle_t> outputs =
5632 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5633 // if the sink device is reachable via an opened output stream, request to
5634 // go via this output stream by adding a second source to the patch
5635 // description
5636 output = selectOutput(outputs);
5637 if (output == AUDIO_IO_HANDLE_NONE) {
5638 ALOGE("%s no output available for internal patch sink", __func__);
5639 return INVALID_OPERATION;
5640 }
5641 outputDesc = mOutputs.valueFor(output);
5642 if (outputDesc->isDuplicated()) {
5643 ALOGV("%s output for device %s is duplicated",
5644 __func__, sinkDevice->toString().c_str());
5645 return INVALID_OPERATION;
5646 }
François Gaffie7e39df22022-04-26 12:48:49 +02005647 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005648 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005649 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005650 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005651 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005652 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005653 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5654 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005655 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5656 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005657 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005658 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005659 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005660 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005661 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005662 return INVALID_OPERATION;
5663 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005664 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005665 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005666 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005667 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005668 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005669 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005670 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005671 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5672 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005673 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005674 }
Eric Laurent83b88082014-06-20 18:31:16 -07005675 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005676 }
5677 // TODO: check from routing capabilities in config file and other conflicting patches
5678
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005679installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005680 status_t status = installPatch(
5681 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005682 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005683 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005684 return INVALID_OPERATION;
5685 }
5686 } else {
5687 return BAD_VALUE;
5688 }
5689 } else {
5690 return BAD_VALUE;
5691 }
5692 return NO_ERROR;
5693}
5694
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005695status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005696{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005697 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005698 ssize_t index = mAudioPatches.indexOfKey(handle);
5699
5700 if (index < 0) {
5701 return BAD_VALUE;
5702 }
5703 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005704 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5705 __func__, mUidCached, patchDesc->getUid(), uid);
5706 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005707 return INVALID_OPERATION;
5708 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005709 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5710 for (size_t i = 0; i < mAudioSources.size(); i++) {
5711 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5712 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5713 portId = sourceDesc->portId();
5714 break;
5715 }
5716 }
5717 return portId != AUDIO_PORT_HANDLE_NONE ?
5718 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005719}
Eric Laurent6a94d692014-05-20 11:18:06 -07005720
François Gaffieafd4cea2019-11-18 15:50:22 +01005721status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005722 uint32_t delayMs,
5723 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005724{
5725 ALOGV("%s patch %d", __func__, handle);
5726 if (mAudioPatches.indexOfKey(handle) < 0) {
5727 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5728 return BAD_VALUE;
5729 }
5730 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005731 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005732 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005733 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005734 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005735 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005736 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005737 return BAD_VALUE;
5738 }
5739
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305740 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005741 getNewOutputDevices(outputDesc, true /*fromCache*/),
5742 true,
5743 0,
5744 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005745 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5746 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005747 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005748 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005749 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005750 return BAD_VALUE;
5751 }
5752 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005753 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005754 true,
5755 NULL);
5756 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005757 status_t status =
5758 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5759 ALOGV("%s patch panel returned %d patchHandle %d",
5760 __func__, status, patchDesc->getAfHandle());
5761 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005762 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005763 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005764 // SW or HW Bridge
5765 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5766 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005767 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005768 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5769 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5770 outputDesc = sourceDesc->swOutput().promote();
5771 }
5772 if (outputDesc == nullptr) {
5773 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5774 // releaseOutput has already called closeOutput in case of direct output
5775 return NO_ERROR;
5776 }
François Gaffie7e39df22022-04-26 12:48:49 +02005777 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005778 // While using a HwBridge, force reconsidering device only if not reusing an existing
5779 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005780 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005781 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5782 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5783 // Reconsider device only for cases:
5784 // 1 / Active Output
5785 // 2 / Inactive Output previously hosting HwBridge
5786 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5787 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5788 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305789 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005790 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5791 outputDesc->devices(),
5792 force,
5793 0,
5794 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005795 } else {
5796 return BAD_VALUE;
5797 }
5798 } else {
5799 return BAD_VALUE;
5800 }
5801 return NO_ERROR;
5802}
5803
5804status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5805 struct audio_patch *patches,
5806 unsigned int *generation)
5807{
François Gaffie53615e22015-03-19 09:24:12 +01005808 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005809 return BAD_VALUE;
5810 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005811 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005812 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005813}
5814
Eric Laurente1715a42014-05-20 11:30:42 -07005815status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005816{
Eric Laurente1715a42014-05-20 11:30:42 -07005817 ALOGV("setAudioPortConfig()");
5818
5819 if (config == NULL) {
5820 return BAD_VALUE;
5821 }
5822 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5823 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005824 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5825 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005826 }
5827
Eric Laurenta121f902014-06-03 13:32:54 -07005828 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005829 if (config->type == AUDIO_PORT_TYPE_MIX) {
5830 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005831 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005832 if (outputDesc == NULL) {
5833 return BAD_VALUE;
5834 }
Eric Laurent84c70242014-06-23 08:46:27 -07005835 ALOG_ASSERT(!outputDesc->isDuplicated(),
5836 "setAudioPortConfig() called on duplicated output %d",
5837 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005838 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005839 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005840 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005841 if (inputDesc == NULL) {
5842 return BAD_VALUE;
5843 }
Eric Laurenta121f902014-06-03 13:32:54 -07005844 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005845 } else {
5846 return BAD_VALUE;
5847 }
5848 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5849 sp<DeviceDescriptor> deviceDesc;
5850 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5851 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5852 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5853 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5854 } else {
5855 return BAD_VALUE;
5856 }
5857 if (deviceDesc == NULL) {
5858 return BAD_VALUE;
5859 }
Eric Laurenta121f902014-06-03 13:32:54 -07005860 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005861 } else {
5862 return BAD_VALUE;
5863 }
5864
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005865 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005866 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5867 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005868 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005869 audioPortConfig->toAudioPortConfig(&newConfig, config);
5870 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005871 }
Eric Laurenta121f902014-06-03 13:32:54 -07005872 if (status != NO_ERROR) {
5873 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005874 }
Eric Laurente1715a42014-05-20 11:30:42 -07005875
5876 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005877}
5878
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005879void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5880{
Eric Laurentd60560a2015-04-10 11:31:20 -07005881 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005882 clearAudioPatches(uid);
5883 clearSessionRoutes(uid);
5884}
5885
Eric Laurent6a94d692014-05-20 11:18:06 -07005886void AudioPolicyManager::clearAudioPatches(uid_t uid)
5887{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005888 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005889 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005890 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005891 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005892 }
5893 }
5894}
5895
François Gaffiec005e562018-11-06 15:04:49 +01005896void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005897{
François Gaffiec005e562018-11-06 15:04:49 +01005898 // Take the first attributes following the product strategy as it is used to retrieve the routed
5899 // device. All attributes wihin a strategy follows the same "routing strategy"
5900 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5901 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005902 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005903 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005904 for (size_t j = 0; j < mOutputs.size(); j++) {
5905 if (mOutputs.keyAt(j) == ouptutToSkip) {
5906 continue;
5907 }
5908 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005909 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005910 continue;
5911 }
5912 // If the default device for this strategy is on another output mix,
5913 // invalidate all tracks in this strategy to force re connection.
5914 // Otherwise select new device on the output mix.
5915 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005916 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005917 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005918 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005919 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005920 // If the device is using preferred mixer attributes, the output need to reopen
5921 // with default configuration when the new selected devices are different from
5922 // current routing devices.
5923 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5924 continue;
5925 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305926 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005927 }
5928 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005929 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005930}
5931
5932void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5933{
5934 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005935 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005936 for (size_t i = 0; i < mOutputs.size(); i++) {
5937 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005938 for (const auto& client : outputDesc->getClientIterable()) {
5939 if (client->hasPreferredDevice() && client->uid() == uid) {
5940 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005941 auto clientStrategy = client->strategy();
5942 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5943 end(affectedStrategies)) {
5944 continue;
5945 }
5946 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005947 }
5948 }
5949 }
5950 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005951 for (const auto& strategy : affectedStrategies) {
5952 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005953 }
5954
5955 // remove input routes associated with this uid
5956 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005957 for (size_t i = 0; i < mInputs.size(); i++) {
5958 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005959 for (const auto& client : inputDesc->getClientIterable()) {
5960 if (client->hasPreferredDevice() && client->uid() == uid) {
5961 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5962 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005963 }
5964 }
5965 }
5966 // reroute inputs if necessary
5967 SortedVector<audio_io_handle_t> inputsToClose;
5968 for (size_t i = 0; i < mInputs.size(); i++) {
5969 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005970 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005971 inputsToClose.add(inputDesc->mIoHandle);
5972 }
5973 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005974 for (const auto& input : inputsToClose) {
5975 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005976 }
5977}
5978
Eric Laurentd60560a2015-04-10 11:31:20 -07005979void AudioPolicyManager::clearAudioSources(uid_t uid)
5980{
5981 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005982 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5983 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005984 stopAudioSource(mAudioSources.keyAt(i));
5985 }
5986 }
5987}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005988
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005989status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5990 audio_io_handle_t *ioHandle,
5991 audio_devices_t *device)
5992{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005993 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5994 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005995 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005996 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5997 if (deviceDesc == nullptr) {
5998 return INVALID_OPERATION;
5999 }
6000 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006001
François Gaffiedf372692015-03-19 10:43:27 +01006002 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006003}
6004
Eric Laurentd60560a2015-04-10 11:31:20 -07006005status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006006 const audio_attributes_t *attributes,
6007 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00006008 uid_t uid) {
6009 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00006010 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00006011}
6012
6013status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
6014 const audio_attributes_t *attributes,
6015 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00006016 uid_t uid, bool internal, bool isCallRx,
6017 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07006018{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006019 ALOGV("%s", __FUNCTION__);
6020 *portId = AUDIO_PORT_HANDLE_NONE;
6021
6022 if (source == NULL || attributes == NULL || portId == NULL) {
6023 ALOGW("%s invalid argument: source %p attributes %p handle %p",
6024 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006025 return BAD_VALUE;
6026 }
6027
Eric Laurentd60560a2015-04-10 11:31:20 -07006028 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
6029 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006030 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
6031 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006032 return INVALID_OPERATION;
6033 }
6034
François Gaffie11d30102018-11-02 16:09:09 +01006035 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07006036 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006037 String8(source->ext.device.address),
6038 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01006039 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006040 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006041 return BAD_VALUE;
6042 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006043
jiabin4ef93452019-09-10 14:29:54 -07006044 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07006045
François Gaffieaaac0fd2018-11-22 17:56:39 +01006046 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01006047 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006048 mEngine->getStreamTypeForAttributes(*attributes),
6049 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00006050 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07006051
David Lif85c5e32024-07-01 13:14:10 +00006052 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07006053 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006054 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006055 }
6056 return status;
6057}
6058
David Lif85c5e32024-07-01 13:14:10 +00006059status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
6060 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07006061{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006062 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006063
6064 // make sure we only have one patch per source.
6065 disconnectAudioSource(sourceDesc);
6066
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006067 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006068 // May the device (dynamic) have been disconnected/reconnected, id has changed.
6069 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
6070 sourceDesc->srcDevice()->type(),
6071 String8(sourceDesc->srcDevice()->address().c_str()),
6072 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01006073 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02006074 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01006075 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01006076 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006077 if (!mAvailableOutputDevices.contains(sinkDevice)) {
6078 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
6079 return INVALID_OPERATION;
6080 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006081 PatchBuilder patchBuilder;
6082 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
6083 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01006084
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006085 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00006086 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07006087}
6088
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006089status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07006090{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006091 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6092 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006093 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006094 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006095 return BAD_VALUE;
6096 }
6097 status_t status = disconnectAudioSource(sourceDesc);
6098
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006099 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006100 return status;
6101}
6102
Andy Hung2ddee192015-12-18 17:34:44 -08006103status_t AudioPolicyManager::setMasterMono(bool mono)
6104{
6105 if (mMasterMono == mono) {
6106 return NO_ERROR;
6107 }
6108 mMasterMono = mono;
6109 // if enabling mono we close all offloaded devices, which will invalidate the
6110 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6111 // for recreating the new AudioTrack as non-offloaded PCM.
6112 //
6113 // If disabling mono, we leave all tracks as is: we don't know which clients
6114 // and tracks are able to be recreated as offloaded. The next "song" should
6115 // play back offloaded.
6116 if (mMasterMono) {
6117 Vector<audio_io_handle_t> offloaded;
6118 for (size_t i = 0; i < mOutputs.size(); ++i) {
6119 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6120 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6121 offloaded.push(desc->mIoHandle);
6122 }
6123 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006124 for (const auto& handle : offloaded) {
6125 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006126 }
6127 }
6128 // update master mono for all remaining outputs
6129 for (size_t i = 0; i < mOutputs.size(); ++i) {
6130 updateMono(mOutputs.keyAt(i));
6131 }
6132 return NO_ERROR;
6133}
6134
6135status_t AudioPolicyManager::getMasterMono(bool *mono)
6136{
6137 *mono = mMasterMono;
6138 return NO_ERROR;
6139}
6140
Eric Laurentac9cef52017-06-09 15:46:26 -07006141float AudioPolicyManager::getStreamVolumeDB(
6142 audio_stream_type_t stream, int index, audio_devices_t device)
6143{
Vlad Popa9d482762024-06-21 16:40:23 -07006144 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6145 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006146}
6147
jiabin81772902018-04-02 17:52:27 -07006148status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6149 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006150 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006151{
Kriti Dang6537def2021-03-02 13:46:59 +01006152 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6153 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006154 return BAD_VALUE;
6155 }
Kriti Dang6537def2021-03-02 13:46:59 +01006156 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6157 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006158
6159 size_t formatsWritten = 0;
6160 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006161
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006162 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006163 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6164 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006165 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006166 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006167 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006168 bool formatEnabled = true;
6169 switch (forceUse) {
6170 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006171 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006172 break;
6173 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6174 formatEnabled = false;
6175 break;
6176 default: // AUTO or ALWAYS => true
6177 break;
jiabin81772902018-04-02 17:52:27 -07006178 }
6179 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6180 }
jiabin81772902018-04-02 17:52:27 -07006181 }
6182 return NO_ERROR;
6183}
6184
Kriti Dang6537def2021-03-02 13:46:59 +01006185status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6186 audio_format_t *surroundFormats) {
6187 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6188 return BAD_VALUE;
6189 }
6190 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6191 __func__, *numSurroundFormats, surroundFormats);
6192
6193 size_t formatsWritten = 0;
6194 size_t formatsMax = *numSurroundFormats;
6195 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6196
6197 // Return formats from all device profiles that have already been resolved by
6198 // checkOutputsForDevice().
6199 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6200 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6201 audio_devices_t deviceType = device->type();
6202 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6203 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006204 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6205 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006206 continue;
6207 }
6208 // Formats reported by sink devices
6209 std::unordered_set<audio_format_t> formatset;
6210 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6211 formatset.insert(it->second.begin(), it->second.end());
6212 }
6213
6214 // Formats hard-coded in the in policy configuration file (if any).
6215 FormatVector encodedFormats = device->encodedFormats();
6216 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6217 // Filter the formats which are supported by the vendor hardware.
6218 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006219 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006220 formats.insert(*it);
6221 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006222 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006223 if (pair.second.count(*it) != 0) {
6224 formats.insert(pair.first);
6225 break;
6226 }
6227 }
6228 }
6229 }
6230 }
6231 *numSurroundFormats = formats.size();
6232 for (const auto& format: formats) {
6233 if (formatsWritten < formatsMax) {
6234 surroundFormats[formatsWritten++] = format;
6235 }
6236 }
6237 return NO_ERROR;
6238}
6239
jiabin81772902018-04-02 17:52:27 -07006240status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6241{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006242 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006243 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6244 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006245 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006246 return BAD_VALUE;
6247 }
6248
Mikhail Naganov100f0122018-11-29 11:22:16 -08006249 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6250 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006251 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006252 return INVALID_OPERATION;
6253 }
6254
Mikhail Naganov100f0122018-11-29 11:22:16 -08006255 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006256 return NO_ERROR;
6257 }
6258
Mikhail Naganov100f0122018-11-29 11:22:16 -08006259 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006260 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006261 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006262 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006263 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006264 }
6265 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006266 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006267 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006268 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006269 }
6270 }
6271
6272 sp<SwAudioOutputDescriptor> outputDesc;
6273 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006274 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6275 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006276 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6277 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006278 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006279 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006280 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006281 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 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006288 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006289 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 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006295 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006296 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006297 AUDIO_DEVICE_IN_HDMI);
6298 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6299 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006300 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006301 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006302 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6303 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6304 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006305 name.c_str(),
6306 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006307 if (status != NO_ERROR) {
6308 continue;
6309 }
6310 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6311 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6312 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006313 name.c_str(),
6314 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006315 profileUpdated |= (status == NO_ERROR);
6316 }
6317
jiabin81772902018-04-02 17:52:27 -07006318 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006319 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006320 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006321 }
6322
6323 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6324}
6325
Eric Laurent5ada82e2019-08-29 17:53:54 -07006326void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006327{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006328 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006329 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006330 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006331 }
6332}
6333
jiabin6012f912018-11-02 17:06:30 -07006334bool AudioPolicyManager::isHapticPlaybackSupported()
6335{
6336 for (const auto& hwModule : mHwModules) {
6337 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6338 for (const auto &outProfile : outputProfiles) {
6339 struct audio_port audioPort;
6340 outProfile->toAudioPort(&audioPort);
6341 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6342 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6343 return true;
6344 }
6345 }
6346 }
6347 }
6348 return false;
6349}
6350
Carter Hsu325a8eb2022-01-19 19:56:51 +08006351bool AudioPolicyManager::isUltrasoundSupported()
6352{
6353 bool hasUltrasoundOutput = false;
6354 bool hasUltrasoundInput = false;
6355 for (const auto& hwModule : mHwModules) {
6356 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6357 if (!hasUltrasoundOutput) {
6358 for (const auto &outProfile : outputProfiles) {
6359 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6360 hasUltrasoundOutput = true;
6361 break;
6362 }
6363 }
6364 }
6365
6366 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6367 if (!hasUltrasoundInput) {
6368 for (const auto &inputProfile : inputProfiles) {
6369 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6370 hasUltrasoundInput = true;
6371 break;
6372 }
6373 }
6374 }
6375
6376 if (hasUltrasoundOutput && hasUltrasoundInput)
6377 return true;
6378 }
6379 return false;
6380}
6381
Atneya Nair698f5ef2022-12-15 16:15:09 -08006382bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6383{
6384 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6385 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6386 for (const auto& hwModule : mHwModules) {
6387 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6388 for (const auto &inputProfile : inputProfiles) {
6389 if ((inputProfile->getFlags() & mask) == mask) {
6390 return true;
6391 }
6392 }
6393 }
6394 return false;
6395}
6396
Eric Laurent8340e672019-11-06 11:01:08 -08006397bool AudioPolicyManager::isCallScreenModeSupported()
6398{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006399 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006400}
6401
6402
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006403status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006404{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006405 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006406 if (!sourceDesc->isConnected()) {
6407 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6408 return NO_ERROR;
6409 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006410 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6411 if (swOutput != 0) {
6412 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006413 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006414 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006415 }
jiabinbce0c1d2020-10-05 11:20:18 -07006416 if (releaseOutput(sourceDesc->portId())) {
6417 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6418 // no need to release audio patch here but just return NO_ERROR.
6419 return NO_ERROR;
6420 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006421 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006422 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006423 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006424 // close Hwoutput and remove from mHwOutputs
6425 } else {
6426 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6427 }
6428 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006429 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006430 sourceDesc->disconnect();
6431 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006432}
6433
François Gaffiec005e562018-11-06 15:04:49 +01006434sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6435 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006436{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006437 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006438 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006439 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006440 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006441 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6442 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006443 source = sourceDesc;
6444 break;
6445 }
6446 }
6447 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006448}
6449
Eric Laurentb4f42a92022-01-17 17:37:31 +01006450bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006451 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006452 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006453{
6454 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6455 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006456 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006457 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006458 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6459 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6460 return false;
6461 }
6462 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6463 return false;
6464 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006465 }
6466
Eric Laurentd332bc82023-08-04 11:45:23 +02006467 // The caller can have the audio config criteria ignored by either passing a null ptr or
6468 // the AUDIO_CONFIG_INITIALIZER value.
6469 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006470 // some positional channel masks and PCM format and for stereo if low latency performance
6471 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006472
6473 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006474 const bool channel_mask_spatialized =
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00006475 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6476 ? audio_channel_mask_contains_stereo(config->channel_mask)
6477 : audio_is_channel_mask_spatialized(config->channel_mask);
Andy Hung481bfe32023-12-18 14:00:29 -08006478 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006479 return false;
6480 }
6481 if (!audio_is_linear_pcm(config->format)) {
6482 return false;
6483 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006484 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6485 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6486 return false;
6487 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006488 }
6489
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006490 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006491 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006492 if (profile == nullptr) {
6493 return false;
6494 }
6495
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006496 return true;
6497}
6498
Shunkai Yao4c3af932024-04-26 04:12:21 +00006499// The Spatializer output is compatible with Haptic use cases if:
6500// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6501// with client if client haptic channel bits were set, or
6502// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6503// including the haptic bits or creating the HapticGenerator effect for same session.
6504bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6505 const audio_config_t* config, audio_session_t sessionId) const {
6506 const auto clientHapticChannel =
6507 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6508 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6509 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6510
6511 if (threadOutputHapticChannel) {
6512 // check format and sampleRate match if client haptic channel mask exist
6513 if (clientHapticChannel) {
6514 return mSpatializerOutput->getFormat() == config->format &&
6515 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6516 }
6517 return true;
6518 } else {
6519 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6520 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6521 // HapticGenerator effect for this session) are not supported.
6522 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006523 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006524 }
6525}
6526
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006527void AudioPolicyManager::checkVirtualizerClientRoutes() {
6528 std::set<audio_stream_type_t> streamsToInvalidate;
6529 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006530 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6531 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006532 audio_attributes_t attr = client->attributes();
6533 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6534 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6535 audio_config_base_t clientConfig = client->config();
6536 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006537 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006538 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006539 streamsToInvalidate.insert(client->stream());
6540 }
6541 }
6542 }
6543
jiabinc44b3462022-12-08 12:52:31 -08006544 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006545}
6546
Eric Laurente191d1b2022-04-15 11:59:25 +02006547
6548bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6549 const sp<SwAudioOutputDescriptor>& outputDesc) {
6550 if (outputDesc->isDuplicated()) {
6551 return false;
6552 }
6553 DeviceVector devices = outputDesc->supportedDevices();
6554 for (size_t i = 0; i < mOutputs.size(); i++) {
6555 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6556 if (desc == outputDesc || desc->isDuplicated()) {
6557 continue;
6558 }
6559 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6560 if (!sharedDevices.isEmpty()
6561 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6562 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6563 return false;
6564 }
6565 }
6566 return true;
6567}
6568
6569
Eric Laurentfa0f6742021-08-17 18:39:44 +02006570status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006571 const audio_attributes_t *attr,
6572 audio_io_handle_t *output) {
6573 *output = AUDIO_IO_HANDLE_NONE;
6574
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006575 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6576 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6577 audio_config_t *configPtr = nullptr;
6578 audio_config_t config;
6579 if (mixerConfig != nullptr) {
6580 config = audio_config_initializer(mixerConfig);
6581 configPtr = &config;
6582 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006583 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006584 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006585 return BAD_VALUE;
6586 }
6587
6588 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006589 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006590 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006591 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006592 return BAD_VALUE;
6593 }
6594
Eric Laurente191d1b2022-04-15 11:59:25 +02006595 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006596 for (size_t i = 0; i < mOutputs.size(); i++) {
6597 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006598 if (!desc->isDuplicated()
6599 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6600 spatializerOutputs.push_back(desc);
6601 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006602 }
6603 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006604 mSpatializerOutput.clear();
6605 bool outputsChanged = false;
6606 for (const auto& desc : spatializerOutputs) {
6607 if (desc->mProfile == profile
6608 && (configPtr == nullptr
6609 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6610 mSpatializerOutput = desc;
6611 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6612 } else {
6613 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6614 " and devices %s", __func__, desc->mIoHandle,
6615 configPtr != nullptr ? configPtr->channel_mask : 0,
6616 devices.toString().c_str());
6617 closeOutput(desc->mIoHandle);
6618 outputsChanged = true;
6619 }
Eric Laurent39095982021-08-24 18:29:27 +02006620 }
6621
Eric Laurente191d1b2022-04-15 11:59:25 +02006622 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006623 sp<SwAudioOutputDescriptor> desc =
6624 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006625 if (desc != nullptr) {
6626 mSpatializerOutput = desc;
6627 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006628 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006629 }
6630
6631 checkVirtualizerClientRoutes();
6632
Eric Laurente191d1b2022-04-15 11:59:25 +02006633 if (outputsChanged) {
6634 mPreviousOutputs = mOutputs;
6635 mpClientInterface->onAudioPortListUpdate();
6636 }
6637
6638 if (mSpatializerOutput == nullptr) {
6639 ALOGV("%s could not open spatializer output with requested config", __func__);
6640 return BAD_VALUE;
6641 }
Eric Laurent39095982021-08-24 18:29:27 +02006642 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006643 ALOGV("%s returning new spatializer output %d", __func__, *output);
6644 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006645}
6646
Eric Laurentfa0f6742021-08-17 18:39:44 +02006647status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6648 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006649 return INVALID_OPERATION;
6650 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006651 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006652 return BAD_VALUE;
6653 }
Eric Laurent39095982021-08-24 18:29:27 +02006654
Eric Laurente191d1b2022-04-15 11:59:25 +02006655 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6656 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6657 closeOutput(mSpatializerOutput->mIoHandle);
6658 //from now on mSpatializerOutput is null
6659 checkVirtualizerClientRoutes();
6660 }
Eric Laurent39095982021-08-24 18:29:27 +02006661
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006662 return NO_ERROR;
6663}
6664
Eric Laurente552edb2014-03-10 17:42:56 -07006665// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006666// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006667// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006668uint32_t AudioPolicyManager::nextAudioPortGeneration()
6669{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006670 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006671}
6672
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006673AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006674 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006675 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006676 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006677 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006678 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006679 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006680 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006681 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006682 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006683 mAudioPortGeneration(1),
6684 mBeaconMuteRefCount(0),
6685 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006686 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006687 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006688 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006689 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006690{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006691}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006692
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006693status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006694 if (mEngine == nullptr) {
6695 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006696 }
6697 mEngine->setObserver(this);
6698 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006699 if (status != NO_ERROR) {
6700 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6701 return status;
6702 }
François Gaffie2110e042015-03-24 08:41:51 +01006703
jiabin29230182023-04-04 21:02:36 +00006704 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6705 // at the end of this function.
6706 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006707 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6708 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6709
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006710 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006711 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006712 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006713
Eric Laurent3a4311c2014-03-17 12:00:47 -07006714 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006715 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6716 defaultOutputDevice == nullptr ||
6717 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6718 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6719 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006720 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006721 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006722 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006723
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006724 // Silence ALOGV statements
6725 property_set("log.tag." LOG_TAG, "D");
6726
Eric Laurente552edb2014-03-10 17:42:56 -07006727 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006728 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006729}
6730
Eric Laurente0720872014-03-11 09:30:41 -07006731AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006732{
Eric Laurente552edb2014-03-10 17:42:56 -07006733 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006734 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006735 }
6736 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006737 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006738 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006739 mAvailableOutputDevices.clear();
6740 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006741 mOutputs.clear();
6742 mInputs.clear();
6743 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006744 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006745 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006746}
6747
Eric Laurente0720872014-03-11 09:30:41 -07006748status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006749{
Eric Laurent87ffa392015-05-22 10:32:38 -07006750 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006751}
6752
Eric Laurente552edb2014-03-10 17:42:56 -07006753// ---
6754
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006755void AudioPolicyManager::onNewAudioModulesAvailable()
6756{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006757 DeviceVector newDevices;
6758 onNewAudioModulesAvailableInt(&newDevices);
6759 if (!newDevices.empty()) {
6760 nextAudioPortGeneration();
6761 mpClientInterface->onAudioPortListUpdate();
6762 }
6763}
6764
6765void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6766{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006767 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006768 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6769 continue;
6770 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006771 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006772 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6773 handle != AUDIO_MODULE_HANDLE_NONE) {
6774 hwModule->setHandle(handle);
6775 } else {
6776 ALOGW("could not load HW module %s", hwModule->getName());
6777 continue;
6778 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006779 }
6780 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006781 // open all output streams needed to access attached devices.
6782 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006783 // This also validates mAvailableOutputDevices list
6784 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6785 if (!outProfile->canOpenNewIo()) {
6786 ALOGE("Invalid Output profile max open count %u for profile %s",
6787 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6788 continue;
6789 }
6790 if (!outProfile->hasSupportedDevices()) {
6791 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6792 continue;
6793 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006794 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6795 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006796 mTtsOutputAvailable = true;
6797 }
6798
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006799 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006800 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006801 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006802 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6803 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006804 } else {
6805 // choose first device present in profile's SupportedDevices also part of
6806 // mAvailableOutputDevices.
6807 if (availProfileDevices.isEmpty()) {
6808 continue;
6809 }
6810 supportedDevice = availProfileDevices.itemAt(0);
6811 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006812 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006813 continue;
6814 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306815
6816 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6817 && availProfileDevices.areAllDevicesAttached()) {
6818 ALOGV("%s skip opening output for mmap profile %s", __func__,
6819 outProfile->getTagName().c_str());
6820 continue;
6821 }
6822
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006823 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6824 mpClientInterface);
6825 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006826 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006827 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006828 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6829 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006830 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006831 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006832 if (status != NO_ERROR) {
6833 ALOGW("Cannot open output stream for devices %s on hw module %s",
6834 supportedDevice->toString().c_str(), hwModule->getName());
6835 continue;
6836 }
6837 for (const auto &device : availProfileDevices) {
6838 // give a valid ID to an attached device once confirmed it is reachable
6839 if (!device->isAttached()) {
6840 device->attach(hwModule);
6841 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006842 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006843 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006844 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6845 }
6846 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006847 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006848 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6849 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006850 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006851 }
Eric Laurent39095982021-08-24 18:29:27 +02006852 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006853 outputDesc->close();
6854 } else {
6855 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306856 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006857 DeviceVector(supportedDevice),
6858 true,
6859 0,
6860 NULL);
6861 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006862 }
6863 // open input streams needed to access attached devices to validate
6864 // mAvailableInputDevices list
6865 for (const auto& inProfile : hwModule->getInputProfiles()) {
6866 if (!inProfile->canOpenNewIo()) {
6867 ALOGE("Invalid Input profile max open count %u for profile %s",
6868 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6869 continue;
6870 }
6871 if (!inProfile->hasSupportedDevices()) {
6872 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6873 continue;
6874 }
6875 // chose first device present in profile's SupportedDevices also part of
6876 // available input devices
6877 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006878 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006879 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006880 ALOGV("%s: Input device list is empty! for profile %s",
6881 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006882 continue;
6883 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306884
6885 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6886 && availProfileDevices.areAllDevicesAttached()) {
6887 ALOGV("%s skip opening input for mmap profile %s", __func__,
6888 inProfile->getTagName().c_str());
6889 continue;
6890 }
6891
Eric Laurentc71b11b2024-06-03 12:54:53 +00006892 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6893 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006894
6895 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6896 status_t status = inputDesc->open(nullptr,
6897 availProfileDevices.itemAt(0),
6898 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306899 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006900 &input);
6901 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306902 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6903 __func__, availProfileDevices.toString().c_str(),
6904 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006905 continue;
6906 }
6907 for (const auto &device : availProfileDevices) {
6908 // give a valid ID to an attached device once confirmed it is reachable
6909 if (!device->isAttached()) {
6910 device->attach(hwModule);
6911 device->importAudioPortAndPickAudioProfile(inProfile, true);
6912 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006913 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006914 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6915 }
6916 }
6917 inputDesc->close();
6918 }
6919 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006920
6921 // Check if spatializer outputs can be closed until used.
6922 // mOutputs vector never contains duplicated outputs at this point.
6923 std::vector<audio_io_handle_t> outputsClosed;
6924 for (size_t i = 0; i < mOutputs.size(); i++) {
6925 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6926 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6927 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6928 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006929 nextAudioPortGeneration();
6930 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6931 if (index >= 0) {
6932 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6933 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6934 patchDesc->getAfHandle(), 0);
6935 mAudioPatches.removeItemsAt(index);
6936 mpClientInterface->onAudioPatchListUpdate();
6937 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006938 desc->close();
6939 }
6940 }
6941 for (auto output : outputsClosed) {
6942 removeOutput(output);
6943 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006944}
6945
Eric Laurent98e38192018-02-15 18:31:53 -08006946void AudioPolicyManager::addOutput(audio_io_handle_t output,
6947 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006948{
Eric Laurent1c333e22014-05-20 10:48:17 -07006949 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006950 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006951 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006952 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006953 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006954}
6955
François Gaffie53615e22015-03-19 09:24:12 +01006956void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6957{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006958 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6959 ALOGV("%s: removing primary output", __func__);
6960 mPrimaryOutput = nullptr;
6961 }
François Gaffie53615e22015-03-19 09:24:12 +01006962 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006963 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006964}
6965
Eric Laurent98e38192018-02-15 18:31:53 -08006966void AudioPolicyManager::addInput(audio_io_handle_t input,
6967 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006968{
Eric Laurent1c333e22014-05-20 10:48:17 -07006969 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006970 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006971}
Eric Laurente552edb2014-03-10 17:42:56 -07006972
François Gaffie11d30102018-11-02 16:09:09 +01006973status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006974 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006975 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006976{
François Gaffie11d30102018-11-02 16:09:09 +01006977 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006978 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006979 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006980
François Gaffie11d30102018-11-02 16:09:09 +01006981 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006982 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006983 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006984 }
Eric Laurente552edb2014-03-10 17:42:56 -07006985
Eric Laurent3b73df72014-03-11 09:06:29 -07006986 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006987 // first call getAudioPort to get the supported attributes from the HAL
6988 struct audio_port_v7 port = {};
6989 device->toAudioPort(&port);
6990 status_t status = mpClientInterface->getAudioPort(&port);
6991 if (status == NO_ERROR) {
6992 device->importAudioPort(port);
6993 }
6994
6995 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006996 for (size_t i = 0; i < mOutputs.size(); i++) {
6997 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006998 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006999 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01007000 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
7001 mOutputs.keyAt(i), device->toString().c_str());
7002 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007003 }
7004 }
7005 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007006 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007007 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007008 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7009 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01007010 if (profile->supportsDevice(device)) {
7011 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307012 ALOGV("%s(): adding profile %s from module %s",
7013 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07007014 }
7015 }
7016 }
7017
Eric Laurent7b279bb2015-12-14 10:18:23 -08007018 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007019
Eric Laurente552edb2014-03-10 17:42:56 -07007020 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007021 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007022 return BAD_VALUE;
7023 }
7024
7025 // open outputs for matching profiles if needed. Direct outputs are also opened to
7026 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7027 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007028 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07007029
7030 // nothing to do if one output is already opened for this profile
7031 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007032 for (j = 0; j < outputs.size(); j++) {
7033 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07007034 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007035 // matching profile: save the sample rates, format and channel masks supported
7036 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01007037 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07007038 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007039 }
Eric Laurente552edb2014-03-10 17:42:56 -07007040 break;
7041 }
7042 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007043 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07007044 continue;
7045 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307046 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7047 ALOGV("%s skip opening output for mmap profile %s",
7048 __func__, profile->getTagName().c_str());
7049 continue;
7050 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007051 if (!profile->canOpenNewIo()) {
7052 ALOGW("Max Output number %u already opened for this profile %s",
7053 profile->maxOpenCount, profile->getTagName().c_str());
7054 continue;
7055 }
7056
Eric Laurent83efe1c2017-07-09 16:51:08 -07007057 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00007058 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07007059 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
7060 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07007061 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01007062 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007063 profiles.removeAt(profile_index);
7064 profile_index--;
7065 } else {
7066 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07007067 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01007068 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07007069 // TODO: when getAudioPort is ready, it may not be needed to import the audio
7070 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07007071 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007072 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007073
François Gaffie11d30102018-11-02 16:09:09 +01007074 if (device_distinguishes_on_address(deviceType)) {
7075 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
7076 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307077 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
7078 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007079 }
Eric Laurente552edb2014-03-10 17:42:56 -07007080 ALOGV("checkOutputsForDevice(): adding output %d", output);
7081 }
7082 }
7083
7084 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007085 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007086 return BAD_VALUE;
7087 }
Eric Laurentd4692962014-05-05 18:13:44 -07007088 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07007089 // check if one opened output is not needed any more after disconnecting one device
7090 for (size_t i = 0; i < mOutputs.size(); i++) {
7091 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007092 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007093 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007094 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01007095 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01007096 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01007097 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007098 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7099 mOutputs.keyAt(i));
7100 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007101 }
Eric Laurente552edb2014-03-10 17:42:56 -07007102 }
7103 }
Eric Laurentd4692962014-05-05 18:13:44 -07007104 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007105 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007106 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7107 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007108 if (!profile->supportsDevice(device)) {
7109 continue;
7110 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307111 ALOGV("%s(): clearing direct output profile %s on module %s",
7112 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007113 profile->clearAudioProfiles();
7114 if (!profile->hasDynamicAudioProfile()) {
7115 continue;
7116 }
7117 // When a device is disconnected, if there is an IOProfile that contains dynamic
7118 // profiles and supports the disconnected device, call getAudioPort to repopulate
7119 // the capabilities of the devices that is supported by the IOProfile.
7120 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7121 if (supportedDevice == device ||
7122 !mAvailableOutputDevices.contains(supportedDevice)) {
7123 continue;
7124 }
7125 struct audio_port_v7 port;
7126 supportedDevice->toAudioPort(&port);
7127 status_t status = mpClientInterface->getAudioPort(&port);
7128 if (status == NO_ERROR) {
7129 supportedDevice->importAudioPort(port);
7130 }
Eric Laurente552edb2014-03-10 17:42:56 -07007131 }
7132 }
7133 }
7134 }
7135 return NO_ERROR;
7136}
7137
François Gaffie11d30102018-11-02 16:09:09 +01007138status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007139 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007140{
François Gaffie11d30102018-11-02 16:09:09 +01007141 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007142 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007143 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007144 }
7145
Eric Laurentd4692962014-05-05 18:13:44 -07007146 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007147 sp<AudioInputDescriptor> desc;
7148
jiabinbf5f4262023-04-12 21:48:34 +00007149 // first call getAudioPort to get the supported attributes from the HAL
7150 struct audio_port_v7 port = {};
7151 device->toAudioPort(&port);
7152 status_t status = mpClientInterface->getAudioPort(&port);
7153 if (status == NO_ERROR) {
7154 device->importAudioPort(port);
7155 }
7156
Eric Laurent0dd51852019-04-19 18:18:58 -07007157 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007158 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007159 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007160 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007161 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007162 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007163 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007164
François Gaffie11d30102018-11-02 16:09:09 +01007165 if (profile->supportsDevice(device)) {
7166 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307167 ALOGV("%s : adding profile %s from module %s", __func__,
7168 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007169 }
7170 }
7171 }
7172
Eric Laurent0dd51852019-04-19 18:18:58 -07007173 if (profiles.isEmpty()) {
7174 ALOGW("%s: No input profile available for device %s",
7175 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007176 return BAD_VALUE;
7177 }
7178
7179 // open inputs for matching profiles if needed. Direct inputs are also opened to
7180 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7181 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7182
Eric Laurent1c333e22014-05-20 10:48:17 -07007183 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007184
Eric Laurentd4692962014-05-05 18:13:44 -07007185 // nothing to do if one input is already opened for this profile
7186 size_t input_index;
7187 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7188 desc = mInputs.valueAt(input_index);
7189 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007190 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007191 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007192 }
Eric Laurentd4692962014-05-05 18:13:44 -07007193 break;
7194 }
7195 }
7196 if (input_index != mInputs.size()) {
7197 continue;
7198 }
7199
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307200 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7201 ALOGV("%s skip opening input for mmap profile %s",
7202 __func__, profile->getTagName().c_str());
7203 continue;
7204 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007205 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307206 ALOGW("%s Max Input number %u already opened for this profile %s",
7207 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007208 continue;
7209 }
7210
Eric Laurentc71b11b2024-06-03 12:54:53 +00007211 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007212 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307213 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307214 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7215 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007216
Eric Laurentcf2c0212014-07-25 16:20:43 -07007217 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007218 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007219 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007220 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007221 mpClientInterface->setParameters(input, String8(param));
7222 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007223 }
jiabin12537fc2023-10-12 17:56:08 +00007224 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007225 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307226 ALOGW("%s direct input missing param for profile %s", __func__,
7227 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007228 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007229 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007230 }
7231
Eric Laurent0dd51852019-04-19 18:18:58 -07007232 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007233 addInput(input, desc);
7234 }
7235 } // endif input != 0
7236
Eric Laurentcf2c0212014-07-25 16:20:43 -07007237 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307238 ALOGW("%s could not open input for device %s on profile %s", __func__,
7239 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007240 profiles.removeAt(profile_index);
7241 profile_index--;
7242 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007243 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007244 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007245 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307246 ALOGV("%s: adding input %d for profile %s", __func__,
7247 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007248
7249 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307250 ALOGV("%s: closing input %d for profile %s", __func__,
7251 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007252 closeInput(input);
7253 }
Eric Laurentd4692962014-05-05 18:13:44 -07007254 }
7255 } // end scan profiles
7256
7257 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007258 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007259 return BAD_VALUE;
7260 }
7261 } else {
7262 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007263 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007264 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007265 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007266 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007267 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007268 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007269 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307270 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7271 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007272 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007273 }
7274 }
7275 }
7276 } // end disconnect
7277
7278 return NO_ERROR;
7279}
7280
7281
Eric Laurente0720872014-03-11 09:30:41 -07007282void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007283{
7284 ALOGV("closeOutput(%d)", output);
7285
François Gaffie1c878552018-11-22 16:53:21 +01007286 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7287 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007288 ALOGW("closeOutput() unknown output %d", output);
7289 return;
7290 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007291 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007292 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007293
Eric Laurente552edb2014-03-10 17:42:56 -07007294 // look for duplicated outputs connected to the output being removed.
7295 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007296 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7297 if (dupOutput->isDuplicated() &&
7298 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7299 sp<SwAudioOutputDescriptor> remainingOutput =
7300 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007301 // As all active tracks on duplicated output will be deleted,
7302 // and as they were also referenced on the other output, the reference
7303 // count for their stream type must be adjusted accordingly on
7304 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007305 const bool wasActive = remainingOutput->isActive();
7306 // Note: no-op on the closing output where all clients has already been set inactive
7307 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007308 // stop() will be a no op if the output is still active but is needed in case all
7309 // active streams refcounts where cleared above
7310 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007311 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007312 }
Eric Laurente552edb2014-03-10 17:42:56 -07007313 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7314 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7315
7316 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007317 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007318 }
7319 }
7320
Eric Laurent05b90f82014-08-27 15:32:29 -07007321 nextAudioPortGeneration();
7322
François Gaffie1c878552018-11-22 16:53:21 +01007323 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007324 if (index >= 0) {
7325 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007326 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7327 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007328 mAudioPatches.removeItemsAt(index);
7329 mpClientInterface->onAudioPatchListUpdate();
7330 }
7331
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007332 if (closingOutputWasActive) {
7333 closingOutput->stop();
7334 }
François Gaffie1c878552018-11-22 16:53:21 +01007335 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007336 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007337 for (const auto device : closingOutput->devices()) {
7338 device->setPreferredConfig(nullptr);
7339 }
7340 }
Eric Laurente552edb2014-03-10 17:42:56 -07007341
François Gaffie53615e22015-03-19 09:24:12 +01007342 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007343 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007344 if (closingOutput == mSpatializerOutput) {
7345 mSpatializerOutput.clear();
7346 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007347
7348 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7349 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007350 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007351 bool directOutputOpen = false;
7352 for (size_t i = 0; i < mOutputs.size(); i++) {
7353 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7354 directOutputOpen = true;
7355 break;
7356 }
7357 }
7358 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007359 ALOGV("no direct outputs open, reset MSD patches");
7360 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7361 // how output devices for patching are resolved. Avoid by caching and reusing the
7362 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7363 // devices to patch to. This may be complicated by the fact that devices may become
7364 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007365 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007366 }
7367 }
jiabin220eea12024-05-17 17:55:20 +00007368
7369 if (closingOutput->mPreferredAttrInfo != nullptr) {
7370 closingOutput->mPreferredAttrInfo->resetActiveClient();
7371 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007372}
7373
7374void AudioPolicyManager::closeInput(audio_io_handle_t input)
7375{
7376 ALOGV("closeInput(%d)", input);
7377
7378 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7379 if (inputDesc == NULL) {
7380 ALOGW("closeInput() unknown input %d", input);
7381 return;
7382 }
7383
Eric Laurent6a94d692014-05-20 11:18:06 -07007384 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007385
François Gaffie11d30102018-11-02 16:09:09 +01007386 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007387 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007388 if (index >= 0) {
7389 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007390 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7391 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007392 mAudioPatches.removeItemsAt(index);
7393 mpClientInterface->onAudioPatchListUpdate();
7394 }
7395
François Gaffie6ebbce02023-07-19 13:27:53 +02007396 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007397 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007398 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007399
François Gaffie11d30102018-11-02 16:09:09 +01007400 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7401 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007402 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007403 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007404 }
Eric Laurente552edb2014-03-10 17:42:56 -07007405}
7406
François Gaffie11d30102018-11-02 16:09:09 +01007407SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7408 const DeviceVector &devices,
7409 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007410{
7411 SortedVector<audio_io_handle_t> outputs;
7412
François Gaffie11d30102018-11-02 16:09:09 +01007413 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007414 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007415 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007416 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007417 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007418 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007419 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007420 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007421 outputs.add(openOutputs.keyAt(i));
7422 }
7423 }
7424 return outputs;
7425}
7426
Mikhail Naganov37977152018-07-11 15:54:44 -07007427void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7428{
7429 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7430 // output is suspended before any tracks are moved to it
7431 checkA2dpSuspend();
7432 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007433 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007434 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007435 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007436 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007437 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7438 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7439 // configuration changes will ultimately be rerouted correctly. We can still avoid
7440 // unnecessary rerouting by caching and reusing the arguments to
7441 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7442 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007443 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007444 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007445 // an event that changed routing likely occurred, inform upper layers
7446 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007447}
7448
François Gaffiec005e562018-11-06 15:04:49 +01007449bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7450 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007451{
François Gaffiec005e562018-11-06 15:04:49 +01007452 return mEngine->getProductStrategyForAttributes(lAttr) ==
7453 mEngine->getProductStrategyForAttributes(rAttr);
7454}
7455
Francois Gaffieff1eb522020-05-06 18:37:04 +02007456void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7457{
7458 for (size_t i = 0; i < mAudioSources.size(); i++) {
7459 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7460 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007461 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007462 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007463 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007464 }
7465 }
7466}
7467
7468void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7469{
7470 for (size_t i = 0; i < mAudioSources.size(); i++) {
7471 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7472 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7473 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7474 disconnectAudioSource(sourceDesc);
7475 }
7476 }
7477}
7478
François Gaffiec005e562018-11-06 15:04:49 +01007479void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7480{
7481 auto psId = mEngine->getProductStrategyForAttributes(attr);
7482
7483 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7484 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007485
François Gaffie11d30102018-11-02 16:09:09 +01007486 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7487 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007488
Eric Laurentc209fe42020-06-05 18:11:23 -07007489 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007490 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007491 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007492 // take into account dynamic audio policies related changes: if a client is now associated
7493 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007494 // invalidate clients on outputs that do not support all the newly selected devices for the
7495 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007496 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007497 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007498 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007499 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007500 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007501
Eric Laurentc209fe42020-06-05 18:11:23 -07007502 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7503 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7504 continue;
7505 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007506 if (!desc->supportsAllDevices(newDevices)) {
7507 invalidatedOutputs.push_back(desc);
7508 break;
7509 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007510 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007511 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007512 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7513 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7514 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007515 if (status == OK) {
7516 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7517 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7518 maxLatency = desc->latency();
7519 }
7520 invalidatedOutputs.push_back(desc);
7521 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007522 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007523 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007524 }
7525 }
7526
Eric Laurent56ed8842022-11-15 16:04:41 +01007527 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007528 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7529 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007530 for (audio_io_handle_t srcOut : srcOutputs) {
7531 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007532 if (desc == nullptr) continue;
7533
7534 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007535 maxLatency = desc->latency();
7536 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007537
Eric Laurent56ed8842022-11-15 16:04:41 +01007538 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007539 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007540 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007541 // a client on a non direct outputs has necessarily a linear PCM format
7542 // so we can call selectOutput() safely
7543 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7544 client->flags(),
7545 client->config().format,
7546 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007547 client->config().sample_rate,
7548 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007549 if (newOutput != srcOut) {
7550 invalidate = true;
7551 break;
7552 }
7553 } else {
7554 sp<IOProfile> profile = getProfileForOutput(newDevices,
7555 client->config().sample_rate,
7556 client->config().format,
7557 client->config().channel_mask,
7558 client->flags(),
7559 true /* directOnly */);
7560 if (profile != desc->mProfile) {
7561 invalidate = true;
7562 break;
7563 }
7564 }
7565 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007566 // mute strategy while moving tracks from one output to another
7567 if (invalidate) {
7568 invalidatedOutputs.push_back(desc);
7569 if (desc->isStrategyActive(psId)) {
7570 setStrategyMute(psId, true, desc);
7571 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7572 newDevices.types());
7573 }
Eric Laurente552edb2014-03-10 17:42:56 -07007574 }
François Gaffiec005e562018-11-06 15:04:49 +01007575 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007576 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007577 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007578 }
Eric Laurente552edb2014-03-10 17:42:56 -07007579 }
7580
Eric Laurent56ed8842022-11-15 16:04:41 +01007581 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7582 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7583 std::to_string(srcOutputs[0]).c_str(),
7584 std::to_string(dstOutputs[0]).c_str());
7585
François Gaffiec005e562018-11-06 15:04:49 +01007586 // Move effects associated to this stream from previous output to new output
7587 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007588 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007589 }
François Gaffiec005e562018-11-06 15:04:49 +01007590 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007591 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007592 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007593 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007594 desc->setTracksInvalidatedStatusByStrategy(psId);
7595 }
Eric Laurente552edb2014-03-10 17:42:56 -07007596 }
7597 }
7598}
7599
Eric Laurente0720872014-03-11 09:30:41 -07007600void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007601{
François Gaffiec005e562018-11-06 15:04:49 +01007602 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7603 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7604 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007605 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007606 }
Eric Laurente552edb2014-03-10 17:42:56 -07007607}
7608
Kevin Rocard153f92d2018-12-18 18:33:28 -08007609void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007610 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007611 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007612 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007613 for (size_t i = 0; i < mOutputs.size(); i++) {
7614 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7615 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007616 sp<AudioPolicyMix> primaryMix;
7617 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007618 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007619 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7620 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7621 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007622 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7623 for (auto &secondaryMix : secondaryMixes) {
7624 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7625 if (outputDesc != nullptr &&
7626 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7627 secondaryDescs.push_back(outputDesc);
7628 }
7629 }
7630
jiabinc44b3462022-12-08 12:52:31 -08007631 if (status != OK &&
7632 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7633 // When it failed to query secondary output, only invalidate the client that is not
7634 // MMAP. The reason is that MMAP stream will not support secondary output.
7635 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007636 } else if (!std::equal(
7637 client->getSecondaryOutputs().begin(),
7638 client->getSecondaryOutputs().end(),
7639 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007640 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7641 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007642 // If the format is not PCM, the tracks should be invalidated to get correct
7643 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007644 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007645 } else {
7646 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7647 std::vector<audio_io_handle_t> secondaryOutputIds;
7648 for (const auto &secondaryDesc: secondaryDescs) {
7649 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7650 weakSecondaryDescs.push_back(secondaryDesc);
7651 }
7652 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7653 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007654 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007655 }
7656 }
7657 }
jiabin10a03f12021-05-07 23:46:28 +00007658 if (!trackSecondaryOutputs.empty()) {
7659 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7660 }
jiabinc44b3462022-12-08 12:52:31 -08007661 if (!clientsToInvalidate.empty()) {
7662 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7663 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007664 }
7665}
7666
Eric Laurent2517af32020-11-25 15:31:27 +01007667bool AudioPolicyManager::isScoRequestedForComm() const {
7668 AudioDeviceTypeAddrVector devices;
7669 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7670 for (const auto &device : devices) {
7671 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7672 return true;
7673 }
7674 }
7675 return false;
7676}
7677
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007678bool AudioPolicyManager::isHearingAidUsedForComm() const {
7679 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7680 true /*fromCache*/);
7681 for (const auto &device : devices) {
7682 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7683 return true;
7684 }
7685 }
7686 return false;
7687}
7688
7689
Eric Laurente0720872014-03-11 09:30:41 -07007690void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007691{
François Gaffie53615e22015-03-19 09:24:12 +01007692 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007693 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007694 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007695 return;
7696 }
7697
Eric Laurent3a4311c2014-03-17 12:00:47 -07007698 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007699 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7700 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007701 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007702
7703 // if suspended, restore A2DP output if:
7704 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007705 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007706 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007707 //
Eric Laurentf732e072016-08-03 19:30:28 -07007708 // if not suspended, suspend A2DP output if:
7709 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007710 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007711 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007712 //
7713 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007714 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007715 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007716 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007717 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007718
7719 mpClientInterface->restoreOutput(a2dpOutput);
7720 mA2dpSuspended = false;
7721 }
7722 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007723 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007724 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007725 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007726 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007727
7728 mpClientInterface->suspendOutput(a2dpOutput);
7729 mA2dpSuspended = true;
7730 }
7731 }
7732}
7733
François Gaffie11d30102018-11-02 16:09:09 +01007734DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7735 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007736{
François Gaffiedb1755b2023-09-01 11:50:35 +02007737 if (outputDesc == nullptr) {
7738 return DeviceVector{};
7739 }
François Gaffie11d30102018-11-02 16:09:09 +01007740
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007741 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007742 if (index >= 0) {
7743 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007744 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007745 ALOGV("%s device %s forced by patch %d", __func__,
7746 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7747 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007748 }
7749 }
7750
Dean Wheatley514b4312020-06-17 21:45:00 +10007751 // Do not retrieve engine device for outputs through MSD
7752 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7753 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7754 return outputDesc->devices();
7755 }
7756
Eric Laurent97ac8712018-07-27 18:59:02 -07007757 // Honor explicit routing requests only if no client using default routing is active on this
7758 // input: a specific app can not force routing for other apps by setting a preferred device.
7759 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007760 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007761 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007762 if (device != nullptr) {
7763 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007764 }
7765
François Gaffiea807ef92018-11-05 10:44:33 +01007766 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7767 // of setForceUse / Default Bus device here
7768 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7769 if (device != nullptr) {
7770 return DeviceVector(device);
7771 }
7772
François Gaffiedb1755b2023-09-01 11:50:35 +02007773 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007774 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7775 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307776 auto hasStreamActive = [&](auto stream) {
7777 return hasStream(streams, stream) && isStreamActive(stream, 0);
7778 };
Eric Laurent484e9272018-06-07 17:29:23 -07007779
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307780 auto doGetOutputDevicesForVoice = [&]() {
7781 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007782 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307783 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007784 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7785 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307786 };
7787
7788 // With low-latency playing on speaker, music on WFD, when the first low-latency
7789 // output is stopped, getNewOutputDevices checks for a product strategy
7790 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007791 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307792 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7793 // stream is associated to the output descriptor.
7794 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7795 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7796 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7797 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007798 // Retrieval of devices for voice DL is done on primary output profile, cannot
7799 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007800 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007801 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7802 break;
7803 }
Eric Laurente552edb2014-03-10 17:42:56 -07007804 }
François Gaffiec005e562018-11-06 15:04:49 +01007805 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007806 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007807}
7808
François Gaffie11d30102018-11-02 16:09:09 +01007809sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7810 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007811{
François Gaffie11d30102018-11-02 16:09:09 +01007812 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007813
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007814 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007815 if (index >= 0) {
7816 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007817 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007818 ALOGV("getNewInputDevice() device %s forced by patch %d",
7819 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7820 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007821 }
7822 }
7823
Eric Laurent97ac8712018-07-27 18:59:02 -07007824 // Honor explicit routing requests only if no client using default routing is active on this
7825 // input: a specific app can not force routing for other apps by setting a preferred device.
7826 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007827 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7828 if (device != nullptr) {
7829 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007830 }
7831
Eric Laurentdc95a252018-04-12 12:46:56 -07007832 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007833 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007834 audio_attributes_t attributes;
7835 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007836 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007837 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7838 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007839 attributes = topClient->attributes();
7840 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007841 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007842 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007843 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7844 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007845 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007846 }
7847
Francois Gaffie716e1432019-01-14 16:58:59 +01007848 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7849 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007850 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007851 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007852 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007853 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007854
Eric Laurente552edb2014-03-10 17:42:56 -07007855 return device;
7856}
7857
Eric Laurent794fde22016-03-11 09:50:45 -08007858bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7859 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007860 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007861}
7862
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007863status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007864 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007865 if (devices == nullptr) {
7866 return BAD_VALUE;
7867 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007868
Andy Hung6d23c0f2022-02-16 09:37:15 -08007869 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007870 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7871 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007872 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007873 for (const auto& device : curDevices) {
7874 devices->push_back(device->getDeviceTypeAddr());
7875 }
7876 return NO_ERROR;
7877}
7878
Eric Laurente0720872014-03-11 09:30:41 -07007879void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007880 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007881 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007882 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007883 updateDevicesAndOutputs();
7884 break;
7885 default:
7886 break;
7887 }
7888}
7889
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007890uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007891
7892 // skip beacon mute management if a dedicated TTS output is available
7893 if (mTtsOutputAvailable) {
7894 return 0;
7895 }
7896
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007897 switch(event) {
7898 case STARTING_OUTPUT:
7899 mBeaconMuteRefCount++;
7900 break;
7901 case STOPPING_OUTPUT:
7902 if (mBeaconMuteRefCount > 0) {
7903 mBeaconMuteRefCount--;
7904 }
7905 break;
7906 case STARTING_BEACON:
7907 mBeaconPlayingRefCount++;
7908 break;
7909 case STOPPING_BEACON:
7910 if (mBeaconPlayingRefCount > 0) {
7911 mBeaconPlayingRefCount--;
7912 }
7913 break;
7914 }
7915
7916 if (mBeaconMuteRefCount > 0) {
7917 // any playback causes beacon to be muted
7918 return setBeaconMute(true);
7919 } else {
7920 // no other playback: unmute when beacon starts playing, mute when it stops
7921 return setBeaconMute(mBeaconPlayingRefCount == 0);
7922 }
7923}
7924
7925uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7926 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7927 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7928 // keep track of muted state to avoid repeating mute/unmute operations
7929 if (mBeaconMuted != mute) {
7930 // mute/unmute AUDIO_STREAM_TTS on all outputs
7931 ALOGV("\t muting %d", mute);
7932 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007933 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7934 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7935 ALOGV("\t no tts volume source available");
7936 return 0;
7937 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007938 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007939 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Vlad Popa1e865e62024-08-15 19:11:42 -07007940 setVolumeSourceMutedInternally(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/,
7941 DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007942 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007943 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007944 maxLatency = latency;
7945 }
7946 }
7947 mBeaconMuted = mute;
7948 return maxLatency;
7949 }
7950 return 0;
7951}
7952
Eric Laurente0720872014-03-11 09:30:41 -07007953void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007954{
François Gaffiec005e562018-11-06 15:04:49 +01007955 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007956 mPreviousOutputs = mOutputs;
7957}
7958
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007959uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007960 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007961 uint32_t delayMs)
7962{
7963 // mute/unmute strategies using an incompatible device combination
7964 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7965 // if unmuting, unmute only after the specified delay
7966 if (outputDesc->isDuplicated()) {
7967 return 0;
7968 }
7969
7970 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007971 DeviceVector devices = outputDesc->devices();
7972 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007973
François Gaffiec005e562018-11-06 15:04:49 +01007974 auto productStrategies = mEngine->getOrderedProductStrategies();
7975 for (const auto &productStrategy : productStrategies) {
7976 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7977 DeviceVector curDevices =
7978 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7979 curDevices = curDevices.filter(outputDesc->supportedDevices());
7980 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007981 bool doMute = false;
7982
François Gaffiec005e562018-11-06 15:04:49 +01007983 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007984 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007985 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7986 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007987 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007988 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007989 }
Eric Laurent99401132014-05-07 19:48:15 -07007990 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007991 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007992 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007993 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007994 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007995 continue;
7996 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307997 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007998 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7999 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
8000 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07008001 if (mute) {
8002 // FIXME: should not need to double latency if volume could be applied
8003 // immediately by the audioflinger mixer. We must account for the delay
8004 // between now and the next time the audioflinger thread for this output
8005 // will process a buffer (which corresponds to one buffer size,
8006 // usually 1/2 or 1/4 of the latency).
8007 if (muteWaitMs < desc->latency() * 2) {
8008 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07008009 }
8010 }
8011 }
8012 }
8013 }
8014 }
8015
Eric Laurent99401132014-05-07 19:48:15 -07008016 // temporary mute output if device selection changes to avoid volume bursts due to
8017 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01008018 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07008019 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008020
Eric Laurentdc462862016-07-19 12:29:53 -07008021 if (muteWaitMs < tempMuteWaitMs) {
8022 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07008023 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008024
8025 // If recommended duration is defined, replace temporary mute duration to avoid
8026 // truncated notifications at beginning, which depends on duration of changing path in HAL.
8027 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
8028 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
8029 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
8030 tempRecommendedMuteDuration : outputDesc->latency() * 4;
8031
François Gaffieaaac0fd2018-11-22 17:56:39 +01008032 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
8033 // make sure that we do not start the temporary mute period too early in case of
8034 // delayed device change
Vlad Popa1e865e62024-08-15 19:11:42 -07008035 setVolumeSourceMutedInternally(activeVs, true, outputDesc, delayMs);
8036 setVolumeSourceMutedInternally(activeVs, false, outputDesc,
8037 delayMs + tempMuteDurationMs,
8038 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07008039 }
8040 }
8041
Eric Laurente552edb2014-03-10 17:42:56 -07008042 // wait for the PCM output buffers to empty before proceeding with the rest of the command
8043 if (muteWaitMs > delayMs) {
8044 muteWaitMs -= delayMs;
8045 usleep(muteWaitMs * 1000);
8046 return muteWaitMs;
8047 }
8048 return 0;
8049}
8050
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308051uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
8052 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01008053 const DeviceVector &devices,
8054 bool force,
8055 int delayMs,
8056 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008057 bool requiresMuteCheck, bool requiresVolumeCheck,
8058 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07008059{
jiabin3ff8d7d2022-12-13 06:27:44 +00008060 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308061 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
8062 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
8063 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008064 uint32_t muteWaitMs;
8065
8066 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308067 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008068 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308069 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008070 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07008071 return muteWaitMs;
8072 }
Eric Laurente552edb2014-03-10 17:42:56 -07008073
8074 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01008075 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008076 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02008077 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008078
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308079 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
8080 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01008081
8082 if (!filteredDevices.isEmpty()) {
8083 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008084 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008085
8086 // if the outputs are not materially active, there is no need to mute.
8087 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01008088 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008089 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308090 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
8091 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008092 muteWaitMs = 0;
8093 }
Eric Laurente552edb2014-03-10 17:42:56 -07008094
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008095 bool outputRouted = outputDesc->isRouted();
8096
Eric Laurent79ea9582020-06-11 18:49:24 -07008097 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8098 // output profile or if new device is not supported AND previous device(s) is(are) still
8099 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02008100 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308101 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8102 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07008103 // restore previous device after evaluating strategy mute state
8104 outputDesc->setDevices(prevDevices);
8105 return muteWaitMs;
8106 }
8107
Eric Laurente552edb2014-03-10 17:42:56 -07008108 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008109 // the requested device is AUDIO_DEVICE_NONE
8110 // OR the requested device is the same as current device
8111 // AND force is not specified
8112 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008113 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008114 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308115 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8116 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8117 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008118 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308119 ALOGV("%s %s setting same device on routed output, force apply volumes",
8120 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008121 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8122 }
Eric Laurente552edb2014-03-10 17:42:56 -07008123 return muteWaitMs;
8124 }
8125
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308126 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8127 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008128
Eric Laurente552edb2014-03-10 17:42:56 -07008129 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008130 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008131 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008132 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008133 PatchBuilder patchBuilder;
8134 patchBuilder.addSource(outputDesc);
8135 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8136 for (const auto &filteredDevice : filteredDevices) {
8137 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008138 }
8139
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008140 // Add half reported latency to delayMs when muteWaitMs is null in order
8141 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008142 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8143 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8144 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008145 }
Eric Laurente552edb2014-03-10 17:42:56 -07008146
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008147 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8148 if (!skipMuteDelay) {
8149 // update stream volumes according to new device
8150 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8151 }
Eric Laurente552edb2014-03-10 17:42:56 -07008152
8153 return muteWaitMs;
8154}
8155
Eric Laurentc75307b2015-03-17 15:29:32 -07008156status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008157 int delayMs,
8158 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008159{
Eric Laurent6a94d692014-05-20 11:18:06 -07008160 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008161 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8162 return INVALID_OPERATION;
8163 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008164 if (patchHandle) {
8165 index = mAudioPatches.indexOfKey(*patchHandle);
8166 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008167 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008168 }
8169 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008170 return INVALID_OPERATION;
8171 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008172 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008173 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008174 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008175 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008176 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008177 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008178 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008179 return status;
8180}
8181
8182status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008183 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008184 bool force,
8185 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008186{
8187 status_t status = NO_ERROR;
8188
Eric Laurent1f2f2232014-06-02 12:01:23 -07008189 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008190 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8191 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008192
François Gaffie11d30102018-11-02 16:09:09 +01008193 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008194 PatchBuilder patchBuilder;
8195 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008196 // AUDIO_SOURCE_HOTWORD is for internal use only:
8197 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008198 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8199 auto result = usecase;
8200 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8201 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8202 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008203 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008204 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008205 if (audio_is_remote_submix_device(device->type())) {
8206 // remote submix HAL does not support audio conversion, need source device
8207 // audio config to match the sink input descriptor audio config, otherwise AIDL
8208 // HAL patching will fail
8209 audio_port_config srcDevicePortConfig = {};
8210 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8211 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8212 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8213 srcDevicePortConfig.format = inputDesc->getFormat();
8214 patchBuilder.addSource(srcDevicePortConfig);
8215 } else {
8216 patchBuilder.addSource(device);
8217 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008218 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008219 }
8220 }
8221 return status;
8222}
8223
Eric Laurent6a94d692014-05-20 11:18:06 -07008224status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8225 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008226{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008227 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008228 ssize_t index;
8229 if (patchHandle) {
8230 index = mAudioPatches.indexOfKey(*patchHandle);
8231 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008232 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008233 }
8234 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008235 return INVALID_OPERATION;
8236 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008237 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008238 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008239 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008240 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008241 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008242 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008243 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008244 return status;
8245}
8246
François Gaffie11d30102018-11-02 16:09:09 +01008247sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008248 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008249 audio_format_t& format,
8250 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008251 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008252{
8253 // Choose an input profile based on the requested capture parameters: select the first available
8254 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008255 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008256
Atneya Nair0f0a8032022-12-12 16:20:12 -08008257 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8258 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8259 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8260
8261 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008262
jiabin2fd710d2022-05-02 23:20:22 +00008263 for (;;) {
jiabin91beb492024-10-16 21:53:36 +00008264 sp<IOProfile> inexact = nullptr;
jiabin5e02d2b2024-09-23 19:26:19 +00008265 uint32_t inexactSamplingRate = 0;
8266 audio_format_t inexactFormat = AUDIO_FORMAT_INVALID;
8267 audio_channel_mask_t inexactChannelMask = AUDIO_CHANNEL_INVALID;
jiabin2fd710d2022-05-02 23:20:22 +00008268 uint32_t updatedSamplingRate = 0;
8269 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8270 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8271 for (const auto& hwModule : mHwModules) {
8272 for (const auto& profile : hwModule->getInputProfiles()) {
8273 // profile->log();
8274 //updatedFormat = format;
jiabin91beb492024-10-16 21:53:36 +00008275 auto compatibleScore = profile->getCompatibilityScore(
jiabin66acc432024-02-06 00:57:36 +00008276 DeviceVector(device),
8277 samplingRate,
8278 &updatedSamplingRate,
8279 format,
8280 &updatedFormat,
8281 channelMask,
8282 &updatedChannelMask,
8283 // FIXME ugly cast
jiabin91beb492024-10-16 21:53:36 +00008284 (audio_output_flags_t) flags);
8285 if (compatibleScore == IOProfile::EXACT_MATCH) {
jiabin66acc432024-02-06 00:57:36 +00008286 samplingRate = updatedSamplingRate;
8287 format = updatedFormat;
8288 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008289 return profile;
jiabin91beb492024-10-16 21:53:36 +00008290 } else if ((flags != AUDIO_INPUT_FLAG_NONE
8291 && compatibleScore == IOProfile::PARTIAL_MATCH_WITH_FLAG)
8292 || (inexact == nullptr && compatibleScore != IOProfile::NO_MATCH)) {
8293 inexact = profile;
jiabin5e02d2b2024-09-23 19:26:19 +00008294 inexactSamplingRate = updatedSamplingRate;
8295 inexactFormat = updatedFormat;
8296 inexactChannelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008297 }
8298 }
8299 }
8300
jiabin91beb492024-10-16 21:53:36 +00008301 if (inexact != nullptr) {
jiabin5e02d2b2024-09-23 19:26:19 +00008302 samplingRate = inexactSamplingRate;
8303 format = inexactFormat;
8304 channelMask = inexactChannelMask;
jiabin91beb492024-10-16 21:53:36 +00008305 return inexact;
jiabin2fd710d2022-05-02 23:20:22 +00008306 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8307 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8308 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8309 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8310 flags = AUDIO_INPUT_FLAG_NONE;
8311 } else { // fail
8312 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8313 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8314 samplingRate, format, channelMask, oriFlags);
8315 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008316 }
8317 }
jiabin2fd710d2022-05-02 23:20:22 +00008318
8319 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008320}
8321
Vlad Popa87e0e582024-05-20 18:49:20 -07008322float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8323 VolumeSource volumeSource,
8324 int index,
8325 const DeviceTypeSet &deviceTypes)
8326{
8327 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8328 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8329 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8330
8331 if (com_android_media_audio_abs_volume_index_fix()) {
Vlad Popa08502d82024-10-22 20:17:47 -07008332 const auto it = mAbsoluteVolumeDrivingStreams.find(volumeDevice);
8333 if (it != mAbsoluteVolumeDrivingStreams.end()) {
8334 audio_attributes_t attributesToDriveAbs = it->second;
Vlad Popa87e0e582024-05-20 18:49:20 -07008335 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8336 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8337 ALOGD("%s: no group matching with %s", __FUNCTION__,
8338 toString(attributesToDriveAbs).c_str());
8339 return volumeDb;
8340 }
8341
8342 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8343 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8344 if (vsToDriveAbs == volumeSource) {
8345 // attenuation is applied by the abs volume controller
Eric Laurent64e868f2024-06-28 16:42:49 +00008346 return (index != 0) ? volumeDbMax : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008347 } else {
8348 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8349 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8350 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8351 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8352 curvesAbs.getVolumeIndexMax());
8353 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8354 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8355 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8356 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8357 return newVolumeDb;
8358 }
8359 }
8360 return volumeDb;
8361 } else {
8362 return volumeDb;
8363 }
8364}
8365
François Gaffieaaac0fd2018-11-22 17:56:39 +01008366float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8367 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008368 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008369 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008370 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008371 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008372{
Vlad Popa9d482762024-06-21 16:40:23 -07008373 float volumeDb;
8374 if (adjustAttenuation) {
8375 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8376 } else {
8377 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8378 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008379 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8380 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8381
8382 if (!computeInternalInteraction) {
8383 return volumeDb;
8384 }
8385
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008386 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8387 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8388 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8389 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008390 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8391 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8392 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8393 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8394 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008395 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008396 mOutputs.isActive(ringVolumeSrc, 0)) {
8397 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008398 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008399 adjustAttenuation,
8400 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008401 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008402 }
8403
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008404 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008405 if ((volumeSource != callVolumeSrc && (isInCall() ||
8406 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008407 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008408 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8409 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008410 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8411 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8412 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008413 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008414 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008415 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008416 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008417 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008418 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008419 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008420 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8421 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8422 // programmatically muted.
8423 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8424 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8425 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008426 bool exemptFromCapping =
8427 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8428 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008429 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8430 volumeSource, volumeDb);
8431 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008432 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8433 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8434 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008435 }
8436 }
Eric Laurente552edb2014-03-10 17:42:56 -07008437 // if a headset is connected, apply the following rules to ring tones and notifications
8438 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008439 // - always attenuate notifications volume by 6dB
8440 // - attenuate ring tones volume by 6dB unless music is not playing and
8441 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008442 // - if music is playing, always limit the volume to current music volume,
8443 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008444 if (!Intersection(deviceTypes,
8445 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8446 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008447 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8448 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008449 ((volumeSource == alarmVolumeSrc ||
8450 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008451 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8452 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8453 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008454 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8455 curves.canBeMuted()) {
8456
Eric Laurente552edb2014-03-10 17:42:56 -07008457 // when the phone is ringing we must consider that music could have been paused just before
8458 // by the music application and behave as if music was active if the last music track was
8459 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008460 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8461 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008462 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008463 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008464 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8465 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008466 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008467 float musicVolDb = computeVolume(musicCurves,
8468 musicVolumeSrc,
8469 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008470 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008471 adjustAttenuation,
8472 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008473 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8474 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8475 if (volumeDb > minVolDb) {
8476 volumeDb = minVolDb;
8477 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008478 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008479 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8480 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008481 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8482 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8483 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8484 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008485 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008486 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008487 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8488 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008489 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8490 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008491 }
8492 }
jiabin9a3361e2019-10-01 09:38:30 -07008493 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008494 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008495 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008496 }
8497 }
8498
François Gaffie43c73442018-11-08 08:21:55 +01008499 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008500}
8501
Eric Laurent3839bc02018-07-10 18:33:34 -07008502int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008503 VolumeSource fromVolumeSource,
8504 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008505{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008506 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008507 return srcIndex;
8508 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008509 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8510 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008511 float minSrc = (float)srcCurves.getVolumeIndexMin();
8512 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8513 float minDst = (float)dstCurves.getVolumeIndexMin();
8514 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008515
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008516 // preserve mute request or correct range
8517 if (srcIndex < minSrc) {
8518 if (srcIndex == 0) {
8519 return 0;
8520 }
8521 srcIndex = minSrc;
8522 } else if (srcIndex > maxSrc) {
8523 srcIndex = maxSrc;
8524 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008525 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8526}
8527
François Gaffieaaac0fd2018-11-22 17:56:39 +01008528status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8529 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008530 int index,
8531 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008532 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008533 int delayMs,
8534 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008535{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008536 // APM is single threaded, and single instance.
8537 static std::set<IVolumeCurves*> invalidCurvesReported;
8538
François Gaffieaaac0fd2018-11-22 17:56:39 +01008539 // do not change actual attributes volume if the attributes is muted
Vlad Popa1e865e62024-08-15 19:11:42 -07008540 if (!com_android_media_audio_ring_my_car() && outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008541 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8542 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008543 return NO_ERROR;
8544 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008545
Eric Laurentae6e88c2024-01-10 14:42:57 +01008546 bool isVoiceVolSrc;
8547 bool isBtScoVolSrc;
8548 if (!isVolumeConsistentForCalls(
8549 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008550 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008551 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008552 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008553 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008554
jiabin9a3361e2019-10-01 09:38:30 -07008555 if (deviceTypes.empty()) {
8556 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008557 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008558 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008559 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008560 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008561
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008562 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008563 if (!invalidCurvesReported.count(&curves)) {
8564 invalidCurvesReported.insert(&curves);
8565 String8 dump;
8566 curves.dump(&dump);
8567 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8568 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008569 return BAD_VALUE;
8570 }
8571
jiabin9a3361e2019-10-01 09:38:30 -07008572 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
Eric Laurentc32e6692024-10-04 14:32:28 +00008573 const VolumeSource dtmfVolSrc = toVolumeSource(AUDIO_STREAM_DTMF, false);
jiabin9a3361e2019-10-01 09:38:30 -07008574 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008575 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurentc32e6692024-10-04 14:32:28 +00008576 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc
8577 || (isInCall() && (dtmfVolSrc == volumeSource))) &&
chenxin2095559032024-06-15 13:59:29 +08008578 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8579 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008580 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008581 }
Vlad Popa1e865e62024-08-15 19:11:42 -07008582
8583 bool muted;
8584 if (!com_android_media_audio_ring_my_car()) {
8585 muted = (index == 0) && (volumeDb != 0.0f);
8586 } else {
8587 muted = curves.isMuted();
8588 }
Eric Laurent31a428a2023-08-11 12:16:28 +02008589 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8590 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008591
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008592 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008593 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8594 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8595 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008596 }
Eric Laurente552edb2014-03-10 17:42:56 -07008597 return NO_ERROR;
8598}
8599
Eric Laurentae6e88c2024-01-10 14:42:57 +01008600void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008601 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008602 float voiceVolume;
Vlad Popa1e865e62024-08-15 19:11:42 -07008603
8604 if (com_android_media_audio_ring_my_car() && curves.isMuted()) {
8605 index = 0;
8606 }
8607
chenxin2095559032024-06-15 13:59:29 +08008608 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008609 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008610 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008611 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8612 } else {
8613 voiceVolume = index == 0 ? 0.0 : 1.0;
8614 }
8615 if (voiceVolume != mLastVoiceVolume) {
8616 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8617 mLastVoiceVolume = voiceVolume;
8618 }
8619}
8620
8621bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8622 const DeviceTypeSet& deviceTypes,
8623 bool& isVoiceVolSrc,
8624 bool& isBtScoVolSrc,
8625 const char* caller) {
8626 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008627 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8628
Eric Laurentae6e88c2024-01-10 14:42:57 +01008629 const bool isScoRequested = isScoRequestedForComm();
8630 const bool isHAUsed = isHearingAidUsedForComm();
8631
Vlad Popa695b76b2024-06-14 16:49:25 -07008632 if (com_android_media_audio_replace_stream_bt_sco()) {
8633 ALOGV("%s stream bt sco is replaced, no volume consistency check for calls", __func__);
8634 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8635 (isScoRequested || isHAUsed);
8636 return true;
8637 }
8638
8639 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008640 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8641
8642 if ((callVolSrc != btScoVolSrc) &&
8643 ((isVoiceVolSrc && isScoRequested) ||
8644 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8645 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8646 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8647 volumeSource, isScoRequested ? " " : " not ");
8648 return false;
8649 }
8650 return true;
8651}
8652
Eric Laurentc75307b2015-03-17 15:29:32 -07008653void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008654 const DeviceTypeSet& deviceTypes,
8655 int delayMs,
8656 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008657{
jiabincd510522020-01-22 09:40:55 -08008658 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008659 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8660 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
Vlad Popa1e865e62024-08-15 19:11:42 -07008661 checkAndSetVolume(curves, toVolumeSource(volumeGroup), curves.getVolumeIndex(deviceTypes),
jiabin9a3361e2019-10-01 09:38:30 -07008662 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008663 }
8664}
8665
François Gaffiec005e562018-11-06 15:04:49 +01008666void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
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{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008672 std::vector<VolumeSource> sourcesToMute;
8673 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8674 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8675 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008676 VolumeSource source = toVolumeSource(attributes, false);
8677 if ((source != VOLUME_SOURCE_NONE) &&
8678 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8679 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008680 sourcesToMute.push_back(source);
8681 }
Eric Laurente552edb2014-03-10 17:42:56 -07008682 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008683 for (auto source : sourcesToMute) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008684 setVolumeSourceMutedInternally(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008685 }
8686
Eric Laurente552edb2014-03-10 17:42:56 -07008687}
8688
Vlad Popa1e865e62024-08-15 19:11:42 -07008689void AudioPolicyManager::setVolumeSourceMutedInternally(VolumeSource volumeSource,
8690 bool on,
8691 const sp<AudioOutputDescriptor>& outputDesc,
8692 int delayMs,
8693 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008694{
jiabin9a3361e2019-10-01 09:38:30 -07008695 if (deviceTypes.empty()) {
8696 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008697 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008698 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008699 if (on) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008700 if (!outputDesc->isMutedInternally(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008701 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008702 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008703 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8704 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008705 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008706 }
8707 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008708 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8709 // ignored
8710 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008711 } else {
Vlad Popa1e865e62024-08-15 19:11:42 -07008712 if (!outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008713 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008714 return;
8715 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008716 if (outputDesc->decMuteCount(volumeSource) == 0) {
8717 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008718 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008719 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008720 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008721 delayMs);
8722 }
8723 }
8724}
8725
François Gaffie53615e22015-03-19 09:24:12 +01008726bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8727{
François Gaffiec005e562018-11-06 15:04:49 +01008728 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008729 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8730 return true;
8731 }
8732
8733 // has known usage?
8734 switch (paa->usage) {
8735 case AUDIO_USAGE_UNKNOWN:
8736 case AUDIO_USAGE_MEDIA:
8737 case AUDIO_USAGE_VOICE_COMMUNICATION:
8738 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8739 case AUDIO_USAGE_ALARM:
8740 case AUDIO_USAGE_NOTIFICATION:
8741 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8742 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8743 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8744 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8745 case AUDIO_USAGE_NOTIFICATION_EVENT:
8746 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8747 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8748 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8749 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008750 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008751 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008752 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008753 case AUDIO_USAGE_EMERGENCY:
8754 case AUDIO_USAGE_SAFETY:
8755 case AUDIO_USAGE_VEHICLE_STATUS:
8756 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008757 break;
8758 default:
8759 return false;
8760 }
8761 return true;
8762}
8763
François Gaffie2110e042015-03-24 08:41:51 +01008764audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8765{
8766 return mEngine->getForceUse(usage);
8767}
8768
Eric Laurent96d1dda2022-03-14 17:14:19 +01008769bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008770 return isStateInCall(mEngine->getPhoneState());
8771}
8772
Eric Laurent96d1dda2022-03-14 17:14:19 +01008773bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008774 return is_state_in_call(state);
8775}
8776
Eric Laurentf9cccec2022-11-16 19:12:00 +01008777bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008778 audio_mode_t mode = mEngine->getPhoneState();
8779 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008780 || (mode == AUDIO_MODE_CALL_SCREEN)
8781 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008782}
8783
Eric Laurentf9cccec2022-11-16 19:12:00 +01008784bool AudioPolicyManager::isInCallOrScreening() const {
8785 audio_mode_t mode = mEngine->getPhoneState();
8786 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8787}
8788
Eric Laurentd60560a2015-04-10 11:31:20 -07008789void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8790{
8791 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008792 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008793 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008794 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008795 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008796 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008797 }
8798 }
8799
8800 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8801 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8802 bool release = false;
8803 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8804 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8805 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8806 source->ext.device.type == deviceDesc->type()) {
8807 release = true;
8808 }
8809 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008810 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008811 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8812 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8813 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008814 sink->ext.device.type == deviceDesc->type() &&
8815 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8816 || strncmp(sink->ext.device.address, address,
8817 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008818 release = true;
8819 }
8820 }
8821 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008822 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8823 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008824 }
8825 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008826
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008827 mInputs.clearSessionRoutesForDevice(deviceDesc);
8828
Francois Gaffie716e1432019-01-14 16:58:59 +01008829 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008830}
8831
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008832void AudioPolicyManager::modifySurroundFormats(
8833 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008834 std::unordered_set<audio_format_t> enforcedSurround(
8835 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008836 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008837 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008838 allSurround.insert(pair.first);
8839 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8840 }
Phil Burk09bc4612016-02-24 15:58:15 -08008841
8842 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8843 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008844 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008845 // This is the resulting set of formats depending on the surround mode:
8846 // 'all surround' = allSurround
8847 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8848 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8849 // 'manual surround' = mManualSurroundFormats
8850 // AUTO: formats v 'enforced surround'
8851 // ALWAYS: formats v 'all surround' v 'enforced surround'
8852 // NEVER: formats ^ 'non-surround'
8853 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008854
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008855 std::unordered_set<audio_format_t> formatSet;
8856 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8857 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008858 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008859 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008860 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008861 formatSet.insert(*formatIter);
8862 }
8863 }
8864 } else {
8865 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8866 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008867 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008868
jiabin81772902018-04-02 17:52:27 -07008869 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008870 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008871 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8872 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8873 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008874 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008875 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8876 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8877 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008878 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008879 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008880 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008881 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008882 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008883 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008884}
8885
jiabin06e4bab2019-07-29 10:13:34 -07008886void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8887 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008888 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8889 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8890
8891 // If NEVER, then remove support for channelMasks > stereo.
8892 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008893 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8894 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008895 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008896 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008897 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008898 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008899 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008900 }
8901 }
jiabin81772902018-04-02 17:52:27 -07008902 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8903 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8904 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008905 bool supports5dot1 = false;
8906 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008907 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008908 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8909 supports5dot1 = true;
8910 break;
8911 }
8912 }
8913 // If not then add 5.1 support.
8914 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008915 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008916 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008917 }
Phil Burk09bc4612016-02-24 15:58:15 -08008918 }
8919}
8920
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008921void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008922 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008923 const sp<IOProfile>& profile) {
8924 if (!profile->hasDynamicAudioProfile()) {
8925 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008926 }
François Gaffie112b0af2015-11-19 16:13:25 +01008927
jiabin12537fc2023-10-12 17:56:08 +00008928 audio_port_v7 devicePort;
8929 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008930
jiabin12537fc2023-10-12 17:56:08 +00008931 audio_port_v7 mixPort;
8932 profile->toAudioPort(&mixPort);
8933 mixPort.ext.mix.handle = ioHandle;
8934
8935 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8936 if (status != NO_ERROR) {
8937 ALOGE("%s failed to query the attributes of the mix port", __func__);
8938 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008939 }
jiabin12537fc2023-10-12 17:56:08 +00008940
8941 std::set<audio_format_t> supportedFormats;
8942 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8943 supportedFormats.insert(mixPort.audio_profiles[i].format);
8944 }
8945 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8946 mReportedFormatsMap[devDesc] = formats;
8947
8948 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008949 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8950 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008951 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8952 modifySurroundFormats(devDesc, &formats);
8953 size_t modifiedNumProfiles = 0;
8954 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8955 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8956 formats.end()) {
8957 // Skip the format that is not present after modifying surround formats.
8958 continue;
8959 }
8960 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8961 sizeof(struct audio_profile));
8962 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8963 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8964 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8965 modifySurroundChannelMasks(&channels);
8966 std::copy(channels.begin(), channels.end(),
8967 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8968 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8969 }
8970 mixPort.num_audio_profiles = modifiedNumProfiles;
8971 }
8972 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008973}
Eric Laurentd60560a2015-04-10 11:31:20 -07008974
Mikhail Naganovdc769682018-05-04 15:34:08 -07008975status_t AudioPolicyManager::installPatch(const char *caller,
8976 audio_patch_handle_t *patchHandle,
8977 AudioIODescriptorInterface *ioDescriptor,
8978 const struct audio_patch *patch,
8979 int delayMs)
8980{
8981 ssize_t index = mAudioPatches.indexOfKey(
8982 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8983 *patchHandle : ioDescriptor->getPatchHandle());
8984 sp<AudioPatch> patchDesc;
8985 status_t status = installPatch(
8986 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8987 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008988 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008989 }
8990 return status;
8991}
8992
8993status_t AudioPolicyManager::installPatch(const char *caller,
8994 ssize_t index,
8995 audio_patch_handle_t *patchHandle,
8996 const struct audio_patch *patch,
8997 int delayMs,
8998 uid_t uid,
8999 sp<AudioPatch> *patchDescPtr)
9000{
9001 sp<AudioPatch> patchDesc;
9002 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
9003 if (index >= 0) {
9004 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01009005 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009006 }
9007
9008 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
9009 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
9010 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
9011 if (status == NO_ERROR) {
9012 if (index < 0) {
9013 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01009014 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009015 } else {
9016 patchDesc->mPatch = *patch;
9017 }
François Gaffieafd4cea2019-11-18 15:50:22 +01009018 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009019 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01009020 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009021 }
9022 nextAudioPortGeneration();
9023 mpClientInterface->onAudioPatchListUpdate();
9024 }
9025 if (patchDescPtr) *patchDescPtr = patchDesc;
9026 return status;
9027}
9028
jiabinbce0c1d2020-10-05 11:20:18 -07009029bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
9030{
9031 const TrackClientVector activeClients = output->getActiveClients();
9032 if (activeClients.empty()) {
9033 return true;
9034 }
9035 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
9036 if (index < 0) {
9037 ALOGE("%s, no audio patch found while there are active clients on output %d",
9038 __func__, output->getId());
9039 return false;
9040 }
9041 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
9042 DeviceVector routedDevices;
9043 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
9044 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
9045 patchDesc->mPatch.sinks[i].id);
9046 if (device == nullptr) {
9047 ALOGE("%s, no audio device found with id(%d)",
9048 __func__, patchDesc->mPatch.sinks[i].id);
9049 return false;
9050 }
9051 routedDevices.add(device);
9052 }
9053 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08009054 if (client->isInvalid()) {
9055 // No need to take care about invalidated clients.
9056 continue;
9057 }
jiabinbce0c1d2020-10-05 11:20:18 -07009058 sp<DeviceDescriptor> preferredDevice =
9059 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
9060 if (mEngine->getOutputDevicesForAttributes(
9061 client->attributes(), preferredDevice, false) == routedDevices) {
9062 return false;
9063 }
9064 }
9065 return true;
9066}
9067
9068sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01009069 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00009070 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
9071 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07009072{
9073 for (const auto& device : devices) {
9074 // TODO: This should be checking if the profile supports the device combo.
9075 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00009076 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
9077 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07009078 return nullptr;
9079 }
9080 }
9081 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
9082 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07009083 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00009084 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009085 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009086 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00009087 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07009088 return nullptr;
9089 }
jiabin14b50cc2023-12-13 19:01:52 +00009090 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
9091 auto portConfig = desc->getConfig();
9092 for (const auto& device : devices) {
9093 device->setPreferredConfig(&portConfig);
9094 }
9095 }
jiabinbce0c1d2020-10-05 11:20:18 -07009096
9097 // Here is where the out_set_parameters() for card & device gets called
9098 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
9099 const audio_devices_t deviceType = device->type();
9100 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00009101 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07009102 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
9103 mpClientInterface->setParameters(output, String8(param));
9104 free(param);
9105 }
jiabin12537fc2023-10-12 17:56:08 +00009106 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07009107 if (!profile->hasValidAudioProfile()) {
9108 ALOGW("%s() missing param", __func__);
9109 desc->close();
9110 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00009111 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
9112 // Reopen the output with the best audio profile picked by APM when the profile supports
9113 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07009114 desc->close();
9115 output = AUDIO_IO_HANDLE_NONE;
9116 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9117 profile->pickAudioProfile(
9118 config.sample_rate, config.channel_mask, config.format);
9119 config.offload_info.sample_rate = config.sample_rate;
9120 config.offload_info.channel_mask = config.channel_mask;
9121 config.offload_info.format = config.format;
9122
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009123 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07009124 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009125 if (status != NO_ERROR) {
9126 return nullptr;
9127 }
9128 }
9129
9130 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07009131 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
9132 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
9133 hwModule->getHalVersionMajor() >= 3) {
9134 setOutputDevices(__func__, desc, devices, true, 0, NULL);
9135 }
baek.kim -61c20122022-07-27 10:05:32 +00009136 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9137 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9138
jiabinbce0c1d2020-10-05 11:20:18 -07009139 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9140 sp<AudioPolicyMix> policyMix;
9141 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9142 policyMix->setOutput(desc);
9143 desc->mPolicyMix = policyMix;
9144 } else {
9145 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009146 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009147 }
9148
baek.kim -61c20122022-07-27 10:05:32 +00009149 } else if (hasPrimaryOutput() && speaker != nullptr
9150 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009151 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9152 // no duplicated output for:
9153 // - direct outputs
9154 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009155 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009156 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9157
9158 //TODO: configure audio effect output stage here
9159
9160 // open a duplicating output thread for the new output and the primary output
9161 sp<SwAudioOutputDescriptor> dupOutputDesc =
9162 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9163 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9164 if (status == NO_ERROR) {
9165 // add duplicated output descriptor
9166 addOutput(duplicatedOutput, dupOutputDesc);
9167 } else {
9168 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9169 mPrimaryOutput->mIoHandle, output);
9170 desc->close();
9171 removeOutput(output);
9172 nextAudioPortGeneration();
9173 return nullptr;
9174 }
9175 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009176 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9177 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9178 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009179 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009180 }
jiabinbce0c1d2020-10-05 11:20:18 -07009181 return desc;
9182}
9183
jiabinf1c73972022-04-14 16:28:52 -07009184status_t AudioPolicyManager::getDevicesForAttributes(
9185 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
wenyu zhang8558a332024-09-09 15:12:48 +00009186 // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9187 // over any usage or content type also present in attr.
9188 if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9189 attr.source != AUDIO_SOURCE_INVALID) {
9190 return getInputDevicesForAttributes(attr, devices);
9191 }
9192
jiabinf1c73972022-04-14 16:28:52 -07009193 // Devices are determined in the following precedence:
9194 //
9195 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9196 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9197 //
9198 // If no such dynamic policy then
9199 // 2) Devices containing an active client using setPreferredDevice
9200 // with same strategy as the attributes.
9201 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9202 //
9203 // If no corresponding active client with setPreferredDevice then
9204 // 3) Devices associated with the strategy determined by the attributes
9205 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9206 //
9207 // See related getOutputForAttrInt().
9208
9209 // check dynamic policies but only for primary descriptors (secondary not used for audible
9210 // audio routing, only used for duplication for playback capture)
9211 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009212 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009213 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009214 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9215 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9216 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009217 if (status != OK) {
9218 return status;
9219 }
9220
9221 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9222 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9223 // as they are unaffected by device/stream volume
9224 // (per SwAudioOutputDescriptor::isFixedVolume()).
9225 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9226 ) {
9227 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9228 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9229 devices.add(deviceDesc);
9230 } else {
9231 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9232 // which selects setPreferredDevice if active. This means forVolume call
9233 // will take an active setPreferredDevice, if such exists.
9234
9235 devices = mEngine->getOutputDevicesForAttributes(
9236 attr, nullptr /* preferredDevice */, false /* fromCache */);
9237 }
9238
9239 if (forVolume) {
9240 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9241 // for single volume control in AudioService (such relationship should exist if
9242 // SPEAKER_SAFE is present).
9243 //
9244 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9245 DeviceVector speakerSafeDevices =
9246 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9247 if (!speakerSafeDevices.isEmpty()) {
9248 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9249 devices.remove(speakerSafeDevices);
9250 }
9251 }
9252
9253 return NO_ERROR;
9254}
9255
wenyu zhang8558a332024-09-09 15:12:48 +00009256status_t AudioPolicyManager::getInputDevicesForAttributes(
9257 const audio_attributes_t &attr, DeviceVector &devices) {
9258 devices = DeviceVector(
9259 mEngine->getInputDeviceForAttributes(attr, 0 /*uid unknown here*/,
9260 AUDIO_SESSION_NONE,
9261 nullptr /* mix */));
9262 return NO_ERROR;
9263}
9264
jiabinf1c73972022-04-14 16:28:52 -07009265status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9266 AudioProfileVector& audioProfiles,
9267 uint32_t flags,
9268 bool isInput) {
9269 for (const auto& hwModule : mHwModules) {
9270 // the MSD module checks for different conditions
9271 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9272 continue;
9273 }
9274 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9275 : hwModule->getOutputProfiles();
9276 for (const auto& profile : ioProfiles) {
9277 if (!profile->areAllDevicesSupported(devices) ||
jiabin91beb492024-10-16 21:53:36 +00009278 !profile->isCompatibleProfileForFlags(flags)) {
jiabinf1c73972022-04-14 16:28:52 -07009279 continue;
9280 }
9281 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9282 }
9283 }
9284
9285 if (!isInput) {
9286 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9287 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9288 if (msdModule != nullptr) {
9289 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9290 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9291 for (const auto &profile: msdModule->getOutputProfiles()) {
9292 if (!profile->asAudioPort()->isDirectOutput()) {
9293 continue;
9294 }
9295 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9296 }
9297 } else {
9298 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9299 }
9300 }
9301 }
9302
9303 return NO_ERROR;
9304}
9305
jiabin3ff8d7d2022-12-13 06:27:44 +00009306sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9307 const audio_config_t *config,
9308 audio_output_flags_t flags,
9309 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009310 closeOutput(outputDesc->mIoHandle);
9311 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9312 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9313 if (preferredOutput == nullptr) {
9314 ALOGE("%s failed to reopen output device=%d, caller=%s",
9315 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009316 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009317 return preferredOutput;
9318}
9319
9320void AudioPolicyManager::reopenOutputsWithDevices(
9321 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9322 for (const auto& [output, devices] : outputsToReopen) {
9323 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9324 closeOutput(output);
9325 openOutputWithProfileAndDevice(desc->mProfile, devices);
9326 }
jiabina84c3d32022-12-02 18:59:55 +00009327}
9328
jiabinc44b3462022-12-08 12:52:31 -08009329PortHandleVector AudioPolicyManager::getClientsForStream(
9330 audio_stream_type_t streamType) const {
9331 PortHandleVector clients;
9332 for (size_t i = 0; i < mOutputs.size(); ++i) {
9333 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9334 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9335 }
9336 return clients;
9337}
9338
9339void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9340 PortHandleVector clients;
9341 for (auto stream : streams) {
9342 PortHandleVector clientsForStream = getClientsForStream(stream);
9343 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9344 }
9345 mpClientInterface->invalidateTracks(clients);
9346}
9347
jiabin220eea12024-05-17 17:55:20 +00009348void AudioPolicyManager::updateClientsInternalMute(
9349 const sp<android::SwAudioOutputDescriptor> &desc) {
9350 if (!desc->isBitPerfect() ||
9351 !com::android::media::audioserver::
9352 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9353 // This is only used for bit perfect output now.
9354 return;
9355 }
9356 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9357 bool bitPerfectClientInternalMute = false;
9358 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9359 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9360 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9361 bitPerfectClient = client;
9362 continue;
9363 }
9364 bool muted = false;
9365 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9366 // System sound is muted.
9367 muted = true;
9368 } else {
9369 bitPerfectClientInternalMute = true;
9370 }
9371 if (client->setInternalMute(muted)) {
9372 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9373 if (!result.ok()) {
9374 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9375 continue;
9376 }
9377 media::TrackInternalMuteInfo info;
9378 info.portId = result.value();
9379 info.muted = client->getInternalMute();
9380 clientsInternalMute.push_back(std::move(info));
9381 }
9382 }
9383 if (bitPerfectClient != nullptr &&
9384 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9385 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9386 if (result.ok()) {
9387 media::TrackInternalMuteInfo info;
9388 info.portId = result.value();
9389 info.muted = bitPerfectClient->getInternalMute();
9390 clientsInternalMute.push_back(std::move(info));
9391 } else {
9392 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9393 __func__, bitPerfectClient->portId());
9394 }
9395 }
9396 if (!clientsInternalMute.empty()) {
9397 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9398 status != NO_ERROR) {
9399 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9400 }
9401 }
9402}
9403
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00009404status_t AudioPolicyManager::getMmapPolicyInfos(AudioMMapPolicyType policyType,
9405 std::vector<AudioMMapPolicyInfo> *policyInfos) {
9406 if (policyType != AudioMMapPolicyType::DEFAULT &&
9407 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9408 return BAD_VALUE;
9409 }
9410 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9411 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9412 return status;
9413 }
9414 }
9415 *policyInfos = mMmapPolicyInfos[policyType];
9416 return NO_ERROR;
9417}
9418
9419status_t AudioPolicyManager::getMmapPolicyForDevice(
9420 AudioMMapPolicyType policyType, AudioMMapPolicyInfo *policyInfo) {
9421 if (policyType != AudioMMapPolicyType::DEFAULT &&
9422 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9423 return BAD_VALUE;
9424 }
9425 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9426 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9427 return status;
9428 }
9429 }
9430 auto it = mMmapPolicyByDeviceType[policyType].find(policyInfo->device.type);
9431 policyInfo->mmapPolicy = it == mMmapPolicyByDeviceType[policyType].end()
9432 ? AudioMMapPolicy::NEVER : it->second;
9433 return NO_ERROR;
9434}
9435
9436status_t AudioPolicyManager::updateMmapPolicyInfos(AudioMMapPolicyType policyType) {
9437 std::vector<AudioMMapPolicyInfo> policyInfos;
9438 if (status_t status = mpClientInterface->getMmapPolicyInfos(policyType, &policyInfos);
9439 status != NO_ERROR) {
9440 ALOGE("%s, failed, error = %d", __func__, status);
9441 return status;
9442 }
9443 std::map<AudioDeviceDescription, AudioMMapPolicy> mmapPolicyByDeviceType;
9444 if (policyInfos.size() == 1 && policyInfos[0].device == AudioDevice()) {
9445 // When there is only one AudioMMapPolicyInfo instance and the device is a default value,
9446 // it indicates the mmap policy is reported via system property. In that case, use the
9447 // routing information to fill details for how mmap is supported for a particular device.
9448 for (const auto &hwModule: mHwModules) {
9449 for (const auto &profile: hwModule->getInputProfiles()) {
9450 if ((profile->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ)
9451 != AUDIO_INPUT_FLAG_MMAP_NOIRQ) {
9452 continue;
9453 }
9454 for (const auto &device: profile->getSupportedDevices()) {
9455 auto deviceDesc =
9456 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9457 if (deviceDesc.ok()) {
9458 mmapPolicyByDeviceType.emplace(
9459 deviceDesc.value(), policyInfos[0].mmapPolicy);
9460 }
9461 }
9462 }
9463 for (const auto &profile: hwModule->getOutputProfiles()) {
9464 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)
9465 != AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
9466 continue;
9467 }
9468 for (const auto &device: profile->getSupportedDevices()) {
9469 auto deviceDesc =
9470 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9471 if (deviceDesc.ok()) {
9472 mmapPolicyByDeviceType.emplace(
9473 deviceDesc.value(), policyInfos[0].mmapPolicy);
9474 }
9475 }
9476 }
9477 }
9478 } else {
9479 for (const auto &info: policyInfos) {
9480 mmapPolicyByDeviceType[info.device.type] = info.mmapPolicy;
9481 }
9482 }
9483 mMmapPolicyByDeviceType.emplace(policyType, mmapPolicyByDeviceType);
9484 mMmapPolicyInfos.emplace(policyType, policyInfos);
9485 return NO_ERROR;
9486}
9487
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009488} // namespace android