blob: ef5f7a96a5d0473bd8e4318493de53892c831081 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Jiabin Huangaa6e9e32024-10-21 17:19:28 +000043#include <android/media/audio/common/AudioMMapPolicy.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010044#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080045#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010046#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080047#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070048#include <cutils/bitops.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
Shunkai Yao2dcd60c2024-08-27 21:08:53 +000058#include "SpatializerHelper.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010059#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070060
Eric Laurent3b73df72014-03-11 09:06:29 -070061namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070062
Marvin Raminbdefaf02023-11-01 09:10:32 +010063
64namespace audio_flags = android::media::audiopolicy;
65
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010066using android::media::audio::common::AudioDevice;
67using android::media::audio::common::AudioDeviceAddress;
Jiabin Huangaa6e9e32024-10-21 17:19:28 +000068using android::media::audio::common::AudioDeviceDescription;
69using android::media::audio::common::AudioMMapPolicy;
70using android::media::audio::common::AudioMMapPolicyInfo;
71using android::media::audio::common::AudioMMapPolicyType;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010072using android::media::audio::common::AudioPortDeviceExt;
73using android::media::audio::common::AudioPortExt;
Eric Laurentb2fb4102024-06-21 12:25:26 +000074using com::android::media::audioserver::fix_call_audio_patch;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000075using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070076
Eric Laurentdc462862016-07-19 12:29:53 -070077//FIXME: workaround for truncated touch sounds
78// to be removed when the problem is handled by system UI
79#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070080
81// Largest difference in dB on earpiece in call between the voice volume and another
82// media / notification / system volume.
83constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
84
jiabin06e4bab2019-07-29 10:13:34 -070085template <typename T>
86bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
87{
88 if (left.size() != right.size()) {
89 return false;
90 }
91 for (size_t index = 0; index < right.size(); index++) {
92 if (left[index] != right[index]) {
93 return false;
94 }
95 }
96 return true;
97}
98
99template <typename T>
100bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
101{
102 return !(left == right);
103}
104
Eric Laurente552edb2014-03-10 17:42:56 -0700105// ----------------------------------------------------------------------------
106// AudioPolicyInterface implementation
107// ----------------------------------------------------------------------------
108
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100109status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
110 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
111 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800112 nextAudioPortGeneration();
113 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800114}
115
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
117 audio_policy_dev_state_t state,
118 const char* device_address,
119 const char* device_name,
120 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800121 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100122 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
123 status == OK) {
124 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
125 } else {
126 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
127 return status;
128 }
129}
130
Ping Tsai2a5a5242024-08-16 13:39:10 +0800131status_t AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000132 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200133{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000134 audio_port_v7 devicePort;
135 device->toAudioPort(&devicePort);
Ping Tsai2a5a5242024-08-16 13:39:10 +0800136 status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
137 ALOGE_IF(status != OK, "Error %d while setting connected state %d for device %s", status,
138 static_cast<int>(state), device->getDeviceTypeAddr().toString(false).c_str());
139
140 return status;
François Gaffie44481e72016-04-20 07:49:57 +0200141}
142
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100143status_t AudioPolicyManager::setDeviceConnectionStateInt(
144 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
145 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100146 if (port.ext.getTag() != AudioPortExt::device) {
147 return BAD_VALUE;
148 }
149 audio_devices_t device_type;
150 std::string device_address;
151 if (status_t status = aidl2legacy_AudioDevice_audio_device(
152 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
153 status != OK) {
154 return status;
155 };
156 const char* device_name = port.name.c_str();
157 // connect/disconnect only 1 device at a time
158 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
159 return BAD_VALUE;
160
161 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
162 device_type, device_address.c_str(), device_name, encodedFormat,
163 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000164 if (device == nullptr) {
165 return INVALID_OPERATION;
166 }
167 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
168 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
169 }
170 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100171}
172
François Gaffie11d30102018-11-02 16:09:09 +0100173status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800174 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100175 const char* device_address,
176 const char* device_name,
177 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800178 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100179 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
180 status == OK) {
181 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
182 } else {
183 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
184 return status;
185 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700186}
Paul McLeane743a472015-01-28 11:07:31 -0800187
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700188status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
189 audio_policy_dev_state_t state)
190{
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700192 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700193 SortedVector <audio_io_handle_t> outputs;
194
François Gaffie11d30102018-11-02 16:09:09 +0100195 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700196
Eric Laurente552edb2014-03-10 17:42:56 -0700197 // save a copy of the opened output descriptors before any output is opened or closed
198 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
199 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100200
201 bool wasLeUnicastActive = isLeUnicastActive();
202
Eric Laurente552edb2014-03-10 17:42:56 -0700203 switch (state)
204 {
205 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800206 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700207 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100208 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700209 return INVALID_OPERATION;
210 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800211 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700212 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700213
Eric Laurente552edb2014-03-10 17:42:56 -0700214 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200215 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700216 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700217 }
218
François Gaffie44481e72016-04-20 07:49:57 +0200219 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
220 // parameters on newly connected devices (instead of opening the outputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800221 if (broadcastDeviceConnectionState(
222 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
223 mAvailableOutputDevices.remove(device);
224 mHwModules.cleanUpForDevice(device);
225 ALOGE("%s() device %s format %x connection failed", __func__,
226 device->toString().c_str(), device->getEncodedFormat());
227 return INVALID_OPERATION;
228 }
François Gaffie44481e72016-04-20 07:49:57 +0200229
François Gaffie11d30102018-11-02 16:09:09 +0100230 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
231 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200232
jiabinc0048632023-04-27 22:04:31 +0000233 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganovf88c2f32024-04-16 15:01:13 -0700234
235 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700236 return INVALID_OPERATION;
237 }
François Gaffie2110e042015-03-24 08:41:51 +0100238
jiabin1c4794b2020-05-05 10:08:05 -0700239 // Populate encapsulation information when a output device is connected.
240 device->setEncapsulationInfoFromHal(mpClientInterface);
241
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700242 // outputs should never be empty here
243 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
244 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100245 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800246
Eric Laurent3ae5f312015-02-03 17:12:08 -0800247 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700248 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700249 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700250 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100251 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700252 return INVALID_OPERATION;
253 }
254
François Gaffie11d30102018-11-02 16:09:09 +0100255 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700256
jiabinc0048632023-04-27 22:04:31 +0000257 // Notify the HAL to prepare to disconnect device
258 broadcastDeviceConnectionState(
259 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700260
Eric Laurente552edb2014-03-10 17:42:56 -0700261 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100262 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700263
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100264 mOutputs.clearSessionRoutesForDevice(device);
265
François Gaffie11d30102018-11-02 16:09:09 +0100266 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100267
jiabinc0048632023-04-27 22:04:31 +0000268 // Send Disconnect to HALs
269 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
270
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800271 // Reset active device codec
272 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
273
Kriti Dangef6be8f2020-11-05 11:58:19 +0100274 // remove device from mReportedFormatsMap cache
275 mReportedFormatsMap.erase(device);
276
jiabina84c3d32022-12-02 18:59:55 +0000277 // remove preferred mixer configurations
278 mPreferredMixerAttrInfos.erase(device->getId());
279
Eric Laurente552edb2014-03-10 17:42:56 -0700280 } break;
281
282 default:
François Gaffie11d30102018-11-02 16:09:09 +0100283 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700284 return BAD_VALUE;
285 }
286
Eric Laurent736a1022019-03-27 18:28:46 -0700287 // Propagate device availability to Engine
288 setEngineDeviceConnectionState(device, state);
289
Eric Laurentae970022019-01-29 14:25:04 -0800290 // No need to evaluate playback routing when connecting a remote submix
291 // output device used by a dynamic policy of type recorder as no
292 // playback use case is affected.
293 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700294 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800295 for (audio_io_handle_t output : outputs) {
296 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800297 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
298 if (policyMix != nullptr
299 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000300 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800301 doCheckForDeviceAndOutputChanges = false;
302 break;
303 }
304 }
305 }
306
307 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700308 // outputs must be closed after checkOutputForAllStrategies() is executed
309 if (!outputs.isEmpty()) {
310 for (audio_io_handle_t output : outputs) {
311 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100312 // close unused outputs after device disconnection or direct outputs that have
313 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200314 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200315 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
316 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200317 (desc->mDirectOpenCount == 0))
318 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
319 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200320 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700321 closeOutput(output);
322 }
Eric Laurente552edb2014-03-10 17:42:56 -0700323 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700324 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
325 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700326 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700327 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800328 };
329
330 if (doCheckForDeviceAndOutputChanges) {
331 checkForDeviceAndOutputChanges(checkCloseOutputs);
332 } else {
333 checkCloseOutputs();
334 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100335 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100336 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700337 const DeviceVector activeMediaDevices =
338 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000339 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700340 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700341 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530342 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
343 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100344 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700345 // do not force device change on duplicated output because if device is 0, it will
346 // also force a device 0 for the two outputs it is duplicated to which may override
347 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100348 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100349 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700350 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700351 // always force when disconnecting (a non-duplicated device)
352 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000353 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000354 // If the device is using preferred mixer attributes, the output need to reopen
355 // with default configuration when the new selected devices are different from
356 // current routing devices
357 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
358 continue;
359 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530360 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700361 }
jiabinbce0c1d2020-10-05 11:20:18 -0700362 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000363 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700364 desc->supportsDevicesForPlayback(activeMediaDevices)) {
365 // Reopen the output to query the dynamic profiles when there is not active
366 // clients or all active clients will be rerouted. Otherwise, set the flag
367 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
368 // can be reopened to query dynamic profiles when all clients are inactive.
369 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000370 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700371 } else {
372 desc->mPendingReopenToQueryProfiles = true;
373 }
374 }
375 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
376 // Clear the flag that previously set for re-querying profiles.
377 desc->mPendingReopenToQueryProfiles = false;
378 }
379 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000380 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700381
Eric Laurentd60560a2015-04-10 11:31:20 -0700382 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700384 }
385
Eric Laurent96d1dda2022-03-14 17:14:19 +0100386 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
387
Eric Laurent72aa32f2014-05-30 18:51:48 -0700388 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530389 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700390 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700391 } // end if is output device
392
Eric Laurente552edb2014-03-10 17:42:56 -0700393 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700394 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100395 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700396 switch (state)
397 {
398 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700399 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700400 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100401 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700402 return INVALID_OPERATION;
403 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700404
Jaideep Sharma33173202024-06-18 17:46:45 +0530405 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
406
Eric Laurent0dd51852019-04-19 18:18:58 -0700407 if (mAvailableInputDevices.add(device) < 0) {
408 return NO_MEMORY;
409 }
410
François Gaffie44481e72016-04-20 07:49:57 +0200411 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
412 // parameters on newly connected devices (instead of opening the inputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800413 if (broadcastDeviceConnectionState(
414 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
415 mAvailableInputDevices.remove(device);
416 mHwModules.cleanUpForDevice(device);
417 ALOGE("%s() device %s format %x connection failed", __func__,
418 device->toString().c_str(), device->getEncodedFormat());
419 return INVALID_OPERATION;
420 }
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700421 // Propagate device availability to Engine
422 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200423
Eric Laurent0dd51852019-04-19 18:18:58 -0700424 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700425 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
426
Eric Laurent0dd51852019-04-19 18:18:58 -0700427 mAvailableInputDevices.remove(device);
428
jiabinc0048632023-04-27 22:04:31 +0000429 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100430
431 mHwModules.cleanUpForDevice(device);
432
Eric Laurentd4692962014-05-05 18:13:44 -0700433 return INVALID_OPERATION;
434 }
435
Eric Laurentd4692962014-05-05 18:13:44 -0700436 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700437
438 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700439 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700440 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100441 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700442 return INVALID_OPERATION;
443 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700444
François Gaffie11d30102018-11-02 16:09:09 +0100445 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700446
jiabinc0048632023-04-27 22:04:31 +0000447 // Notify the HAL to prepare to disconnect device
448 broadcastDeviceConnectionState(
449 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700450
François Gaffie11d30102018-11-02 16:09:09 +0100451 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700452
453 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100454
jiabinc0048632023-04-27 22:04:31 +0000455 // Set Disconnect to HALs
456 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
457
Kriti Dangef6be8f2020-11-05 11:58:19 +0100458 // remove device from mReportedFormatsMap cache
459 mReportedFormatsMap.erase(device);
Mikhail Naganovc66ffc12024-05-30 16:56:25 -0700460
461 // Propagate device availability to Engine
462 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700463 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700464
465 default:
François Gaffie11d30102018-11-02 16:09:09 +0100466 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700467 return BAD_VALUE;
468 }
469
Eric Laurent0dd51852019-04-19 18:18:58 -0700470 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700471 // As the input device list can impact the output device selection, update
472 // getDeviceForStrategy() cache
473 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700474
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100475 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200476 // Reconnect Audio Source
477 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
478 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
479 checkAudioSourceForAttributes(attributes);
480 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700481 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100482 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700483 }
484
Eric Laurentb52c1522014-05-20 11:27:36 -0700485 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharma33173202024-06-18 17:46:45 +0530486 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700487 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700488 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700489
François Gaffie11d30102018-11-02 16:09:09 +0100490 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700491 return BAD_VALUE;
492}
493
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100494status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
495 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800496 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700497 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
498 devDescr->setName(device_name);
499 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100500}
501
Eric Laurent736a1022019-03-27 18:28:46 -0700502void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
503 audio_policy_dev_state_t state) {
504
505 // the Engine does not have to know about remote submix devices used by dynamic audio policies
506 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
507 return;
508 }
509 mEngine->setDeviceConnectionState(device, state);
510}
511
512
Eric Laurente0720872014-03-11 09:30:41 -0700513audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100514 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700515{
Eric Laurent634b7142016-04-20 13:48:02 -0700516 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800517 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
518 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700519 (strlen(device_address) != 0)/*matchAddress*/);
520
521 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100522 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700523 device, device_address);
524 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
525 }
François Gaffie53615e22015-03-19 09:24:12 +0100526
Eric Laurent3a4311c2014-03-17 12:00:47 -0700527 DeviceVector *deviceVector;
528
Eric Laurente552edb2014-03-10 17:42:56 -0700529 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700530 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700531 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700532 deviceVector = &mAvailableInputDevices;
533 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100534 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700535 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700536 }
Eric Laurent634b7142016-04-20 13:48:02 -0700537
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800538 return (deviceVector->getDevice(
539 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700540 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800541}
542
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800543status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
544 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800545 const char *device_name,
546 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800547{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800548 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
549 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800550
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800551 // connect/disconnect only 1 device at a time
552 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
553
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800554 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700555 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800556 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800557 // Nothing to do: device is not connected
558 return NO_ERROR;
559 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800560 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800561
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700562 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800563 // configure codecs.
564 // Handle two specific cases by sending a set parameter to
565 // configure A2DP codecs. No need to toggle device state.
566 // Case 1: A2DP active device switches from primary to primary
567 // module
568 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100569 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700570 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800571 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
572 if (availablePrimaryOutputDevices().contains(devDesc) &&
573 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100574 bool isA2dp = audio_is_a2dp_out_device(device);
575 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
576 : String8(AudioParameter::keyReconfigLeSupported);
577 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800578 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100579 int isReconfigSupported;
580 repliedParameters.getInt(supportKey, isReconfigSupported);
581 if (isReconfigSupported) {
582 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
583 : String8(AudioParameter::keyReconfigLe);
584 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800585 param.add(key, String8("true"));
586 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
587 devDesc->setEncodedFormat(encodedFormat);
588 return NO_ERROR;
589 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700590 }
591 }
cnx421bd2dcc42020-07-11 14:58:44 +0800592 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000593 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800594 for (size_t i = 0; i < mOutputs.size(); i++) {
595 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000596 // mute media strategies to avoid sending the music tail into
597 // the earpiece or headset.
598 if (desc->isStrategyActive(musicStrategy)) {
599 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
600 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
601 tempRecommendedMuteDuration : desc->latency() * 4;
602 if (muteWaitMs < tempMuteDurationMs) {
603 muteWaitMs = tempMuteDurationMs;
604 }
605 }
cnx421bd2dcc42020-07-11 14:58:44 +0800606 setStrategyMute(musicStrategy, true, desc);
607 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
608 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
609 nullptr, true /*fromCache*/).types());
610 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000611 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
612 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
613 // happens after the actual device switch.
614 if (muteWaitMs > 0) {
615 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
616 usleep(muteWaitMs * 1000);
617 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800618 // Toggle the device state: UNAVAILABLE -> AVAILABLE
619 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100620 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800621 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800622 device_address, device_name,
623 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800624 if (status != NO_ERROR) {
625 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
626 status);
627 return status;
628 }
629
630 status = setDeviceConnectionState(device,
631 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800632 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800633 if (status != NO_ERROR) {
634 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
635 status);
636 return status;
637 }
638
639 return NO_ERROR;
640}
641
Pattydd807582021-11-04 21:01:03 +0800642status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
643 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800644{
Pattydd807582021-11-04 21:01:03 +0800645 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800646 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800647 std::unordered_set<audio_format_t> formatSet;
648 sp<HwModule> primaryModule =
649 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700650 if (primaryModule == nullptr) {
651 ALOGE("%s() unable to get primary module", __func__);
652 return NO_INIT;
653 }
Pattydd807582021-11-04 21:01:03 +0800654
655 DeviceTypeSet audioDeviceSet;
656
657 switch(device) {
658 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
659 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
660 break;
661 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800662 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
663 break;
664 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
665 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800666 break;
667 default:
668 ALOGE("%s() device type 0x%08x not supported", __func__, device);
669 return BAD_VALUE;
670 }
671
jiabin9a3361e2019-10-01 09:38:30 -0700672 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800673 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800674 for (const auto& device : declaredDevices) {
675 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800676 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800677 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800678 return status;
679}
680
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100681DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
682{
683 DeviceVector rxSinkdevices{};
684 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
685 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
686 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
687 auto rxSinkDevice = rxSinkdevices.itemAt(0);
688 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
689 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
690 // retrieve Rx Source device descriptor
691 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
692 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
693
694 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
695 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
696 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
697 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
698 return DeviceVector(rxSinkDevice);
699 }
700 }
701 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
702 // the device returned is not necessarily reachable via this output
703 // (filter later by setOutputDevices())
704 return getNewOutputDevices(mPrimaryOutput, fromCache);
705}
706
707status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
708{
François Gaffiedb1755b2023-09-01 11:50:35 +0200709 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100710 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
711 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
712 }
713 return INVALID_OPERATION;
714}
715
716status_t AudioPolicyManager::updateCallRoutingInternal(
717 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700718{
719 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100720 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700721 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200722 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700723 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100724 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700725 }
François Gaffie11d30102018-11-02 16:09:09 +0100726
Francois Gaffie716e1432019-01-14 16:58:59 +0100727 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100728 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200729
Eric Laurentb2fb4102024-06-21 12:25:26 +0000730 if (!fix_call_audio_patch()) {
731 disconnectTelephonyAudioSource(mCallRxSourceClient);
732 disconnectTelephonyAudioSource(mCallTxSourceClient);
733 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200734
735 if (rxDevices.isEmpty()) {
736 ALOGW("%s() no selected output device", __func__);
737 return INVALID_OPERATION;
738 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000739 if (txSourceDevice == nullptr) {
740 ALOGE("%s() selected input device not available", __func__);
741 return INVALID_OPERATION;
742 }
François Gaffiec005e562018-11-06 15:04:49 +0100743
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100744 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100745 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700746
François Gaffie9eb18552018-11-05 10:33:26 +0100747 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700748 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100749 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700750 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100751 // retrieve Rx Source and Tx Sink device descriptors
752 sp<DeviceDescriptor> rxSourceDevice =
753 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
754 String8(),
755 AUDIO_FORMAT_DEFAULT);
756 sp<DeviceDescriptor> txSinkDevice =
757 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
758 String8(),
759 AUDIO_FORMAT_DEFAULT);
760
761 // RX and TX Telephony device are declared by Primary Audio HAL
762 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
763 (telephonyRxModule->getHalVersionMajor() >= 3)) {
764 if (rxSourceDevice == 0 || txSinkDevice == 0) {
765 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100766 ALOGE("%s() no telephony Tx and/or RX device", __func__);
767 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100768 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100769 // createAudioPatchInternal now supports both HW / SW bridging
770 createRxPatch = true;
771 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100772 } else {
773 // If the RX device is on the primary HW module, then use legacy routing method for
774 // voice calls via setOutputDevice() on primary output.
775 // Otherwise, create two audio patches for TX and RX path.
776 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
777 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700778 // If the TX device is also on the primary HW module, setOutputDevice() will take care
779 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100780 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
781 (txSinkDevice != 0);
782 }
783 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
784 // Otherwise, create two audio patches for TX and RX path.
785 if (!createRxPatch) {
Eric Laurentb2fb4102024-06-21 12:25:26 +0000786 if (fix_call_audio_patch()) {
787 disconnectTelephonyAudioSource(mCallRxSourceClient);
788 }
François Gaffiedb1755b2023-09-01 11:50:35 +0200789 if (!hasPrimaryOutput()) {
790 ALOGW("%s() no primary output available", __func__);
791 return INVALID_OPERATION;
792 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530793 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700794 } else { // create RX path audio patch
David Lif85c5e32024-07-01 13:14:10 +0000795 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800796 // If the TX device is on the primary HW module but RX device is
797 // on other HW module, SinkMetaData of telephony input should handle it
798 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700799 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700800 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100801 // terminate active capture if on the same HW module as the call TX source device
802 // FIXME: would be better to refine to only inputs whose profile connects to the
803 // call TX device but this information is not in the audio patch and logic here must be
804 // symmetric to the one in startInput()
805 for (const auto& activeDesc : mInputs.getActiveInputs()) {
806 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
807 closeActiveClients(activeDesc);
808 }
809 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200810 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000811 } else if (fix_call_audio_patch()) {
812 disconnectTelephonyAudioSource(mCallTxSourceClient);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800813 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100814 if (waitMs != nullptr) {
815 *waitMs = muteWaitMs;
816 }
817 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800818}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700819
Mikhail Naganov100f0122018-11-29 11:22:16 -0800820bool AudioPolicyManager::isDeviceOfModule(
821 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
822 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
823 if (module != 0) {
824 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
825 .indexOf(devDesc) != NAME_NOT_FOUND
826 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
827 .indexOf(devDesc) != NAME_NOT_FOUND;
828 }
829 return false;
830}
831
David Lif85c5e32024-07-01 13:14:10 +0000832void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200833{
Eric Laurentb2fb4102024-06-21 12:25:26 +0000834 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
835
836 if (fix_call_audio_patch()) {
837 if (mCallRxSourceClient != nullptr) {
838 DeviceVector rxDevices =
839 mEngine->getOutputDevicesForAttributes(aa, nullptr, false /*fromCache*/);
840 ALOG_ASSERT(!rxDevices.isEmpty() || !mCallRxSourceClient->isConnected(),
841 "connectTelephonyRxAudioSource(): no device found for call RX source");
842 sp<DeviceDescriptor> rxDevice = rxDevices.itemAt(0);
843 if (mCallRxSourceClient->isConnected()
844 && mCallRxSourceClient->sinkDevice()->equals(rxDevice)) {
845 return;
846 }
847 disconnectTelephonyAudioSource(mCallRxSourceClient);
848 }
849 } else {
850 disconnectTelephonyAudioSource(mCallRxSourceClient);
851 }
852
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200853 const struct audio_port_config source = {
854 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
855 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
856 };
Eric Laurent541a2002024-01-15 18:11:42 +0100857 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurentb2fb4102024-06-21 12:25:26 +0000858
Eric Laurentccbd7872024-06-20 12:34:15 +0000859 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Lif85c5e32024-07-01 13:14:10 +0000860 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100861 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
862 mCallRxSourceClient = mAudioSources.valueFor(portId);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000863 ALOGV("%s portdID %d between source %s and sink %s", __func__, portId,
864 mCallRxSourceClient->srcDevice()->toString().c_str(),
865 mCallRxSourceClient->sinkDevice()->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200866 ALOGE_IF(mCallRxSourceClient == nullptr,
867 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200868}
869
Francois Gaffie601801d2021-06-22 13:27:39 +0200870void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200871{
Francois Gaffie601801d2021-06-22 13:27:39 +0200872 if (clientDesc == nullptr) {
873 return;
874 }
875 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
876 "%s error stopping audio source", __func__);
877 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200878}
879
880void AudioPolicyManager::connectTelephonyTxAudioSource(
881 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
882 uint32_t delayMs)
883{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200884 if (srcDevice == nullptr || sinkDevice == nullptr) {
885 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
886 return;
887 }
Eric Laurentb2fb4102024-06-21 12:25:26 +0000888
889 if (fix_call_audio_patch()) {
890 if (mCallTxSourceClient != nullptr) {
891 if (mCallTxSourceClient->isConnected()
892 && mCallTxSourceClient->srcDevice()->equals(srcDevice)) {
893 return;
894 }
895 disconnectTelephonyAudioSource(mCallTxSourceClient);
896 }
897 } else {
898 disconnectTelephonyAudioSource(mCallTxSourceClient);
899 }
900
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200901 PatchBuilder patchBuilder;
902 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000903
Francois Gaffie601801d2021-06-22 13:27:39 +0200904 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200905 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
906
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200907 struct audio_port_config source = {};
908 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100909 mCallTxSourceClient = new SourceClientDescriptor(
910 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurentccbd7872024-06-20 12:34:15 +0000911 mCommunnicationStrategy, toVolumeSource(aa), true,
912 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100913 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
914
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200915 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
916 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200917 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
918 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200919 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
Eric Laurentb2fb4102024-06-21 12:25:26 +0000920 ALOGV("%s portdID %d between source %s and sink %s", __func__, callTxSourceClientPortId,
921 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200922 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200923 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200924 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200925}
926
Eric Laurente0720872014-03-11 09:30:41 -0700927void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700928{
929 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100930 // store previous phone state for management of sonification strategy below
931 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100932 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100933
934 if (mEngine->setPhoneState(state) != NO_ERROR) {
935 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700936 return;
937 }
François Gaffie2110e042015-03-24 08:41:51 +0100938 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700939 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700940 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700941 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800942 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700943 }
944
François Gaffie2110e042015-03-24 08:41:51 +0100945 /**
946 * Switching to or from incall state or switching between telephony and VoIP lead to force
947 * routing command.
948 */
Eric Laurent74b71512019-11-06 17:21:57 -0800949 bool force = ((isStateInCall(oldState) != isStateInCall(state))
950 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700951
952 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700953 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700954
Eric Laurente552edb2014-03-10 17:42:56 -0700955 int delayMs = 0;
956 if (isStateInCall(state)) {
957 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100958 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
959 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700960 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700961 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700962 // mute media and sonification strategies and delay device switch by the largest
963 // latency of any output where either strategy is active.
964 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100965 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
966 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
967 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700968 (delayMs < (int)desc->latency()*2)) {
969 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700970 }
François Gaffiec005e562018-11-06 15:04:49 +0100971 setStrategyMute(musicStrategy, true, desc);
972 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
973 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
974 nullptr, true /*fromCache*/).types());
975 setStrategyMute(sonificationStrategy, true, desc);
976 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
977 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
978 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700979 }
980 }
981
François Gaffiedb1755b2023-09-01 11:50:35 +0200982 if (state == AUDIO_MODE_IN_CALL) {
983 (void)updateCallRouting(false /*fromCache*/, delayMs);
984 } else {
985 if (oldState == AUDIO_MODE_IN_CALL) {
986 disconnectTelephonyAudioSource(mCallRxSourceClient);
987 disconnectTelephonyAudioSource(mCallTxSourceClient);
988 }
989 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100990 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
991 // force routing command to audio hardware when ending call
992 // even if no device change is needed
993 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
994 rxDevices = mPrimaryOutput->devices();
995 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530996 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700997 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700998 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700999
jiabin3ff8d7d2022-12-13 06:27:44 +00001000 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001001 // reevaluate routing on all outputs in case tracks have been started during the call
1002 for (size_t i = 0; i < mOutputs.size(); i++) {
1003 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +01001004 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00001005 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
1006 && desc->mPreferredAttrInfo != nullptr) {
1007 // If the output is using preferred mixer attributes and the audio mode is not normal,
1008 // the output need to reopen with default configuration.
1009 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
1010 continue;
1011 }
Francois Gaffie601801d2021-06-22 13:27:39 +02001012 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
1013 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05301014 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +02001015 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001016 }
1017 }
jiabin3ff8d7d2022-12-13 06:27:44 +00001018 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -07001019
Eric Laurent96d1dda2022-03-14 17:14:19 +01001020 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
1021
Eric Laurente552edb2014-03-10 17:42:56 -07001022 if (isStateInCall(state)) {
1023 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -07001024 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -08001025 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -07001026 }
1027
1028 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +01001029 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
1030 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -07001031}
1032
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -07001033audio_mode_t AudioPolicyManager::getPhoneState() {
1034 return mEngine->getPhoneState();
1035}
1036
Eric Laurente0720872014-03-11 09:30:41 -07001037void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +01001038 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -07001039{
François Gaffie2110e042015-03-24 08:41:51 +01001040 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -07001041 if (config == mEngine->getForceUse(usage)) {
1042 return;
1043 }
Eric Laurente552edb2014-03-10 17:42:56 -07001044
François Gaffie2110e042015-03-24 08:41:51 +01001045 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1046 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1047 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001048 }
François Gaffie2110e042015-03-24 08:41:51 +01001049 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1050 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1051 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001052
1053 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001054 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001055
Eric Laurent22fcda22019-05-17 16:28:47 -07001056 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1057 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001058 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001059 }
1060
Eric Laurentdc462862016-07-19 12:29:53 -07001061 //FIXME: workaround for truncated touch sounds
1062 // to be removed when the problem is handled by system UI
1063 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001064 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1065 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1066 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001067
1068 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001069 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001070}
1071
Eric Laurente0720872014-03-11 09:30:41 -07001072void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001073{
1074 ALOGV("setSystemProperty() property %s, value %s", property, value);
1075}
1076
Dorin Drimusecc9f422022-03-09 17:57:40 +01001077// Find an MSD output profile compatible with the parameters passed.
1078// When "directOnly" is set, restrict search to profiles for direct outputs.
1079sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1080 const DeviceVector& devices,
1081 uint32_t samplingRate,
1082 audio_format_t format,
1083 audio_channel_mask_t channelMask,
1084 audio_output_flags_t flags,
1085 bool directOnly)
1086{
1087 flags = getRelevantFlags(flags, directOnly);
1088
1089 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1090 if (msdModule != nullptr) {
1091 // for the msd module check if there are patches to the output devices
1092 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1093 HwModuleCollection modules;
1094 modules.add(msdModule);
1095 return searchCompatibleProfileHwModules(
1096 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1097 flags, directOnly);
1098 }
1099 }
1100 return nullptr;
1101}
1102
Michael Chana94fbb22018-04-24 14:31:19 +10001103// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1104// search to profiles for direct outputs.
1105sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001106 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001107 uint32_t samplingRate,
1108 audio_format_t format,
1109 audio_channel_mask_t channelMask,
1110 audio_output_flags_t flags,
1111 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001112{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001113 flags = getRelevantFlags(flags, directOnly);
1114
1115 return searchCompatibleProfileHwModules(
1116 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1117}
1118
1119audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1120 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001121 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001122 // only retain flags that will drive the direct output profile selection
1123 // if explicitly requested
1124 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001125 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001126 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1127 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001128 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001129 return flags;
1130}
Eric Laurent861a6282015-05-18 15:40:16 -07001131
Dorin Drimusecc9f422022-03-09 17:57:40 +01001132sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1133 const HwModuleCollection& hwModules,
1134 const DeviceVector& devices,
1135 uint32_t samplingRate,
1136 audio_format_t format,
1137 audio_channel_mask_t channelMask,
1138 audio_output_flags_t flags,
1139 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001140 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001141 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001142 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001143 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001144 samplingRate, NULL /*updatedSamplingRate*/,
1145 format, NULL /*updatedFormat*/,
1146 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001147 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001148 continue;
1149 }
1150 // reject profiles not corresponding to a device currently available
1151 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1152 continue;
1153 }
1154 // reject profiles if connected device does not support codec
1155 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1156 continue;
1157 }
1158 if (!directOnly) {
1159 return curProfile;
1160 }
1161
1162 // when searching for direct outputs, if several profiles are compatible, give priority
1163 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001164 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001165 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001166 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001167 }
1168 profile = curProfile;
1169 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1170 break;
1171 }
Eric Laurente552edb2014-03-10 17:42:56 -07001172 }
1173 }
Eric Laurent861a6282015-05-18 15:40:16 -07001174 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001175}
1176
Eric Laurentfa0f6742021-08-17 18:39:44 +02001177sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001178 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001179{
1180 for (const auto& hwModule : mHwModules) {
1181 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001182 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001183 continue;
1184 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001185 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001186 // reject profiles not corresponding to a device currently available
1187 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1188 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1189 continue;
1190 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001191 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1192 != devices.size()) {
1193 continue;
1194 }
1195 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001196 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1197 return curProfile;
1198 }
1199 }
1200 return nullptr;
1201}
1202
Eric Laurentf4e63452017-11-06 19:31:46 +00001203audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001204{
François Gaffiec005e562018-11-06 15:04:49 +01001205 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001206
1207 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1208 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1209 // format, flags, etc. This may result in some discrepancy for functions that utilize
1210 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1211 // and AudioSystem::getOutputSamplingRate().
1212
François Gaffie11d30102018-11-02 16:09:09 +01001213 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001214 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov806170e2024-09-05 17:26:50 -07001215 if (stream == AUDIO_STREAM_MUSIC && mConfig->useDeepBufferForMedia()) {
Mingyu Shih75563d32023-05-24 04:47:40 +08001216 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1217 }
1218 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001219
François Gaffie11d30102018-11-02 16:09:09 +01001220 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1221 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001222 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001223}
1224
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001225status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1226 const audio_attributes_t *srcAttr,
1227 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001228{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001229 if (srcAttr != NULL) {
1230 if (!isValidAttributes(srcAttr)) {
1231 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1232 __func__,
1233 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1234 srcAttr->tags);
1235 return BAD_VALUE;
1236 }
1237 *dstAttr = *srcAttr;
1238 } else {
1239 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1240 ALOGE("%s: invalid stream type", __func__);
1241 return BAD_VALUE;
1242 }
François Gaffiec005e562018-11-06 15:04:49 +01001243 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001244 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001245
1246 // Only honor audibility enforced when required. The client will be
1247 // forced to reconnect if the forced usage changes.
1248 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001249 dstAttr->flags = static_cast<audio_flags_mask_t>(
1250 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001251 }
1252
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001253 return NO_ERROR;
1254}
1255
Kevin Rocard153f92d2018-12-18 18:33:28 -08001256status_t AudioPolicyManager::getOutputForAttrInt(
1257 audio_attributes_t *resultAttr,
1258 audio_io_handle_t *output,
1259 audio_session_t session,
1260 const audio_attributes_t *attr,
1261 audio_stream_type_t *stream,
1262 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001263 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001264 audio_output_flags_t *flags,
Robert Wufb971192024-10-30 21:54:35 +00001265 DeviceIdVector *selectedDeviceIds,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001266 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001267 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001268 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001269 bool *isSpatialized,
1270 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001271{
François Gaffiec005e562018-11-06 15:04:49 +01001272 DeviceVector outputDevices;
Robert Wufb971192024-10-30 21:54:35 +00001273 audio_port_handle_t requestedPortId = getFirstDeviceId(*selectedDeviceIds);
1274 selectedDeviceIds->clear();
François Gaffie11d30102018-11-02 16:09:09 +01001275 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001276 const sp<DeviceDescriptor> requestedDevice =
1277 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1278
Eric Laurent8a1095a2019-11-08 14:44:16 -08001279 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001280 *isSpatialized = false;
1281
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001282 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1283 if (status != NO_ERROR) {
1284 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001285 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001286 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001287 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001288 }
François Gaffiec005e562018-11-06 15:04:49 +01001289 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001290
François Gaffiec005e562018-11-06 15:04:49 +01001291 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1292 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001293
Oscar Azucena873d10f2023-01-12 18:34:42 -08001294 bool usePrimaryOutputFromPolicyMixes = false;
1295
Kevin Rocard153f92d2018-12-18 18:33:28 -08001296 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1297 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1298 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001299 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001300 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1301 .channel_mask = config->channel_mask,
1302 .format = config->format,
1303 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001304 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001305 mAvailableOutputDevices, requestedDevice, primaryMix,
1306 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001307 if (status != OK) {
1308 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001309 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001310
Kevin Rocard153f92d2018-12-18 18:33:28 -08001311 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001312 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungdb27c442024-08-14 11:37:57 -07001313 && (!audio_is_linear_pcm(config->format) ||
1314 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001315 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001316 return BAD_VALUE;
1317 }
1318 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001319 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001320 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1321 primaryMix->mDeviceAddress,
1322 AUDIO_FORMAT_DEFAULT);
1323 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001324 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001325 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1326 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001327 // if a direct output can be opened to deliver the track's multi-channel content to the
1328 // output rather than being downmixed by the primary output, then use this direct
1329 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1330 // mix.
1331 bool tryDirectForChannelMask = policyDesc != nullptr
1332 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1333 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001334 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001335 audio_io_handle_t newOutput;
1336 status = openDirectOutput(
1337 *stream, session, config,
1338 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangf6e304f2024-07-09 23:06:58 -07001339 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001340 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001341 policyDesc = mOutputs.valueFor(newOutput);
1342 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001343 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001344 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001345 policyDesc = nullptr;
1346 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001347 }
1348 if (policyDesc != nullptr) {
1349 policyDesc->mPolicyMix = primaryMix;
1350 *output = policyDesc->mIoHandle;
Robert Wufb971192024-10-30 21:54:35 +00001351 if (policyMixDevice != nullptr) {
1352 selectedDeviceIds->push_back(policyMixDevice->getId());
1353 }
jiabin24ff57a2023-11-27 21:06:51 +00001354 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1355 // Remove direct flag as it is not on a direct output.
1356 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1357 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001358
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001359 ALOGV("getOutputForAttr() returns output %d", *output);
1360 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1361 *outputType = API_OUT_MIX_PLAYBACK;
1362 } else {
1363 *outputType = API_OUTPUT_LEGACY;
1364 }
1365 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001366 } else {
1367 if (policyMixDevice != nullptr) {
1368 ALOGE("%s, try to use primary mix but no output found", __func__);
1369 return INVALID_OPERATION;
1370 }
1371 // Fallback to default engine selection as the selected primary mix device is not
1372 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001373 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001374 }
François Gaffiec005e562018-11-06 15:04:49 +01001375 // Virtual sources must always be dynamicaly or explicitly routed
1376 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1377 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1378 return BAD_VALUE;
1379 }
1380 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1381 // in order to let the choice of the order to future vendor engine
1382 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001383
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001384 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001385 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001386 }
1387
Nadav Barb2f18162018-07-18 13:01:53 +03001388 // Set incall music only if device was explicitly set, and fallback to the device which is
1389 // chosen by the engine if not.
1390 // FIXME: provide a more generic approach which is not device specific and move this back
1391 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001392 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001393 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001394 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001395 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001396 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001397 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001398 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001399 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001400 }
1401 }
1402
François Gaffiec005e562018-11-06 15:04:49 +01001403 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1404 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1405 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001406
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001407 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001408 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001409 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001410 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001411 ALOGV("%s() Using MSD devices %s instead of devices %s",
1412 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001413 } else {
1414 *output = AUDIO_IO_HANDLE_NONE;
1415 }
1416 }
1417 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001418 sp<PreferredMixerAttributesInfo> info = nullptr;
1419 if (outputDevices.size() == 1) {
1420 info = getPreferredMixerAttributesInfo(
1421 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001422 mEngine->getProductStrategyForAttributes(*resultAttr),
1423 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001424 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1425 // and it is currently active.
1426 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001427 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001428 info = nullptr;
1429 }
jiabin8a096672024-09-18 18:20:24 +00001430
1431 if (info != nullptr && info->isBitPerfect() &&
1432 (*flags & (AUDIO_OUTPUT_FLAG_DIRECT | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
1433 AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
1434 // Reject direct request if a preferred mixer config in use is bit-perfect.
1435 ALOGD("%s reject direct request as bit-perfect mixer attributes is active",
1436 __func__);
1437 return BAD_VALUE;
1438 }
1439
jiabin220eea12024-05-17 17:55:20 +00001440 if (com::android::media::audioserver::
1441 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1442 if (info != nullptr && info->getUid() == uid &&
1443 info->configMatches(*config) &&
1444 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1445 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1446 [this, &outputDevices](audio_usage_t usage) {
1447 return mOutputs.isUsageActiveOnDevice(
1448 usage, outputDevices[0]); }))) {
1449 // Bit-perfect request is not allowed when the phone mode is not normal or
1450 // there is any higher priority user case active.
1451 return INVALID_OPERATION;
1452 }
1453 }
jiabina84c3d32022-12-02 18:59:55 +00001454 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001455 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001456 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001457 // The client will be active if the client is currently preferred mixer owner and the
1458 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001459 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001460 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001461 && info->getUid() == uid
1462 && *output != AUDIO_IO_HANDLE_NONE
1463 // When bit-perfect output is selected for the preferred mixer attributes owner,
1464 // only need to consider the config matches.
1465 && mOutputs.valueFor(*output)->isConfigurationMatched(
1466 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001467
1468 if (*isBitPerfect) {
1469 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1470 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001471 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001472 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001473 AudioProfileVector profiles;
1474 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1475 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001476 const auto channels = profiles[0]->getChannels();
1477 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1478 config->channel_mask = *channels.begin();
1479 }
1480 const auto sampleRates = profiles[0]->getSampleRates();
1481 if (!sampleRates.empty() &&
1482 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1483 config->sample_rate = *sampleRates.begin();
1484 }
jiabinf1c73972022-04-14 16:28:52 -07001485 config->format = profiles[0]->getFormat();
1486 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001487 return INVALID_OPERATION;
1488 }
Paul McLeanaa981192015-03-21 09:55:15 -07001489
Michael Chan6fb34492020-12-08 15:44:49 +11001490 for (auto &outputDevice : outputDevices) {
Robert Wufb971192024-10-30 21:54:35 +00001491 if (std::find(selectedDeviceIds->begin(), selectedDeviceIds->end(),
1492 outputDevice->getId()) == selectedDeviceIds->end()) {
1493 selectedDeviceIds->push_back(outputDevice->getId());
1494 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
1495 std::swap(selectedDeviceIds->front(), selectedDeviceIds->back());
1496 }
Michael Chan6fb34492020-12-08 15:44:49 +11001497 }
1498 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001499
Eric Laurent8a1095a2019-11-08 14:44:16 -08001500 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1501 *outputType = API_OUTPUT_TELEPHONY_TX;
1502 } else {
1503 *outputType = API_OUTPUT_LEGACY;
1504 }
1505
Robert Wufb971192024-10-30 21:54:35 +00001506 ALOGV("%s returns output %d selectedDeviceIds %s", __func__, *output,
1507 toString(*selectedDeviceIds).c_str());
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001508
1509 return NO_ERROR;
1510}
1511
1512status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1513 audio_io_handle_t *output,
1514 audio_session_t session,
1515 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001516 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001517 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001518 audio_output_flags_t *flags,
Robert Wufb971192024-10-30 21:54:35 +00001519 DeviceIdVector *selectedDeviceIds,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001520 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001521 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001522 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001523 bool *isSpatialized,
Andy Hung6b137d12024-08-27 22:35:17 +00001524 bool *isBitPerfect,
Vlad Popa1e865e62024-08-15 19:11:42 -07001525 float *volume,
1526 bool *muted)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001527{
1528 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1529 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1530 return INVALID_OPERATION;
1531 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001532 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001533 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001534 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001535 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001536 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Robert Wufb971192024-10-30 21:54:35 +00001537 DeviceIdVector requestedDeviceIds = *selectedDeviceIds;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001538
1539 // Prevent from storing invalid requested device id in clients
Robert Wufb971192024-10-30 21:54:35 +00001540 DeviceIdVector sanitizedRequestedPortIds;
1541 for (auto deviceId : *selectedDeviceIds) {
1542 if (mAvailableOutputDevices.getDeviceFromId(deviceId) != nullptr) {
1543 sanitizedRequestedPortIds.push_back(deviceId);
1544 }
1545 }
1546 *selectedDeviceIds = sanitizedRequestedPortIds;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001547
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001548 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Robert Wufb971192024-10-30 21:54:35 +00001549 config, flags, selectedDeviceIds, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001550 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1551 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001552 if (status != NO_ERROR) {
1553 return status;
1554 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001555 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001556 if (secondaryOutputs != nullptr) {
1557 for (auto &secondaryMix : secondaryMixes) {
1558 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1559 if (outputDesc != nullptr &&
1560 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1561 secondaryOutputs->push_back(outputDesc->mIoHandle);
1562 weakSecondaryOutputDescs.push_back(outputDesc);
1563 }
1564 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001565 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001566
Eric Laurent8fc147b2018-07-22 19:13:55 -07001567 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001568 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001569 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001570 };
jiabin4ef93452019-09-10 14:29:54 -07001571 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001572
Eric Laurentc209fe42020-06-05 18:11:23 -07001573 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Robert Wufb971192024-10-30 21:54:35 +00001574 // TODO(b/367816690): Add device id sets to TrackClientDescriptor
Eric Laurent8fc147b2018-07-22 19:13:55 -07001575 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001576 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Robert Wufb971192024-10-30 21:54:35 +00001577 getFirstDeviceId(sanitizedRequestedPortIds), *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001578 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001579 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001580 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001581 std::move(weakSecondaryOutputDescs),
1582 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001583 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001584
Andy Hung6b137d12024-08-27 22:35:17 +00001585 *volume = Volume::DbToAmpl(outputDesc->getCurVolume(toVolumeSource(resultAttr)));
Vlad Popa1e865e62024-08-15 19:11:42 -07001586 *muted = outputDesc->isMutedByGroup(toVolumeSource(resultAttr));
Andy Hung6b137d12024-08-27 22:35:17 +00001587
Robert Wufb971192024-10-30 21:54:35 +00001588 ALOGV("%s() returns output %d requestedPortIds %s selectedDeviceIds %s for port ID %d",
1589 __func__, *output, toString(requestedDeviceIds).c_str(),
1590 toString(*selectedDeviceIds).c_str(), *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001591
Eric Laurente83b55d2014-11-14 10:06:21 -08001592 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001593}
1594
Eric Laurentc529cf62020-04-17 18:19:10 -07001595status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1596 audio_session_t session,
1597 const audio_config_t *config,
1598 audio_output_flags_t flags,
1599 const DeviceVector &devices,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001600 audio_io_handle_t *output,
1601 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001602
1603 *output = AUDIO_IO_HANDLE_NONE;
1604
1605 // skip direct output selection if the request can obviously be attached to a mixed output
1606 // and not explicitly requested
1607 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1608 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1609 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1610 return NAME_NOT_FOUND;
1611 }
1612
Mikhail Naganov806170e2024-09-05 17:26:50 -07001613 // Reject flag combinations that do not make sense. Note that the requested flags might not
1614 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1615 // combine the requested flags with its own flags, yielding an unsupported combination.
1616 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1617 return NAME_NOT_FOUND;
1618 }
1619
Eric Laurentc529cf62020-04-17 18:19:10 -07001620 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1621 // This prevents creating an offloaded track and tearing it down immediately after start
1622 // when audioflinger detects there is an active non offloadable effect.
1623 // FIXME: We should check the audio session here but we do not have it in this context.
1624 // This may prevent offloading in rare situations where effects are left active by apps
1625 // in the background.
1626 sp<IOProfile> profile;
1627 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1628 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1629 profile = getProfileForOutput(
1630 devices, config->sample_rate, config->format, config->channel_mask,
1631 flags, true /* directOnly */);
1632 }
1633
1634 if (profile == nullptr) {
1635 return NAME_NOT_FOUND;
1636 }
1637
1638 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1639 for (size_t i = 0; i < mOutputs.size(); i++) {
1640 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1641 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1642 // reuse direct output if currently open by the same client
1643 // and configured with same parameters
1644 if ((config->sample_rate == desc->getSamplingRate()) &&
1645 (config->format == desc->getFormat()) &&
1646 (config->channel_mask == desc->getChannelMask()) &&
1647 (session == desc->mDirectClientSession)) {
1648 desc->mDirectOpenCount++;
Jaideep Sharma33173202024-06-18 17:46:45 +05301649 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001650 mOutputs.keyAt(i), session);
1651 *output = mOutputs.keyAt(i);
1652 return NO_ERROR;
1653 }
1654 }
1655 }
1656
1657 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001658 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301659 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1660 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001661 return NAME_NOT_FOUND;
1662 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1663 // MMAP gracefully handles lack of an exclusive track resource by mixing
1664 // above the audio framework. For AAudio to know that the limit is reached,
1665 // return an error.
Jaideep Sharma33173202024-06-18 17:46:45 +05301666 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1667 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001668 return NAME_NOT_FOUND;
1669 } else {
1670 // Close outputs on this profile, if available, to free resources for this request
1671 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1672 const auto desc = mOutputs.valueAt(i);
1673 if (desc->mProfile == profile) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301674 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1675 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001676 closeOutput(desc->mIoHandle);
1677 }
1678 }
1679 }
1680 }
1681
1682 // Unable to close streams to find free resources for this request
1683 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05301684 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1685 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001686 return NAME_NOT_FOUND;
1687 }
1688
Atneya Nairb16666a2023-12-11 20:18:33 -08001689 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001690
Michael Chan6fb34492020-12-08 15:44:49 +11001691 // An MSD patch may be using the only output stream that can service this request. Release
1692 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001693 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001694
Eric Laurentf1f22e72021-07-13 14:04:14 +02001695 status_t status =
Dean Wheatleydfb67b82024-01-23 09:36:29 +11001696 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07001697 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001698
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001699 // only accept an output with the requested parameters, unless the format can be IEC61937
1700 // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1701 const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1702 && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1703 && audio_has_proportional_frames(outputDesc->getFormat());
Eric Laurentc529cf62020-04-17 18:19:10 -07001704 if (status != NO_ERROR ||
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001705 (!ignoreRequestedParametersCheck &&
1706 ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1707 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1708 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001709 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1710 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1711 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1712 config->channel_mask, outputDesc->getChannelMask());
1713 if (*output != AUDIO_IO_HANDLE_NONE) {
1714 outputDesc->close();
1715 }
1716 // fall back to mixer output if possible when the direct output could not be open
1717 if (audio_is_linear_pcm(config->format) &&
1718 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1719 return NAME_NOT_FOUND;
1720 }
1721 *output = AUDIO_IO_HANDLE_NONE;
1722 return BAD_VALUE;
1723 }
1724 outputDesc->mDirectOpenCount = 1;
1725 outputDesc->mDirectClientSession = session;
1726
1727 addOutput(*output, outputDesc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07001728 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
1729 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
1730 hwModule->getHalVersionMajor() >= 3) {
1731 setOutputDevices(__func__, outputDesc, devices, true, 0, NULL);
1732 }
Eric Laurentc529cf62020-04-17 18:19:10 -07001733 mPreviousOutputs = mOutputs;
1734 ALOGV("%s returns new direct output %d", __func__, *output);
1735 mpClientInterface->onAudioPortListUpdate();
1736 return NO_ERROR;
1737}
1738
François Gaffie11d30102018-11-02 16:09:09 +01001739audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1740 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001741 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001742 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001743 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001744 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001745 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001746 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001747 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001748{
Andy Hungc88b0642018-04-27 15:42:35 -07001749 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001750
jiabine375d412019-02-26 12:54:53 -08001751 // Discard haptic channel mask when forcing muting haptic channels.
1752 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001753 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1754 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001755
Eric Laurente552edb2014-03-10 17:42:56 -07001756 // open a direct output if required by specified parameters
1757 //force direct flag if offload flag is set: offloading implies a direct output stream
1758 // and all common behaviors are driven by checking only the direct flag
1759 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001760 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1761 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001762 }
Nadav Bar766fb022018-01-07 12:18:03 +02001763 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1764 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001765 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001766
1767 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1768
Eric Laurente83b55d2014-11-14 10:06:21 -08001769 // only allow deep buffering for music stream type
1770 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001771 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001772 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov806170e2024-09-05 17:26:50 -07001773 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001774 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001775 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001776 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001777 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001778 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001779 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001780 audio_is_linear_pcm(config->format) &&
1781 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001782 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001783 AUDIO_OUTPUT_FLAG_DIRECT);
1784 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001785 }
Eric Laurente552edb2014-03-10 17:42:56 -07001786
Carter Hsua3abb402021-10-26 11:11:20 +08001787 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1788 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1789 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1790 }
1791
Eric Laurentf9230d52024-01-26 18:49:09 +01001792 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao4c3af932024-04-26 04:12:21 +00001793 // was specified and offload or direct playback is not explicitly requested, and there is no
1794 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001795 *isSpatialized = false;
Shunkai Yao4c3af932024-04-26 04:12:21 +00001796 if (mSpatializerOutput != nullptr &&
1797 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1798 prefMixerConfigInfo == nullptr &&
1799 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1800 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001801 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001802 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001803 }
1804
Eric Laurentc529cf62020-04-17 18:19:10 -07001805 audio_config_t directConfig = *config;
1806 directConfig.channel_mask = channelMask;
Haofan Wangf6e304f2024-07-09 23:06:58 -07001807
1808 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1809 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001810 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001811 return output;
1812 }
1813
Eric Laurent14cbfca2016-03-17 09:42:16 -07001814 // A request for HW A/V sync cannot fallback to a mixed output because time
1815 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001816 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001817 return AUDIO_IO_HANDLE_NONE;
1818 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001819 // A request for Tuner cannot fallback to a mixed output
1820 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1821 return AUDIO_IO_HANDLE_NONE;
1822 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001823
Eric Laurente552edb2014-03-10 17:42:56 -07001824 // ignoring channel mask due to downmix capability in mixer
1825
1826 // open a non direct output
1827
1828 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001829 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001830 // get which output is suitable for the specified stream. The actual
1831 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001832 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001833 if (prefMixerConfigInfo != nullptr) {
1834 for (audio_io_handle_t outputHandle : outputs) {
1835 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1836 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1837 output = outputHandle;
1838 break;
1839 }
1840 }
1841 if (output == AUDIO_IO_HANDLE_NONE) {
1842 // No output open with the preferred profile. Open a new one.
1843 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1844 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1845 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1846 config.format = prefMixerConfigInfo->getConfigBase().format;
1847 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1848 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1849 &config, prefMixerConfigInfo->getFlags());
1850 if (preferredOutput == nullptr) {
1851 ALOGE("%s failed to open output with preferred mixer config", __func__);
1852 } else {
1853 output = preferredOutput->mIoHandle;
1854 }
1855 }
1856 } else {
1857 // at this stage we should ignore the DIRECT flag as no direct output could be
1858 // found earlier
1859 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001860 if (com::android::media::audioserver::
1861 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1862 // If the preferred mixer attributes is null, do not select the bit-perfect output
1863 // unless the bit-perfect output is the only output.
1864 // The bit-perfect output can exist while the passed in preferred mixer attributes
1865 // info is null when it is a high priority client. The high priority clients are
1866 // ringtone or alarm, which is not a bit-perfect use case.
1867 size_t i = 0;
1868 while (i < outputs.size() && outputs.size() > 1) {
1869 auto desc = mOutputs.valueFor(outputs[i]);
1870 // The output descriptor must not be null here.
1871 if (desc->isBitPerfect()) {
1872 outputs.removeItemsAt(i);
1873 } else {
1874 i += 1;
1875 }
1876 }
1877 }
jiabina84c3d32022-12-02 18:59:55 +00001878 output = selectOutput(
1879 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1880 }
Eric Laurente552edb2014-03-10 17:42:56 -07001881 }
François Gaffie11d30102018-11-02 16:09:09 +01001882 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001883 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001884 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001885
Eric Laurente552edb2014-03-10 17:42:56 -07001886 return output;
1887}
1888
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001889sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001890 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1891 mAvailableInputDevices);
1892 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1893}
1894
1895DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1896 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1897 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001898}
1899
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001900const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001901 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001902 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1903 if (msdModule != 0) {
1904 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1905 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1906 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1907 const struct audio_port_config *source = &patch->mPatch.sources[j];
1908 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1909 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001910 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001911 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001912 }
1913 }
1914 }
1915 return msdPatches;
1916}
1917
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001918bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1919 ssize_t index = mAudioPatches.indexOfKey(handle);
1920 if (index < 0) {
1921 return false;
1922 }
1923 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1924 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1925 if (msdModule == nullptr) {
1926 return false;
1927 }
1928 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1929 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1930 return true;
1931 }
1932 index = getMsdOutputPatches().indexOfKey(handle);
1933 if (index < 0) {
1934 return false;
1935 }
1936 return true;
1937}
1938
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001939status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1940 const InputProfileCollection &inputProfiles,
1941 const OutputProfileCollection &outputProfiles,
1942 const sp<DeviceDescriptor> &sourceDevice,
1943 const sp<DeviceDescriptor> &sinkDevice,
1944 AudioProfileVector& sourceProfiles,
1945 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001946 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001947 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001948 return NO_INIT;
1949 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001950 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001951 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001952 return NO_INIT;
1953 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001954 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001955 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1956 inProfile->supportsDevice(sourceDevice)) {
1957 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001958 }
1959 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001960 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001961 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001962 outProfile->supportsDevice(sinkDevice)) {
1963 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001964 }
1965 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001966 return NO_ERROR;
1967}
1968
1969status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1970 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1971 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1972{
Dean Wheatley16809da2022-12-09 14:55:46 +11001973 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1974 static const std::vector<audio_format_t> formatsOrder = {{
1975 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001976 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1977 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001978 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1979 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1980 // preferred).
1981 std::vector<audio_channel_mask_t> masks = {{
1982 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1983 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1984 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1985 // insert index masks (higher counts most preferred) as preferred over position masks
1986 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1987 masks.insert(
1988 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1989 }
1990 return masks;
1991 }();
1992
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001993 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001994 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1995 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001996 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001997 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1998 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001999 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002000 }
2001 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
2002 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
2003 sinkConfig->format = bestSinkConfig.format;
2004 // For encoded streams force direct flag to prevent downstream mixing.
2005 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2006 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11002007 if (audio_is_iec61937_compatible(sinkConfig->format)) {
2008 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002009 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11002010 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
2011 // raw and IEC61937 framed streams.
2012 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2013 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
2014 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002015 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
2016 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11002017 sourceConfig->channel_mask =
2018 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
2019 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
2020 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002021 sourceConfig->format = bestSinkConfig.format;
2022 // Copy input stream directly without any processing (e.g. resampling).
2023 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2024 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
2025 if (hwAvSync) {
2026 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
2027 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
2028 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
2029 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
2030 }
2031 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
2032 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
2033 sinkConfig->config_mask |= config_mask;
2034 sourceConfig->config_mask |= config_mask;
2035 return NO_ERROR;
2036}
2037
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002038PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
2039 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002040{
2041 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002042 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
2043 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
2044 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
2045 if (deviceModule == nullptr) {
2046 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
2047 return patchBuilder;
2048 }
2049 const InputProfileCollection inputProfiles = msdIsSource ?
2050 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
2051 const OutputProfileCollection outputProfiles = msdIsSource ?
2052 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
2053
2054 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
2055 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
2056 device : getMsdAudioOutDevices().itemAt(0);
2057 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
2058
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002059 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
2060 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002061 AudioProfileVector sourceProfiles;
2062 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002063 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
2064 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002065 for (auto hwAvSync : { true, false }) {
2066 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
2067 sourceProfiles, sinkProfiles) != NO_ERROR) {
2068 continue;
2069 }
2070 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2071 &sinkConfig) == NO_ERROR) {
2072 // Found a matching config. Re-create PatchBuilder with this config.
2073 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2074 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002075 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002076 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002077 " supporting PCM format conversion.", __func__);
2078 return patchBuilder;
2079}
2080
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002081status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002082 DeviceVector devices;
2083 if (outputDevices != nullptr && outputDevices->size() > 0) {
2084 devices.add(*outputDevices);
2085 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002086 // Use media strategy for unspecified output device. This should only
2087 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2088 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002089 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002090 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002091 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002092 }
Michael Chan6fb34492020-12-08 15:44:49 +11002093 std::vector<PatchBuilder> patchesToCreate;
2094 for (auto i = 0u; i < devices.size(); ++i) {
2095 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002096 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002097 }
2098 // Retain only the MSD patches associated with outputDevices request.
2099 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002100 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002101 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2102 auto retainedPatch = false;
2103 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2104 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2105 patchesToRemove.removeItemsAt(i);
2106 retainedPatch = true;
2107 break;
2108 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002109 }
Michael Chan6fb34492020-12-08 15:44:49 +11002110 if (retainedPatch) {
2111 it = patchesToCreate.erase(it);
2112 continue;
2113 }
2114 ++it;
2115 }
2116 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2117 return NO_ERROR;
2118 }
2119 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2120 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002121 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002122 }
Michael Chan6fb34492020-12-08 15:44:49 +11002123 status_t status = NO_ERROR;
2124 for (const auto &p : patchesToCreate) {
2125 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2126 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2127 char message[256];
2128 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2129 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2130 currStatus == NO_ERROR ? "Success" : "Error",
2131 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2132 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2133 if (currStatus == NO_ERROR) {
2134 ALOGD("%s", message);
2135 } else {
2136 ALOGE("%s", message);
2137 if (status == NO_ERROR) {
2138 status = currStatus;
2139 }
2140 }
2141 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002142 return status;
2143}
2144
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002145void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2146 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002147 for (size_t i = 0; i < msdPatches.size(); i++) {
2148 const auto& patch = msdPatches[i];
2149 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2150 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2151 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2152 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2153 releaseAudioPatch(patch->getHandle(), mUidCached);
2154 break;
2155 }
2156 }
2157 }
2158}
2159
Dorin Drimus94d94412022-02-02 09:05:02 +01002160bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002161 DeviceVector devicesToCheck =
2162 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002163 AudioPatchCollection msdPatches = getMsdOutputPatches();
2164 for (size_t i = 0; i < msdPatches.size(); i++) {
2165 const auto& patch = msdPatches[i];
2166 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2167 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2168 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2169 const auto& foundDevice = devicesToCheck.getDevice(
2170 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2171 if (foundDevice != nullptr) {
2172 devicesToCheck.remove(foundDevice);
2173 if (devicesToCheck.isEmpty()) {
2174 return true;
2175 }
2176 }
2177 }
2178 }
2179 }
2180 return false;
2181}
2182
Eric Laurente0720872014-03-11 09:30:41 -07002183audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002184 audio_output_flags_t flags,
2185 audio_format_t format,
2186 audio_channel_mask_t channelMask,
2187 uint32_t samplingRate,
2188 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002189{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002190 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2191 "%s called with format %#x", __func__, format);
2192
jiabinebb6af42020-06-09 17:31:17 -07002193 // Return the output that haptic-generating attached to when 1) session id is specified,
2194 // 2) haptic-generating effect exists for given session id and 3) the output that
2195 // haptic-generating effect attached to is in given outputs.
2196 if (sessionId != AUDIO_SESSION_NONE) {
2197 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2198 sessionId, FX_IID_HAPTICGENERATOR);
2199 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2200 return hapticGeneratingOutput;
2201 }
2202 }
2203
Eric Laurent16c66dd2019-05-01 17:54:10 -07002204 // Flags disqualifying an output: the match must happen before calling selectOutput()
2205 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2206 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2207
2208 // Flags expressing a functional request: must be honored in priority over
2209 // other criteria
2210 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2211 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002212 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2213 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002214 // Flags expressing a performance request: have lower priority than serving
2215 // requested sampling rate or channel mask
2216 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2217 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2218 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2219
2220 const audio_output_flags_t functionalFlags =
2221 (audio_output_flags_t)(flags & kFunctionalFlags);
2222 const audio_output_flags_t performanceFlags =
2223 (audio_output_flags_t)(flags & kPerformanceFlags);
2224
2225 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2226
Eric Laurente552edb2014-03-10 17:42:56 -07002227 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002228 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002229 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002230 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002231 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002232 // with tiebreak preferring the minimum number of extra functional flags
2233 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002234 // 3: the output supporting the exact channel mask
2235 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002236 // 5: the output with the highest sampling rate if the requested sample rate is
2237 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002238 // 6: the output with the highest number of requested performance flags
2239 // 7: the output with the bit depth the closest to the requested one
2240 // 8: the primary output
2241 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002242
Eric Laurent16c66dd2019-05-01 17:54:10 -07002243 // matching criteria values in priority order for best matching output so far
2244 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002245
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002246 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002247 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2248 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2249 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002250
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002251 for (audio_io_handle_t output : outputs) {
2252 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002253 // matching criteria values in priority order for current output
2254 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002255
Eric Laurent16c66dd2019-05-01 17:54:10 -07002256 if (outputDesc->isDuplicated()) {
2257 continue;
2258 }
2259 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2260 continue;
2261 }
Eric Laurent8838a382014-09-08 16:44:28 -07002262
Eric Laurent16c66dd2019-05-01 17:54:10 -07002263 // If haptic channel is specified, use the haptic output if present.
2264 // When using haptic output, same audio format and sample rate are required.
2265 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002266 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002267 // skip if haptic channel specified but output does not support it, or output support haptic
2268 // but there is no haptic channel requested AND no orphan haptic effect exist
2269 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2270 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002271 continue;
2272 }
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002273 // In the case of audio-coupled-haptic playback, there is no format conversion and
2274 // resampling in the framework, same format/channel/sampleRate for client and the output
2275 // thread is required. In the case of HapticGenerator effect, do not require format
2276 // matching.
2277 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2278 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao4c3af932024-04-26 04:12:21 +00002279 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao28f14bd2024-04-05 22:50:56 +00002280 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002281 }
2282
2283 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002284 const int matchingFunctionalFlags =
2285 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2286 const int totalFunctionalFlags =
2287 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2288 // Prefer matching functional flags, but subtract unnecessary functional flags.
2289 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002290
2291 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002292 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2293 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002294 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2295 channelCount <= outputChannelCount) {
2296 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002297 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2298 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002299 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002300 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002301 currentMatchCriteria[3] = outputChannelCount;
2302 }
2303
2304 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002305 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002306 int diff; // avoid unsigned integer overflow.
2307 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2308
2309 // prefer the closest output sampling rate greater than or equal to target
2310 // if none exists, prefer the closest output sampling rate less than target.
2311 //
2312 // criteria is offset to make non-negative.
2313 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002314 }
2315
2316 // performance flags match
2317 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2318
2319 // format match
2320 if (format != AUDIO_FORMAT_INVALID) {
2321 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002322 PolicyAudioPort::kFormatDistanceMax -
2323 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002324 }
2325
2326 // primary output match
2327 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2328
2329 // compare match criteria by priority then value
2330 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2331 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2332 bestMatchCriteria = currentMatchCriteria;
2333 bestOutput = output;
2334
2335 std::stringstream result;
2336 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2337 std::ostream_iterator<int>(result, " "));
2338 ALOGV("%s new bestOutput %d criteria %s",
2339 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002340 }
2341 }
2342
Eric Laurent16c66dd2019-05-01 17:54:10 -07002343 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002344}
2345
Eric Laurent8fc147b2018-07-22 19:13:55 -07002346status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002347{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002348 ALOGV("%s portId %d", __FUNCTION__, portId);
2349
2350 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2351 if (outputDesc == 0) {
2352 ALOGW("startOutput() no output for client %d", portId);
Eric Laurent5d837ea2024-11-15 18:56:01 +00002353 return DEAD_OBJECT;
Eric Laurente552edb2014-03-10 17:42:56 -07002354 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002355 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002356
Eric Laurent8fc147b2018-07-22 19:13:55 -07002357 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002358 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002359
jiabin220eea12024-05-17 17:55:20 +00002360 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2361 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2362 && outputDesc->isBitPerfect()) {
2363 // Usually, APM selects bit-perfect output for high priority use cases only when
2364 // bit-perfect output is the only output that can be routed to the selected device.
2365 // However, here is no need to play high priority use cases such as ringtone and alarm
2366 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2367 // can attach to new output.
2368 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2369 __func__, client->stream());
2370 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2371 return DEAD_OBJECT;
2372 }
2373
Eric Laurent733ce942017-12-07 12:18:25 -08002374 status_t status = outputDesc->start();
2375 if (status != NO_ERROR) {
2376 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002377 }
2378
Eric Laurent97ac8712018-07-27 18:59:02 -07002379 uint32_t delayMs;
2380 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002381
2382 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002383 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002384 if (status == DEAD_OBJECT) {
2385 sp<SwAudioOutputDescriptor> desc =
2386 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2387 if (desc == nullptr) {
2388 // This is not common, it may indicate something wrong with the HAL.
2389 ALOGE("%s unable to open output with default config", __func__);
2390 return status;
2391 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002392 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002393 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002394 }
jiabina84c3d32022-12-02 18:59:55 +00002395
2396 // If the client is the first one active on preferred mixer parameters, reopen the output
2397 // if the current mixer parameters doesn't match the preferred one.
2398 if (outputDesc->devices().size() == 1) {
2399 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2400 outputDesc->devices()[0]->getId(), client->strategy());
2401 if (info != nullptr && info->getUid() == client->uid()) {
2402 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2403 info->getConfigBase(), info->getFlags())) {
2404 stopSource(outputDesc, client);
2405 outputDesc->stop();
2406 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2407 config.channel_mask = info->getConfigBase().channel_mask;
2408 config.sample_rate = info->getConfigBase().sample_rate;
2409 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002410 sp<SwAudioOutputDescriptor> desc =
2411 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2412 if (desc == nullptr) {
2413 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002414 }
jiabin220eea12024-05-17 17:55:20 +00002415 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002416 // Intentionally return error to let the client side resending request for
2417 // creating and starting.
2418 return DEAD_OBJECT;
2419 }
2420 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002421 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002422 // If it is first bit-perfect client, reroute all clients that will be routed to
2423 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2424 PortHandleVector clientsToInvalidate;
jiabine6b87492024-09-18 23:36:14 +00002425 std::vector<sp<SwAudioOutputDescriptor>> outputsToResetDevice;
jiabine3d1f552023-06-14 17:42:17 +00002426 for (size_t i = 0; i < mOutputs.size(); i++) {
jiabinfedb92e2024-09-16 21:36:30 +00002427 if (mOutputs[i] == outputDesc || (!mOutputs[i]->devices().isEmpty() &&
2428 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty())) {
jiabine3d1f552023-06-14 17:42:17 +00002429 continue;
2430 }
jiabine6b87492024-09-18 23:36:14 +00002431 if (mOutputs[i]->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
2432 outputsToResetDevice.push_back(mOutputs[i]);
2433 }
jiabine3d1f552023-06-14 17:42:17 +00002434 for (const auto& c : mOutputs[i]->getClientIterable()) {
2435 clientsToInvalidate.push_back(c->portId());
2436 }
2437 }
2438 if (!clientsToInvalidate.empty()) {
2439 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2440 __func__);
2441 mpClientInterface->invalidateTracks(clientsToInvalidate);
2442 }
jiabine6b87492024-09-18 23:36:14 +00002443 for (const auto& output : outputsToResetDevice) {
2444 resetOutputDevice(output, 0 /*delayMs*/, nullptr /*patchHandle*/);
2445 }
jiabine3d1f552023-06-14 17:42:17 +00002446 }
jiabina84c3d32022-12-02 18:59:55 +00002447 }
2448 }
2449
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002450 if (client->hasPreferredDevice()) {
2451 // playback activity with preferred device impacts routing occurred, inform upper layers
2452 mpClientInterface->onRoutingUpdated();
2453 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002454 if (delayMs != 0) {
2455 usleep(delayMs * 1000);
2456 }
2457
jiabin220eea12024-05-17 17:55:20 +00002458 if (status == NO_ERROR &&
2459 outputDesc->mPreferredAttrInfo != nullptr &&
2460 outputDesc->isBitPerfect() &&
2461 com::android::media::audioserver::
2462 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2463 // A new client is started on bit-perfect output, update all clients internal mute.
2464 updateClientsInternalMute(outputDesc);
2465 }
2466
Eric Laurentc75307b2015-03-17 15:29:32 -07002467 return status;
2468}
2469
Eric Laurent96d1dda2022-03-14 17:14:19 +01002470bool AudioPolicyManager::isLeUnicastActive() const {
2471 if (isInCall()) {
2472 return true;
2473 }
2474 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2475}
2476
2477bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2478 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2479 return false;
2480 }
2481 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2482 ALOGV("%s active %d", __func__, active);
2483 return active;
2484}
2485
Eric Laurent97ac8712018-07-27 18:59:02 -07002486status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2487 const sp<TrackClientDescriptor>& client,
2488 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002489{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002490 // cannot start playback of STREAM_TTS if any other output is being used
2491 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002492
2493 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002494 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002495 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002496 auto clientStrategy = client->strategy();
2497 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002498 if (stream == AUDIO_STREAM_TTS) {
2499 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002500 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002501 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002502 return INVALID_OPERATION;
2503 } else {
2504 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2505 }
2506 } else {
2507 // some playback other than beacon starts
2508 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2509 }
2510
Eric Laurent77305a62016-07-25 16:39:22 -07002511 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002512 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002513 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002514
François Gaffie11d30102018-11-02 16:09:09 +01002515 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002516 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002517 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002518 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002519 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002520 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002521 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002522 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002523 } else {
2524 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002525 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002526 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2527 AUDIO_FORMAT_DEFAULT);
2528 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2529 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002530 }
2531
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002532 // requiresMuteCheck is false when we can bypass mute strategy.
2533 // It covers a common case when there is no materially active audio
2534 // and muting would result in unnecessary delay and dropped audio.
2535 const uint32_t outputLatencyMs = outputDesc->latency();
2536 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002537 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002538
Eric Laurente552edb2014-03-10 17:42:56 -07002539 // increment usage count for this stream on the requested output:
2540 // NOTE that the usage count is the same for duplicated output and hardware output which is
2541 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002542 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002543
2544 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002545 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002546 // Preferred device may be exclusive, use only if no other active clients on this output
2547 devices = DeviceVector(
2548 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2549 } else {
2550 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2551 }
François Gaffie11d30102018-11-02 16:09:09 +01002552 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002553 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002554 }
2555 }
Eric Laurente552edb2014-03-10 17:42:56 -07002556
François Gaffiec005e562018-11-06 15:04:49 +01002557 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002558 selectOutputForMusicEffects();
2559 }
2560
François Gaffie1c878552018-11-22 16:53:21 +01002561 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002562 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002563 if (devices.isEmpty()) {
2564 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002565 }
François Gaffiec005e562018-11-06 15:04:49 +01002566 bool shouldWait =
2567 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2568 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2569 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002570 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002571 const bool needToCloseBitPerfectOutput =
2572 (com::android::media::audioserver::
2573 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2574 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2575 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002576 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002577 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002578 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002579 // An output has a shared device if
2580 // - managed by the same hw module
2581 // - supports the currently selected device
2582 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002583 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002584
Eric Laurent77305a62016-07-25 16:39:22 -07002585 // force a device change if any other output is:
2586 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002587 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002588 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002589 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002590 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002591 // change the device currently selected by the other output.
2592 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002593 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002594 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002595 force = true;
2596 }
2597 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002598 // a notification so that audio focus effect can propagate, or that a mute/unmute
2599 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002600 const uint32_t latencyMs = desc->latency();
2601 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2602
2603 if (shouldWait && isActive && (waitMs < latencyMs)) {
2604 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002605 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002606
2607 // Require mute check if another output is on a shared device
2608 // and currently active to have proper drain and avoid pops.
2609 // Note restoring AudioTracks onto this output needs to invoke
2610 // a volume ramp if there is no mute.
2611 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002612
2613 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2614 outputsToReopen.push_back(desc);
2615 }
Eric Laurente552edb2014-03-10 17:42:56 -07002616 }
2617 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002618
jiabin220eea12024-05-17 17:55:20 +00002619 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002620 // If the output is open with preferred mixer attributes, but the routed device is
2621 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2622 // changed.
2623 return DEAD_OBJECT;
2624 }
jiabin220eea12024-05-17 17:55:20 +00002625 for (auto& outputToReopen : outputsToReopen) {
2626 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2627 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002628 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302629 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2630 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002631
Eric Laurente552edb2014-03-10 17:42:56 -07002632 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002633 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002634 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002635 curves.getVolumeIndex(outputDesc->devices().types()),
Vlad Popa1e865e62024-08-15 19:11:42 -07002636 outputDesc, outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002637 outputDesc->useHwGain() /*force*/)) {
2638 // request AudioService to reinitialize the volume curves asynchronously
2639 ALOGE("checkAndSetVolume failed, requesting volume range init");
2640 mpClientInterface->onVolumeRangeInitRequest();
2641 };
Eric Laurente552edb2014-03-10 17:42:56 -07002642
2643 // update the outputs if starting an output with a stream that can affect notification
2644 // routing
2645 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002646
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002647 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002648 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002649 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002650 }
Eric Laurentdc462862016-07-19 12:29:53 -07002651
2652 if (waitMs > muteWaitMs) {
2653 *delayMs = waitMs - muteWaitMs;
2654 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002655
2656 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2657 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2658 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2659 // change occurs after the MixerThread starts and causes a stream volume
2660 // glitch.
2661 //
2662 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002663 }
Eric Laurentdc462862016-07-19 12:29:53 -07002664
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002665 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002666 mEngine->getForceUse(
2667 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002668 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002669 }
2670
Eric Laurent97ac8712018-07-27 18:59:02 -07002671 // Automatically enable the remote submix input when output is started on a re routing mix
2672 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002673 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2674 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002675 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2676 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2677 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002678 "remote-submix",
2679 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002680 }
2681
Eric Laurent96d1dda2022-03-14 17:14:19 +01002682 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2683
Eric Laurente552edb2014-03-10 17:42:56 -07002684 return NO_ERROR;
2685}
2686
Eric Laurent96d1dda2022-03-14 17:14:19 +01002687void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2688 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2689 bool isUnicastActive = isLeUnicastActive();
2690
2691 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002692 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002693 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2694 for (size_t i = 0; i < mOutputs.size(); i++) {
2695 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2696 if (desc != ignoredOutput && desc->isActive()
2697 && ((isUnicastActive &&
2698 !desc->devices().
2699 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2700 || (wasUnicastActive &&
2701 !desc->devices().getDevicesFromTypes(
2702 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2703 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2704 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002705 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002706 // If the device is using preferred mixer attributes, the output need to reopen
2707 // with default configuration when the new selected devices are different from
2708 // current routing devices.
2709 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2710 continue;
2711 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302712 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002713 // re-apply device specific volume if not done by setOutputDevice()
2714 if (!force) {
2715 applyStreamVolumes(desc, newDevices.types(), delayMs);
2716 }
2717 }
2718 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002719 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002720 }
2721}
2722
Eric Laurent8fc147b2018-07-22 19:13:55 -07002723status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002724{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002725 ALOGV("%s portId %d", __FUNCTION__, portId);
2726
2727 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2728 if (outputDesc == 0) {
2729 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurent5d837ea2024-11-15 18:56:01 +00002730 return DEAD_OBJECT;
Eric Laurente552edb2014-03-10 17:42:56 -07002731 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002732 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002733
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002734 if (client->hasPreferredDevice(true)) {
2735 // playback activity with preferred device impacts routing occurred, inform upper layers
2736 mpClientInterface->onRoutingUpdated();
2737 }
2738
Eric Laurent97ac8712018-07-27 18:59:02 -07002739 ALOGV("stopOutput() output %d, stream %d, session %d",
2740 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002741
Eric Laurent97ac8712018-07-27 18:59:02 -07002742 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002743
Eric Laurent733ce942017-12-07 12:18:25 -08002744 if (status == NO_ERROR ) {
2745 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002746 } else {
2747 return status;
2748 }
2749
2750 if (outputDesc->devices().size() == 1) {
2751 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2752 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002753 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002754 if (info != nullptr && info->getUid() == client->uid()) {
2755 info->decreaseActiveClient();
2756 if (info->getActiveClientCount() == 0) {
2757 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002758 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002759 }
2760 }
jiabin220eea12024-05-17 17:55:20 +00002761 if (com::android::media::audioserver::
2762 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2763 !outputReopened && outputDesc->isBitPerfect()) {
2764 // Only need to update the clients' internal mute when the output is bit-perfect and it
2765 // is not reopened.
2766 updateClientsInternalMute(outputDesc);
2767 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002768 }
2769 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002770}
2771
Eric Laurent97ac8712018-07-27 18:59:02 -07002772status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2773 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002774{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002775 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002776 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002777 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002778 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002779
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002780 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2781
François Gaffie1c878552018-11-22 16:53:21 +01002782 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2783 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002784 // Automatically disable the remote submix input when output is stopped on a
2785 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002786 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002787 if (isSingleDeviceType(
2788 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002789 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002790 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002791 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2792 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002793 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002794 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002795 }
2796 }
2797 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002798 if (client->hasPreferredDevice(true) &&
2799 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002800 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002801 forceDeviceUpdate = true;
2802 }
2803
Eric Laurente552edb2014-03-10 17:42:56 -07002804 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002805 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002806
Eric Laurente552edb2014-03-10 17:42:56 -07002807 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002808 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002809 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002810 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002811
2812 // If the routing does not change, if an output is routed on a device using HwGain
2813 // (aka setAudioPortConfig) and there are still active clients following different
2814 // volume group(s), force reapply volume
2815 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2816 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2817
Eric Laurente552edb2014-03-10 17:42:56 -07002818 // delay the device switch by twice the latency because stopOutput() is executed when
2819 // the track stop() command is received and at that time the audio track buffer can
2820 // still contain data that needs to be drained. The latency only covers the audio HAL
2821 // and kernel buffers. Also the latency does not always include additional delay in the
2822 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302823 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002824 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002825
2826 // force restoring the device selection on other active outputs if it differs from the
2827 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002828 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002829 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002830 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002831 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002832 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002833 desc->isActive() &&
2834 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002835 (newDevices != desc->devices())) {
2836 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2837 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002838
jiabin220eea12024-05-17 17:55:20 +00002839 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002840 // If the device is using preferred mixer attributes, the output need to
2841 // reopen with default configuration when the new selected devices are
2842 // different from current routing devices.
2843 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2844 continue;
2845 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302846 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002847
Eric Laurent57de36c2016-09-28 16:59:11 -07002848 // re-apply device specific volume if not done by setOutputDevice()
2849 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002850 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002851 }
Eric Laurente552edb2014-03-10 17:42:56 -07002852 }
2853 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002854 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002855 // update the outputs if stopping one with a stream that can affect notification routing
2856 handleNotificationRoutingForStream(stream);
2857 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002858
2859 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2860 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002861 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002862 }
2863
François Gaffiec005e562018-11-06 15:04:49 +01002864 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002865 selectOutputForMusicEffects();
2866 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002867
2868 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2869
Eric Laurente552edb2014-03-10 17:42:56 -07002870 return NO_ERROR;
2871 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002872 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002873 return INVALID_OPERATION;
2874 }
2875}
2876
jiabinbce0c1d2020-10-05 11:20:18 -07002877bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002878{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002879 ALOGV("%s portId %d", __FUNCTION__, portId);
2880
2881 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2882 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002883 // If an output descriptor is closed due to a device routing change,
2884 // then there are race conditions with releaseOutput from tracks
2885 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2886 // destroyed shortly thereafter.
2887 //
2888 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002889 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002890 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002891 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002892
2893 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002894
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302895 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2896 if (outputDesc->isClientActive(client)) {
2897 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2898 stopOutput(portId);
2899 }
2900
Eric Laurent8fc147b2018-07-22 19:13:55 -07002901 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2902 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002903 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002904 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002905 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002906 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002907 if (--outputDesc->mDirectOpenCount == 0) {
2908 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002909 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002910 }
2911 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302912
Andy Hung39efb7a2018-09-26 15:39:28 -07002913 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002914 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2915 // The output is pending reopened to query dynamic profiles and
2916 // there is no active clients
2917 closeOutput(outputDesc->mIoHandle);
2918 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2919 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2920 if (newOutputDesc == nullptr) {
2921 ALOGE("%s failed to open output", __func__);
2922 }
2923 return true;
2924 }
2925 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002926}
2927
Eric Laurentcaf7f482014-11-25 17:50:47 -08002928status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2929 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002930 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002931 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002932 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002933 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002934 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002935 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002936 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002937 audio_port_handle_t *portId,
2938 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002939{
François Gaffiec005e562018-11-06 15:04:49 +01002940 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002941 "flags %#x attributes=%s requested device ID %d",
2942 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2943 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002944
Eric Laurentad2e7b92017-09-14 20:06:42 -07002945 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002946 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002947 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002948 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002949 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002950 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002951 sp<RecordClientDescriptor> clientDesc;
2952 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002953 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002954 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002955
2956 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2957 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2958 return INVALID_OPERATION;
2959 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002960
Francois Gaffie716e1432019-01-14 16:58:59 +01002961 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2962 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002963 }
2964
Paul McLean466dc8e2015-04-17 13:15:36 -06002965 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002966 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002967 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002968
Eric Laurentad2e7b92017-09-14 20:06:42 -07002969 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2970 // possible
2971 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2972 *input != AUDIO_IO_HANDLE_NONE) {
2973 ssize_t index = mInputs.indexOfKey(*input);
2974 if (index < 0) {
2975 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2976 status = BAD_VALUE;
2977 goto error;
2978 }
2979 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002980 RecordClientVector clients = inputDesc->getClientsForSession(session);
2981 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002982 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2983 status = BAD_VALUE;
2984 goto error;
2985 }
2986 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2987 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002988 // corresponds to a new client and is only permitted from the same UID.
2989 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002990 if (clients.size() > 1) {
2991 for (const auto& client : clients) {
2992 // The client map is ordered by key values (portId) and portIds are allocated
2993 // incrementaly. So the first client in this list is the one opened by audio flinger
2994 // when the mmap stream is created and should be ignored as it does not correspond
2995 // to an actual client
2996 if (client == *clients.cbegin()) {
2997 continue;
2998 }
2999 if (uid != client->uid() && !client->isSilenced()) {
3000 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
3001 uid, client->portId(), client->uid());
3002 status = INVALID_OPERATION;
3003 goto error;
3004 }
Eric Laurent331679c2018-04-16 17:03:16 -07003005 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003006 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003007 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01003008 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07003009
Eric Laurentfecbceb2021-02-09 14:46:43 +01003010 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003011 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003012 }
3013
3014 *input = AUDIO_IO_HANDLE_NONE;
3015 *inputType = API_INPUT_INVALID;
3016
Francois Gaffie716e1432019-01-14 16:58:59 +01003017 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02003018 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003019 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003020 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003021 ALOGW("%s could not find input mix for attr %s",
3022 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07003023 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01003024 }
jiabinc1de2df2019-05-07 14:26:40 -07003025 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
3026 String8(attr->tags + strlen("addr=")),
3027 AUDIO_FORMAT_DEFAULT);
3028 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07003029 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07003030 __func__, attributes.source, attributes.tags);
3031 status = BAD_VALUE;
3032 goto error;
3033 }
3034
Kevin Rocard25f9b052019-02-27 15:08:54 -08003035 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
3036 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
3037 } else {
3038 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
3039 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01003040 if (virtualDeviceId) {
3041 *virtualDeviceId = policyMix->mVirtualDeviceId;
3042 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003043 } else {
François Gaffie11d30102018-11-02 16:09:09 +01003044 if (explicitRoutingDevice != nullptr) {
3045 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07003046 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01003047 // Prevent from storing invalid requested device id in clients
3048 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003049 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08003050 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
3051 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07003052 }
François Gaffie11d30102018-11-02 16:09:09 +01003053 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01003054 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07003055 status = BAD_VALUE;
3056 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08003057 }
Alden DSouzab7d20782021-02-08 08:51:42 -08003058 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
3059 *inputType = API_INPUT_MIX_CAPTURE;
3060 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01003061 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
3062 // there is an external policy, but this input is attached to a mix of recorders,
3063 // meaning it receives audio injected into the framework, so the recorder doesn't
3064 // know about it and is therefore considered "legacy"
3065 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01003066
3067 if (virtualDeviceId) {
3068 *virtualDeviceId = policyMix->mVirtualDeviceId;
3069 }
François Gaffie11d30102018-11-02 16:09:09 +01003070 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003071 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01003072 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07003073 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08003074 } else {
3075 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003076 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003077
Eric Laurent599c7582015-12-07 18:05:55 -08003078 }
3079
François Gaffiec005e562018-11-06 15:04:49 +01003080 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003081 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003082 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003083 AudioProfileVector profiles;
3084 status_t ret = getProfilesForDevices(
3085 DeviceVector(device), profiles, flags, true /*isInput*/);
3086 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003087 const auto channels = profiles[0]->getChannels();
3088 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3089 config->channel_mask = *channels.begin();
3090 }
3091 const auto sampleRates = profiles[0]->getSampleRates();
3092 if (!sampleRates.empty() &&
3093 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3094 config->sample_rate = *sampleRates.begin();
3095 }
jiabinf1c73972022-04-14 16:28:52 -07003096 config->format = profiles[0]->getFormat();
3097 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003098 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003099 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003100
Marvin Ramine5a122d2023-12-07 13:57:59 +01003101
3102 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3103 *virtualDeviceId = policyMix->mVirtualDeviceId;
3104 }
3105
Eric Laurent8f42ea12018-08-08 09:08:25 -07003106exit:
3107
François Gaffiec005e562018-11-06 15:04:49 +01003108 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3109 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003110
Francois Gaffie716e1432019-01-14 16:58:59 +01003111 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003112 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003113 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003114
Mikhail Naganov2996f672019-04-18 12:29:59 -07003115 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003116 requestedDeviceId, attributes.source, flags,
3117 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003118 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003119 // Move (if found) effect for the client session to its input
3120 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003121 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003122
3123 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3124 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003125
Eric Laurent599c7582015-12-07 18:05:55 -08003126 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003127
3128error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003129 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003130}
3131
3132
François Gaffie11d30102018-11-02 16:09:09 +01003133audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003134 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003135 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003136 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003137 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003138 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003139{
3140 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003141 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003142 bool isSoundTrigger = false;
3143
François Gaffiec005e562018-11-06 15:04:49 +01003144 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003145 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3146 if (index >= 0) {
3147 input = mSoundTriggerSessions.valueFor(session);
3148 isSoundTrigger = true;
3149 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3150 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3151 } else {
3152 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003153 }
François Gaffiec005e562018-11-06 15:04:49 +01003154 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003155 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003156 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003157 }
3158
Carter Hsua3abb402021-10-26 11:11:20 +08003159 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3160 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3161 }
3162
Eric Laurentfe231122017-11-17 17:48:06 -08003163 // sampling rate and flags may be updated by getInputProfile
3164 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3165 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003166 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003167 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003168 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003169 // find a compatible input profile (not necessarily identical in parameters)
3170 sp<IOProfile> profile = getInputProfile(
3171 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3172 if (profile == nullptr) {
3173 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003174 }
jiabin2fd710d2022-05-02 23:20:22 +00003175
Glenn Kasten05ddca52016-02-11 08:17:12 -08003176 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003177 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003178 if (samplingRate == 0) {
3179 samplingRate = profileSamplingRate;
3180 }
Eric Laurente552edb2014-03-10 17:42:56 -07003181
Eric Laurent322b4d22015-04-03 15:57:54 -07003182 if (profile->getModuleHandle() == 0) {
3183 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003184 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003185 }
3186
Eric Laurentec376dc2021-04-08 20:41:22 +02003187 // Reuse an already opened input if a client with the same session ID already exists
3188 // on that input
3189 for (size_t i = 0; i < mInputs.size(); i++) {
3190 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3191 if (desc->mProfile != profile) {
3192 continue;
3193 }
3194 RecordClientVector clients = desc->clientsList();
3195 for (const auto &client : clients) {
3196 if (session == client->session()) {
3197 return desc->mIoHandle;
3198 }
3199 }
3200 }
3201
Eric Laurentc71b11b2024-06-03 12:54:53 +00003202 bool isPreemptor = false;
Eric Laurent3974e3b2017-12-07 17:58:43 -08003203 if (!profile->canOpenNewIo()) {
Eric Laurentc71b11b2024-06-03 12:54:53 +00003204 if (com::android::media::audioserver::fix_input_sharing_logic()) {
3205 // First pick best candidate for preemption (there may not be any):
3206 // - Preempt and input if:
3207 // - It has only strictly lower priority use cases than the new client
3208 // - It has equal priority use cases than the new client, was not
3209 // opened thanks to preemption or has been active since opened.
3210 // - Order the preemption candidates by inactive first and priority second
3211 sp<AudioInputDescriptor> closeCandidate;
3212 int leastCloseRank = INT_MAX;
3213 static const int sCloseActive = 0x100;
3214
3215 for (size_t i = 0; i < mInputs.size(); i++) {
3216 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3217 if (desc->mProfile != profile) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003218 continue;
3219 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003220 sp<RecordClientDescriptor> topPrioClient = desc->getHighestPriorityClient();
3221 if (topPrioClient == nullptr) {
3222 continue;
3223 }
3224 int topPrio = source_priority(topPrioClient->source());
3225 if (topPrio < source_priority(attributes.source)
3226 || (topPrio == source_priority(attributes.source)
3227 && !desc->isPreemptor())) {
3228 int closeRank = (desc->isActive() ? sCloseActive : 0) + topPrio;
3229 if (closeRank < leastCloseRank) {
3230 leastCloseRank = closeRank;
3231 closeCandidate = desc;
3232 }
3233 }
3234 }
3235
3236 if (closeCandidate != nullptr) {
3237 closeInput(closeCandidate->mIoHandle);
3238 // Mark the new input as being issued from a preemption
3239 // so that is will not be preempted later
3240 isPreemptor = true;
3241 } else {
3242 // Then pick the best reusable input (There is always one)
3243 // The order of preference is:
3244 // 1) active inputs with same use case as the new client
3245 // 2) inactive inputs with same use case
3246 // 3) active inputs with different use cases
3247 // 4) inactive inputs with different use cases
3248 sp<AudioInputDescriptor> reuseCandidate;
3249 int leastReuseRank = INT_MAX;
3250 static const int sReuseDifferentUseCase = 0x100;
3251
3252 for (size_t i = 0; i < mInputs.size(); i++) {
3253 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3254 if (desc->mProfile != profile) {
3255 continue;
3256 }
3257 int reuseRank = sReuseDifferentUseCase;
3258 for (const auto& client: desc->getClientIterable()) {
3259 if (client->source() == attributes.source) {
3260 reuseRank = 0;
3261 break;
3262 }
3263 }
3264 reuseRank += desc->isActive() ? 0 : 1;
3265 if (reuseRank < leastReuseRank) {
3266 leastReuseRank = reuseRank;
3267 reuseCandidate = desc;
3268 }
3269 }
3270 return reuseCandidate->mIoHandle;
3271 }
3272 } else { // fix_input_sharing_logic()
3273 for (size_t i = 0; i < mInputs.size(); ) {
3274 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
3275 if (desc->mProfile != profile) {
3276 i++;
3277 continue;
3278 }
3279 // if sound trigger, reuse input if used by other sound trigger on same session
3280 // else
3281 // reuse input if active client app is not in IDLE state
3282 //
3283 RecordClientVector clients = desc->clientsList();
3284 bool doClose = false;
3285 for (const auto& client : clients) {
3286 if (isSoundTrigger != client->isSoundTrigger()) {
3287 continue;
3288 }
3289 if (client->isSoundTrigger()) {
3290 if (session == client->session()) {
3291 return desc->mIoHandle;
3292 }
3293 continue;
3294 }
3295 if (client->active() && client->appState() != APP_STATE_IDLE) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003296 return desc->mIoHandle;
3297 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003298 doClose = true;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003299 }
Eric Laurentc71b11b2024-06-03 12:54:53 +00003300 if (doClose) {
3301 closeInput(desc->mIoHandle);
3302 } else {
3303 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003304 }
Eric Laurent4eb58f12018-12-07 16:41:02 -08003305 }
3306 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003307 }
3308
Eric Laurentc71b11b2024-06-03 12:54:53 +00003309 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
3310 profile, mpClientInterface, isPreemptor);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003311
Eric Laurentfe231122017-11-17 17:48:06 -08003312 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3313 lConfig.sample_rate = profileSamplingRate;
3314 lConfig.channel_mask = profileChannelMask;
3315 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003316
François Gaffie11d30102018-11-02 16:09:09 +01003317 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003318
3319 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003320 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003321 (profileSamplingRate != lConfig.sample_rate) ||
3322 !audio_formats_match(profileFormat, lConfig.format) ||
3323 (profileChannelMask != lConfig.channel_mask)) {
3324 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003325 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003326 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003327 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003328 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003329 }
Eric Laurent599c7582015-12-07 18:05:55 -08003330 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003331 }
3332
Eric Laurentc722f302014-12-10 11:21:49 -08003333 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003334
Eric Laurent599c7582015-12-07 18:05:55 -08003335 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003336 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003337
Eric Laurent599c7582015-12-07 18:05:55 -08003338 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003339}
3340
Eric Laurent4eb58f12018-12-07 16:41:02 -08003341status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003342{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003343 ALOGV("%s portId %d", __FUNCTION__, portId);
3344
3345 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3346 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003347 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003348 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003349 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003350 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003351 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003352 if (client->active()) {
3353 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3354 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003355 }
3356
Eric Laurent8f42ea12018-08-08 09:08:25 -07003357 audio_session_t session = client->session();
3358
Eric Laurent4eb58f12018-12-07 16:41:02 -08003359 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003360
Eric Laurent4eb58f12018-12-07 16:41:02 -08003361 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003362
Eric Laurent4eb58f12018-12-07 16:41:02 -08003363 status_t status = inputDesc->start();
3364 if (status != NO_ERROR) {
3365 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003366 }
Eric Laurente552edb2014-03-10 17:42:56 -07003367
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003368 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003369 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003370 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003371
Eric Laurent8f42ea12018-08-08 09:08:25 -07003372 // indicate active capture to sound trigger service if starting capture from a mic on
3373 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003374 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003375 if (device != nullptr) {
3376 status = setInputDevice(input, device, true /* force */);
3377 } else {
3378 ALOGW("%s no new input device can be found for descriptor %d",
3379 __FUNCTION__, inputDesc->getId());
3380 status = BAD_VALUE;
3381 }
Eric Laurente552edb2014-03-10 17:42:56 -07003382
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003383 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003384 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003385 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003386 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003387 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3388 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003389 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003390 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003391
François Gaffie11d30102018-11-02 16:09:09 +01003392 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3393 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003394 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003395 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003396 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003397
Eric Laurent8f42ea12018-08-08 09:08:25 -07003398 // automatically enable the remote submix output when input is started if not
3399 // used by a policy mix of type MIX_TYPE_RECORDERS
3400 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003401 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003402 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003403 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003404 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003405 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3406 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003407 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003408 if (address != "") {
3409 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3410 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003411 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003412 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003413 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003414 } else if (status != NO_ERROR) {
3415 // Restore client activity state.
3416 inputDesc->setClientActive(client, false);
3417 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003418 }
3419
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003420 ALOGV("%s input %d source = %d status = %d exit",
3421 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003422
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003423 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003424}
3425
Eric Laurent8fc147b2018-07-22 19:13:55 -07003426status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003427{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003428 ALOGV("%s portId %d", __FUNCTION__, portId);
3429
3430 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3431 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003432 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurent5d837ea2024-11-15 18:56:01 +00003433 return DEAD_OBJECT;
Eric Laurente552edb2014-03-10 17:42:56 -07003434 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003435 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003436 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003437 if (!client->active()) {
3438 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003439 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003440 }
Carter Hsue6139d52021-07-08 10:30:20 +08003441 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003442 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003443
Eric Laurent8f42ea12018-08-08 09:08:25 -07003444 inputDesc->stop();
3445 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003446 auto current_source = inputDesc->source();
3447 setInputDevice(input, getNewInputDevice(inputDesc),
3448 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003449 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003450 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003451 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003452 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003453 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3454 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003455 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003456 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003457
3458 // automatically disable the remote submix output when input is stopped if not
3459 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003460 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003461 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003462 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003463 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003464 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3465 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003466 }
3467 if (address != "") {
3468 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3469 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003470 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003471 }
3472 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003473 resetInputDevice(input);
3474
3475 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3476 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003477 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3478 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003479 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003480 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003481 }
3482 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003483 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003484 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003485}
3486
Eric Laurent8fc147b2018-07-22 19:13:55 -07003487void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003488{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003489 ALOGV("%s portId %d", __FUNCTION__, portId);
3490
3491 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3492 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003493 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003494 return;
3495 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003496 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003497 audio_io_handle_t input = inputDesc->mIoHandle;
3498
Eric Laurent8f42ea12018-08-08 09:08:25 -07003499 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003500
Andy Hung39efb7a2018-09-26 15:39:28 -07003501 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003502
3503 // If no more clients are present in this session, park effects to an orphan chain
3504 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3505 if (clientsOnSession.size() == 0) {
3506 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3507 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003508 if (inputDesc->getClientCount() > 0) {
3509 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003510 return;
3511 }
3512
Eric Laurent05b90f82014-08-27 15:32:29 -07003513 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003514 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003515 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003516}
3517
Eric Laurent8f42ea12018-08-08 09:08:25 -07003518void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003519{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003520 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003521
3522 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003523 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003524 }
3525}
3526
Eric Laurent8f42ea12018-08-08 09:08:25 -07003527void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3528{
3529 stopInput(portId);
3530 releaseInput(portId);
3531}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003532
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003533bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3534 if (input->clientsList().size() == 0
3535 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3536 return true;
3537 }
3538 for (const auto& client : input->clientsList()) {
3539 sp<DeviceDescriptor> device =
3540 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3541 client->session());
3542 if (!input->supportedDevices().contains(device)) {
3543 return true;
3544 }
3545 }
3546 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3547 return false;
3548}
3549
Eric Laurent0dd51852019-04-19 18:18:58 -07003550void AudioPolicyManager::checkCloseInputs() {
3551 // After connecting or disconnecting an input device, close input if:
3552 // - it has no client (was just opened to check profile) OR
3553 // - none of its supported devices are connected anymore OR
3554 // - one of its clients cannot be routed to one of its supported
3555 // devices anymore. Otherwise update device selection
3556 std::vector<audio_io_handle_t> inputsToClose;
3557 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07003558 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003559 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003560 }
3561 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003562 for (const audio_io_handle_t handle : inputsToClose) {
3563 ALOGV("%s closing input %d", __func__, handle);
3564 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003565 }
Eric Laurentd4692962014-05-05 18:13:44 -07003566}
3567
Vlad Popa87e0e582024-05-20 18:49:20 -07003568status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3569 const char *address __unused,
3570 bool enabled,
3571 audio_stream_type_t streamToDriveAbs)
3572{
Vlad Popa08502d82024-10-22 20:17:47 -07003573 ALOGI("%s: deviceType 0x%X, enabled %d, streamToDriveAbs %d", __func__, deviceType, enabled,
3574 streamToDriveAbs);
3575
Vlad Popa87e0e582024-05-20 18:49:20 -07003576 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
Vlad Popafb0af7c2024-10-29 16:38:37 -07003577 if (enabled) {
3578 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3579 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3580 toString(streamToDriveAbs).c_str());
3581 return BAD_VALUE;
3582 }
3583
3584 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3585 } else {
3586 mAbsoluteVolumeDrivingStreams.erase(deviceType);
Vlad Popa87e0e582024-05-20 18:49:20 -07003587 }
3588
Vlad Popafb0af7c2024-10-29 16:38:37 -07003589 // apply the stream volumes regarding the new absolute mode to all the outputs
3590 for (size_t i = 0; i < mOutputs.size(); i++) {
3591 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
3592 ALOGV("%s: apply stream volumes for portId %d", __func__, desc->getId());
3593 applyStreamVolumes(desc, {deviceType}, static_cast<int>(desc->latency()) * 2);
3594 }
3595
Vlad Popa87e0e582024-05-20 18:49:20 -07003596 return NO_ERROR;
3597}
3598
François Gaffie251c7f02018-11-07 10:41:08 +01003599void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003600{
3601 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003602 if (indexMin < 0 || indexMax < 0) {
3603 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3604 return;
3605 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003606 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003607
3608 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003609 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3610 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003611 continue;
3612 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003613 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003614 }
Eric Laurente552edb2014-03-10 17:42:56 -07003615}
3616
Eric Laurente0720872014-03-11 09:30:41 -07003617status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003618 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003619 bool muted,
François Gaffie53615e22015-03-19 09:24:12 +01003620 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003621{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003622 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003623 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3624 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3625 return NO_ERROR;
3626 }
Jaideep Sharma33173202024-06-18 17:46:45 +05303627 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3628 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Vlad Popa1e865e62024-08-15 19:11:42 -07003629 return setVolumeIndexForAttributes(attributes, index, muted, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003630}
3631
Eric Laurente0720872014-03-11 09:30:41 -07003632status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003633 int *index,
3634 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003635{
François Gaffiec005e562018-11-06 15:04:49 +01003636 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3637 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003638 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003639 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003640 deviceTypes = mEngine->getOutputDevicesForStream(
3641 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003642 }
jiabin9a3361e2019-10-01 09:38:30 -07003643 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003644}
3645
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003646status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003647 int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003648 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003649 audio_devices_t device)
3650{
3651 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003652 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3653 if (group == VOLUME_GROUP_NONE) {
3654 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003655 return BAD_VALUE;
3656 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003657 ALOGV("%s: group %d matching with %s index %d",
3658 __FUNCTION__, group, toString(attributes).c_str(), index);
Eric Laurentc86a3e12024-10-10 14:26:43 +00003659 if (mEngine->getStreamTypeForAttributes(attributes) == AUDIO_STREAM_PATCH) {
3660 ALOGV("%s: cannot change volume for PATCH stream, attrs: %s",
3661 __FUNCTION__, toString(attributes).c_str());
3662 return NO_ERROR;
3663 }
François Gaffiecfe17322018-11-07 13:41:29 +01003664 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003665 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003666 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003667 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3668 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3669 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3670 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003671 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3672
Vlad Popa1e865e62024-08-15 19:11:42 -07003673
3674 status = setVolumeCurveIndex(index, muted, device, curves);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003675 if (status != NO_ERROR) {
3676 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3677 return status;
3678 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003679
jiabin9a3361e2019-10-01 09:38:30 -07003680 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003681 auto curCurvAttrs = curves.getAttributes();
3682 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3683 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003684 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003685 } else if (!curves.getStreamTypes().empty()) {
3686 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003687 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003688 } else {
3689 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3690 return BAD_VALUE;
3691 }
jiabin9a3361e2019-10-01 09:38:30 -07003692 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3693 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003694
François Gaffiecfe17322018-11-07 13:41:29 +01003695 // update volume on all outputs and streams matching the following:
3696 // - The requested stream (or a stream matching for volume control) is active on the output
3697 // - The device (or devices) selected by the engine for this stream includes
3698 // the requested device
3699 // - For non default requested device, currently selected device on the output is either the
3700 // requested device or one of the devices selected by the engine for this stream
3701 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3702 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003703 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003704 for (size_t i = 0; i < mOutputs.size(); i++) {
3705 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003706 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003707
jiabin9a3361e2019-10-01 09:38:30 -07003708 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3709 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003710 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003711
3712 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003713 continue;
3714 }
3715 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3716 curDevices.find(device) == curDevices.end()) {
3717 continue;
3718 }
3719 bool applyVolume = false;
3720 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3721 curSrcDevices.insert(device);
3722 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003723 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3724 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003725 } else {
3726 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3727 }
3728 if (!applyVolume) {
3729 continue; // next output
3730 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003731 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3732 // If a higher priority strategy is active, and the output is routed to a device with a
3733 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003734 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003735 applyVolume = false;
Vlad Popa1e865e62024-08-15 19:11:42 -07003736 bool swMute = com_android_media_audio_ring_my_car() ? curves.isMuted() : (index == 0);
Francois Gaffie593634d2021-06-22 13:31:31 +02003737 // If the volume source is active with higher priority source, ensure at least Sw Muted
Vlad Popa1e865e62024-08-15 19:11:42 -07003738 desc->setSwMute(swMute, vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003739 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3740 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3741 false /*preferredDevice*/);
3742 if (activeClients.empty()) {
3743 continue;
3744 }
3745 bool isPreempted = false;
3746 bool isHigherPriority = productStrategy < strategy;
3747 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003748 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003749 ALOGV("%s: Strategy=%d (\nrequester:\n"
3750 " group %d, volumeGroup=%d attributes=%s)\n"
3751 " higher priority source active:\n"
3752 " volumeGroup=%d attributes=%s) \n"
3753 " on output %zu, bailing out", __func__, productStrategy,
3754 group, group, toString(attributes).c_str(),
3755 client->volumeSource(), toString(client->attributes()).c_str(), i);
3756 applyVolume = false;
3757 isPreempted = true;
3758 break;
3759 }
3760 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003761 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003762 applyVolume = true;
3763 }
3764 }
3765 if (isPreempted || applyVolume) {
3766 break;
3767 }
3768 }
3769 if (!applyVolume) {
3770 continue; // next output
3771 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003772 }
François Gaffieed91f582020-01-31 10:35:37 +01003773 //FIXME: workaround for truncated touch sounds
3774 // delayed volume change for system stream to be removed when the problem is
3775 // handled by system UI
Vlad Popa1e865e62024-08-15 19:11:42 -07003776 status_t volStatus = checkAndSetVolume(curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003777 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003778 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3779 if (volStatus != NO_ERROR) {
3780 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003781 }
3782 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003783
3784 // update voice volume if the an active call route exists
3785 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3786 && (curSrcDevices.find(
3787 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3788 != curSrcDevices.end())) {
3789 bool isVoiceVolSrc;
3790 bool isBtScoVolSrc;
3791 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3792 isVoiceVolSrc, isBtScoVolSrc, __func__)
3793 && (isVoiceVolSrc || isBtScoVolSrc)) {
Vlad Popad80ed572024-11-06 18:28:17 -08003794 bool voiceVolumeManagedByHost = !isBtScoVolSrc &&
chenxin2095559032024-06-15 13:59:29 +08003795 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3796 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurentae6e88c2024-01-10 14:42:57 +01003797 }
3798 }
3799
François Gaffiecfe17322018-11-07 13:41:29 +01003800 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3801 return status;
3802}
3803
François Gaffieaaac0fd2018-11-22 17:56:39 +01003804status_t AudioPolicyManager::setVolumeCurveIndex(int index,
Vlad Popa1e865e62024-08-15 19:11:42 -07003805 bool muted,
François Gaffiecfe17322018-11-07 13:41:29 +01003806 audio_devices_t device,
3807 IVolumeCurves &volumeCurves)
3808{
3809 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3810 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003811 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3812 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003813 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharma33173202024-06-18 17:46:45 +05303814 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3815 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003816 return BAD_VALUE;
3817 }
3818 if (!audio_is_output_device(device)) {
3819 return BAD_VALUE;
3820 }
3821
3822 // Force max volume if stream cannot be muted
3823 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3824
Vlad Popa1e865e62024-08-15 19:11:42 -07003825 ALOGV("%s device %08x, index %d, muted %d", __FUNCTION__ , device, index, muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003826 volumeCurves.addCurrentVolumeIndex(device, index);
Vlad Popa1e865e62024-08-15 19:11:42 -07003827 volumeCurves.setIsMuted(muted);
François Gaffiecfe17322018-11-07 13:41:29 +01003828 return NO_ERROR;
3829}
3830
3831status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3832 int &index,
3833 audio_devices_t device)
3834{
3835 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3836 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003837 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003838 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003839 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003840 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003841 }
jiabin9a3361e2019-10-01 09:38:30 -07003842 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003843}
3844
3845status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3846 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003847 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003848{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003849 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003850 return BAD_VALUE;
3851 }
jiabin9a3361e2019-10-01 09:38:30 -07003852 index = curves.getVolumeIndex(deviceTypes);
3853 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003854 return NO_ERROR;
3855}
3856
3857status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3858 int &index)
3859{
3860 index = getVolumeCurves(attr).getVolumeIndexMin();
3861 return NO_ERROR;
3862}
3863
3864status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3865 int &index)
3866{
3867 index = getVolumeCurves(attr).getVolumeIndexMax();
3868 return NO_ERROR;
3869}
3870
Eric Laurent36829f92017-04-07 19:04:42 -07003871audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003872{
3873 // select one output among several suitable for global effects.
3874 // The priority is as follows:
3875 // 1: An offloaded output. If the effect ends up not being offloadable,
3876 // AudioFlinger will invalidate the track and the offloaded output
3877 // will be closed causing the effect to be moved to a PCM output.
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003878 // 2: Spatializer output if the stereo spatializer feature enabled
3879 // 3: A deep buffer output
3880 // 4: The primary output
3881 // 5: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003882
François Gaffiec005e562018-11-06 15:04:49 +01003883 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3884 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003885 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003886
Eric Laurent36829f92017-04-07 19:04:42 -07003887 if (outputs.size() == 0) {
3888 return AUDIO_IO_HANDLE_NONE;
3889 }
Eric Laurente552edb2014-03-10 17:42:56 -07003890
Eric Laurent36829f92017-04-07 19:04:42 -07003891 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3892 bool activeOnly = true;
3893
3894 while (output == AUDIO_IO_HANDLE_NONE) {
3895 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003896 audio_io_handle_t outputSpatializer = AUDIO_IO_HANDLE_NONE;
Eric Laurent36829f92017-04-07 19:04:42 -07003897 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3898 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3899
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003900 for (audio_io_handle_t outputLoop : outputs) {
3901 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(outputLoop);
Eric Laurent83d17c22019-04-02 17:10:01 -07003902 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003903 continue;
3904 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003905 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003906 activeOnly, outputLoop, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003907 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003908 outputOffloaded = outputLoop;
3909 }
3910 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
3911 if (SpatializerHelper::isStereoSpatializationFeatureEnabled()) {
3912 outputSpatializer = outputLoop;
3913 }
Eric Laurent36829f92017-04-07 19:04:42 -07003914 }
3915 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003916 outputDeepBuffer = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003917 }
3918 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003919 outputPrimary = outputLoop;
Eric Laurent36829f92017-04-07 19:04:42 -07003920 }
3921 }
3922 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3923 output = outputOffloaded;
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00003924 } else if (outputSpatializer != AUDIO_IO_HANDLE_NONE) {
3925 output = outputSpatializer;
Eric Laurent36829f92017-04-07 19:04:42 -07003926 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3927 output = outputDeepBuffer;
3928 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3929 output = outputPrimary;
3930 } else {
3931 output = outputs[0];
3932 }
3933 activeOnly = false;
3934 }
3935
3936 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003937 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3938 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003939 mMusicEffectOutput = output;
3940 }
3941
3942 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003943 return output;
3944}
3945
Eric Laurent36829f92017-04-07 19:04:42 -07003946audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3947{
3948 return selectOutputForMusicEffects();
3949}
3950
Eric Laurente0720872014-03-11 09:30:41 -07003951status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003952 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003953 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003954 int session,
3955 int id)
3956{
Shunkai Yao29d10572024-03-19 04:31:47 +00003957 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003958 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003959 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003960 index = mInputs.indexOfKey(io);
3961 if (index < 0) {
3962 ALOGW("registerEffect() unknown io %d", io);
3963 return INVALID_OPERATION;
3964 }
Eric Laurente552edb2014-03-10 17:42:56 -07003965 }
3966 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003967 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3968 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3969 || strategy == PRODUCT_STRATEGY_NONE));
3970 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003971}
3972
Eric Laurentc241b0d2018-11-28 09:08:49 -08003973status_t AudioPolicyManager::unregisterEffect(int id)
3974{
3975 if (mEffects.getEffect(id) == nullptr) {
3976 return INVALID_OPERATION;
3977 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003978 if (mEffects.isEffectEnabled(id)) {
3979 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3980 setEffectEnabled(id, false);
3981 }
3982 return mEffects.unregisterEffect(id);
3983}
3984
3985status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3986{
3987 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3988 if (effect == nullptr) {
3989 return INVALID_OPERATION;
3990 }
3991
3992 status_t status = mEffects.setEffectEnabled(id, enabled);
3993 if (status == NO_ERROR) {
3994 mInputs.trackEffectEnabled(effect, enabled);
3995 }
3996 return status;
3997}
3998
Eric Laurent6c796322019-04-09 14:13:17 -07003999
4000status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
4001{
4002 mEffects.moveEffects(ids, io);
4003 return NO_ERROR;
4004}
4005
Eric Laurentc75307b2015-03-17 15:29:32 -07004006bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
4007{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01004008 auto vs = toVolumeSource(stream, false);
4009 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07004010}
4011
4012bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
4013{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01004014 auto vs = toVolumeSource(stream, false);
4015 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07004016}
4017
Eric Laurente0720872014-03-11 09:30:41 -07004018bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07004019{
4020 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07004021 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08004022 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07004023 return true;
4024 }
4025 }
4026 return false;
4027}
4028
Eric Laurent275e8e92014-11-30 15:14:47 -08004029// Register a list of custom mixes with their attributes and format.
4030// When a mix is registered, corresponding input and output profiles are
4031// added to the remote submix hw module. The profile contains only the
4032// parameters (sampling rate, format...) specified by the mix.
4033// The corresponding input remote submix device is also connected.
4034//
4035// When a remote submix device is connected, the address is checked to select the
4036// appropriate profile and the corresponding input or output stream is opened.
4037//
4038// When capture starts, getInputForAttr() will:
4039// - 1 look for a mix matching the address passed in attribtutes tags if any
4040// - 2 if none found, getDeviceForInputSource() will:
4041// - 2.1 look for a mix matching the attributes source
4042// - 2.2 if none found, default to device selection by policy rules
4043// At this time, the corresponding output remote submix device is also connected
4044// and active playback use cases can be transferred to this mix if needed when reconnecting
4045// after AudioTracks are invalidated
4046//
4047// When playback starts, getOutputForAttr() will:
4048// - 1 look for a mix matching the address passed in attribtutes tags if any
4049// - 2 if none found, look for a mix matching the attributes usage
4050// - 3 if none found, default to device and output selection by policy rules.
4051
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07004052status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08004053{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004054 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
4055 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004056 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004057 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01004058 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004059 // examine each mix's route type
4060 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004061 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08004062 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
4063 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
4064 ALOGE("Unsupported Policy Mix %zu of %zu: "
4065 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
4066 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004067 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08004068 break;
4069 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08004070 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
4071 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07004072 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004073 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
4074 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004075 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004076 rSubmixModule = mHwModules.getModuleFromName(
4077 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4078 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004079 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08004080 i);
4081 res = INVALID_OPERATION;
4082 break;
4083 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004084 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004085
Eric Laurent97ac8712018-07-27 18:59:02 -07004086 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004087 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07004088 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07004089 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004090 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4091 } else {
4092 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
4093 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07004094 }
François Gaffie036e1e92015-03-19 10:16:24 +01004095
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004096 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004097 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004098 res = INVALID_OPERATION;
4099 break;
4100 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004101 audio_config_t outputConfig = mix.mFormat;
4102 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07004103 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
4104 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004105 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
4106 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07004107 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004108 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
4109 audio_is_linear_pcm(outputConfig.format)
4110 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07004111 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11004112 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
4113 audio_is_linear_pcm(inputConfig.format)
4114 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01004115
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004116 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07004117 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004118 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07004119 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004120 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07004121 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004122 }
Eric Laurent97ac8712018-07-27 18:59:02 -07004123 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
4124 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08004125 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004126 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004127 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08004128
4129 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
4130 mix.mDeviceType, mix.mDeviceAddress,
4131 String8(), AUDIO_FORMAT_DEFAULT);
4132 if (device == nullptr) {
4133 res = INVALID_OPERATION;
4134 break;
4135 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004136
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004137 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07004138 // First try to find an already opened output supporting the device
4139 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004140 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08004141
Eric Laurentc529cf62020-04-17 18:19:10 -07004142 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004143 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08004144 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004145 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004146 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004147 } else {
4148 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004149 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004150 }
4151 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004152 // If no output found, try to find a direct output profile supporting the device
4153 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
4154 sp<HwModule> module = mHwModules[i];
4155 for (size_t j = 0;
4156 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
4157 j++) {
4158 sp<IOProfile> profile = module->getOutputProfiles()[j];
4159 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
4160 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
4161 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004162 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004163 res = INVALID_OPERATION;
4164 } else {
4165 foundOutput = true;
4166 }
4167 }
4168 }
4169 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004170 if (res != NO_ERROR) {
4171 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004172 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004173 res = INVALID_OPERATION;
4174 break;
4175 } else if (!foundOutput) {
4176 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004177 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004178 res = INVALID_OPERATION;
4179 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004180 } else {
4181 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004182 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004183 }
Eric Laurentc722f302014-12-10 11:21:49 -08004184 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004185 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004186 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004187 if (audio_flags::audio_mix_ownership()) {
4188 // Only unregister mixes that were actually registered to not accidentally unregister
4189 // mixes that already existed previously.
4190 unregisterPolicyMixes(registeredMixes);
4191 registeredMixes.clear();
4192 } else {
4193 unregisterPolicyMixes(mixes);
4194 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004195 } else if (checkOutputs) {
4196 checkForDeviceAndOutputChanges();
4197 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004198 }
4199 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004200}
4201
4202status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4203{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004204 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004205 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004206 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004207 sp<HwModule> rSubmixModule;
4208 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004209 for (const auto& mix : mixes) {
4210 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004211
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004212 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004213 rSubmixModule = mHwModules.getModuleFromName(
4214 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4215 if (rSubmixModule == 0) {
4216 res = INVALID_OPERATION;
4217 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004218 }
4219 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004220
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004221 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004222
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004223 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004224 res = INVALID_OPERATION;
4225 continue;
4226 }
4227
Marvin Ramin0783e202024-03-05 12:45:50 +01004228 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004229 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004230 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4231 status_t currentRes =
4232 setDeviceConnectionStateInt(device,
4233 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4234 address.c_str(),
4235 "remote-submix",
4236 AUDIO_FORMAT_DEFAULT);
4237 if (!audio_flags::audio_mix_ownership()) {
4238 res = currentRes;
4239 }
4240 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004241 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004242 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004243 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004244 }
4245 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004246 }
jiabin5740f082019-08-19 15:08:30 -07004247 rSubmixModule->removeOutputProfile(address.c_str());
4248 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004249
Kevin Rocard153f92d2018-12-18 18:33:28 -08004250 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004251 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004252 res = INVALID_OPERATION;
4253 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004254 } else {
4255 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004256 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004257 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004258 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004259
4260 if (res == NO_ERROR && checkOutputs) {
4261 checkForDeviceAndOutputChanges();
4262 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004263 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004264 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004265}
4266
Marvin Raminbdefaf02023-11-01 09:10:32 +01004267status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4268 if (!audio_flags::audio_mix_test_api()) {
4269 return INVALID_OPERATION;
4270 }
4271
4272 _aidl_return.clear();
4273 _aidl_return.reserve(mPolicyMixes.size());
4274 for (const auto &policyMix: mPolicyMixes) {
4275 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4276 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4277 policyMix->mCbFlags);
4278 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004279 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004280 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004281 }
4282
Vlad Popaa5d73f32024-03-08 16:05:38 -08004283 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004284 return OK;
4285}
4286
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004287status_t AudioPolicyManager::updatePolicyMix(
4288 const AudioMix& mix,
4289 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4290 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4291 if (res == NO_ERROR) {
4292 checkForDeviceAndOutputChanges();
4293 updateCallAndOutputRouting();
4294 }
4295 return res;
4296}
4297
Mikhail Naganov100f0122018-11-29 11:22:16 -08004298void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4299{
4300 size_t i = 0;
4301 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4302 for (const auto& fmt : mManualSurroundFormats) {
4303 if (i++ != 0) dst->append(", ");
4304 std::string sfmt;
4305 FormatConverter::toString(fmt, sfmt);
4306 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4307 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4308 }
4309}
4310
Eric Laurentc529cf62020-04-17 18:19:10 -07004311// Returns true if all devices types match the predicate and are supported by one HW module
4312bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004313 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004314 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004315 const char *context,
4316 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004317 for (size_t i = 0; i < devices.size(); i++) {
4318 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004319 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004320 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004321 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004322 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004323 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004324 return false;
4325 }
4326 }
4327 return true;
4328}
4329
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004330void AudioPolicyManager::changeOutputDevicesMuteState(
4331 const AudioDeviceTypeAddrVector& devices) {
4332 ALOGVV("%s() num devices %zu", __func__, devices.size());
4333
4334 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4335 getSoftwareOutputsForDevices(devices);
4336
4337 for (size_t i = 0; i < outputs.size(); i++) {
4338 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4339 DeviceVector prevDevices = outputDesc->devices();
4340 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4341 }
4342}
4343
4344std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4345 const AudioDeviceTypeAddrVector& devices) const
4346{
4347 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4348 DeviceVector deviceDescriptors;
4349 for (size_t j = 0; j < devices.size(); j++) {
4350 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4351 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4352 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4353 ALOGE("%s: device type %#x address %s not supported or not an output device",
4354 __func__, devices[j].mType, devices[j].getAddress());
4355 continue;
4356 }
4357 deviceDescriptors.add(desc);
4358 }
4359 for (size_t i = 0; i < mOutputs.size(); i++) {
4360 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4361 continue;
4362 }
4363 outputs.push_back(mOutputs.valueAt(i));
4364 }
4365 return outputs;
4366}
4367
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004368status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004369 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004370 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004371 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4372 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004373 }
4374 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004375 if (res != NO_ERROR) {
4376 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4377 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004378 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004379
4380 checkForDeviceAndOutputChanges();
4381 updateCallAndOutputRouting();
4382
4383 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004384}
4385
4386status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4387 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004388 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4389 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004390 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004391 __FUNCTION__, uid);
4392 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004393 }
4394
Eric Laurentc529cf62020-04-17 18:19:10 -07004395 checkForDeviceAndOutputChanges();
4396 updateCallAndOutputRouting();
4397
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004398 return res;
4399}
4400
Eric Laurent2517af32020-11-25 15:31:27 +01004401
jiabin0a488932020-08-07 17:32:40 -07004402status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4403 device_role_t role,
4404 const AudioDeviceTypeAddrVector &devices) {
4405 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4406 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004407
Eric Laurentc529cf62020-04-17 18:19:10 -07004408 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004409 return BAD_VALUE;
4410 }
jiabin0a488932020-08-07 17:32:40 -07004411 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004412 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004413 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4414 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004415 return status;
4416 }
4417
4418 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004419
4420 bool forceVolumeReeval = false;
4421 // FIXME: workaround for truncated touch sounds
4422 // to be removed when the problem is handled by system UI
4423 uint32_t delayMs = 0;
4424 if (strategy == mCommunnicationStrategy) {
4425 forceVolumeReeval = true;
4426 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4427 updateInputRouting();
4428 }
4429 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004430
4431 return NO_ERROR;
4432}
4433
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004434void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4435 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004436{
4437 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004438 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004439 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004440 // Only apply special touch sound delay once
4441 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004442 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004443 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004444 for (size_t i = 0; i < mOutputs.size(); i++) {
4445 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4446 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004447 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4448 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004449 // As done in setDeviceConnectionState, we could also fix default device issue by
4450 // preventing the force re-routing in case of default dev that distinguishes on address.
4451 // Let's give back to engine full device choice decision however.
jiabin2361ed82024-09-20 17:36:31 +00004452 bool newDevicesNotEmpty = !newDevices.isEmpty();
4453 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()
4454 && newDevicesNotEmpty) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004455 // If the device is using preferred mixer attributes, the output need to reopen
4456 // with default configuration when the new selected devices are different from
4457 // current routing devices.
4458 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4459 continue;
4460 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304461
jiabin2361ed82024-09-20 17:36:31 +00004462 waitMs = setOutputDevices(__func__, outputDesc, newDevices,
4463 newDevicesNotEmpty /*force*/, delayMs,
4464 nullptr /*patchHandle*/, !skipDelays /*requiresMuteCheck*/,
4465 !newDevicesNotEmpty /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004466 // Only apply special touch sound delay once
4467 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004468 }
4469 if (forceVolumeReeval && !newDevices.isEmpty()) {
4470 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4471 }
4472 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004473 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004474 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004475}
4476
Eric Laurent2517af32020-11-25 15:31:27 +01004477void AudioPolicyManager::updateInputRouting() {
4478 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304479 // Skip for hotword recording as the input device switch
4480 // is handled within sound trigger HAL
4481 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4482 continue;
4483 }
Eric Laurent2517af32020-11-25 15:31:27 +01004484 auto newDevice = getNewInputDevice(activeDesc);
4485 // Force new input selection if the new device can not be reached via current input
4486 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4487 setInputDevice(activeDesc->mIoHandle, newDevice);
4488 } else {
4489 closeInput(activeDesc->mIoHandle);
4490 }
4491 }
4492}
4493
Paul Wang5d7cdb52022-11-22 09:45:06 +00004494status_t
4495AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4496 device_role_t role,
4497 const AudioDeviceTypeAddrVector &devices) {
4498 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4499 dumpAudioDeviceTypeAddrVector(devices).c_str());
4500
Eric Laurent78fedbf2023-03-09 14:40:44 +01004501 if (!areAllDevicesSupported(
4502 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004503 return BAD_VALUE;
4504 }
4505 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4506 if (status != NO_ERROR) {
4507 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4508 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4509 return status;
4510 }
4511
4512 checkForDeviceAndOutputChanges();
4513
4514 bool forceVolumeReeval = false;
4515 // TODO(b/263479999): workaround for truncated touch sounds
4516 // to be removed when the problem is handled by system UI
4517 uint32_t delayMs = 0;
4518 if (strategy == mCommunnicationStrategy) {
4519 forceVolumeReeval = true;
4520 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4521 updateInputRouting();
4522 }
4523 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4524
4525 return NO_ERROR;
4526}
4527
4528status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4529 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004530{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004531 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004532
Paul Wang5d7cdb52022-11-22 09:45:06 +00004533 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004534 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004535 ALOGW_IF(status != NAME_NOT_FOUND,
4536 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004537 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004538 return status;
4539 }
4540
4541 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004542
4543 bool forceVolumeReeval = false;
4544 // FIXME: workaround for truncated touch sounds
4545 // to be removed when the problem is handled by system UI
4546 uint32_t delayMs = 0;
4547 if (strategy == mCommunnicationStrategy) {
4548 forceVolumeReeval = true;
4549 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4550 updateInputRouting();
4551 }
4552 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004553
4554 return NO_ERROR;
4555}
4556
jiabin0a488932020-08-07 17:32:40 -07004557status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4558 device_role_t role,
4559 AudioDeviceTypeAddrVector &devices) {
4560 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004561}
4562
Jiabin Huang3b98d322020-09-03 17:54:16 +00004563status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4564 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4565 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4566 dumpAudioDeviceTypeAddrVector(devices).c_str());
4567
Mikhail Naganov55773032020-10-01 15:08:13 -07004568 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004569 return BAD_VALUE;
4570 }
4571 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4572 ALOGW_IF(status != NO_ERROR,
4573 "Engine could not set preferred devices %s for audio source %d role %d",
4574 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4575
Wenyu Zhang47655d22024-10-01 12:24:53 +00004576 if (status == NO_ERROR) {
4577 updateInputRouting();
4578 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004579 return status;
4580}
4581
4582status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4583 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4584 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4585 dumpAudioDeviceTypeAddrVector(devices).c_str());
4586
Mikhail Naganov55773032020-10-01 15:08:13 -07004587 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004588 return BAD_VALUE;
4589 }
4590 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4591 ALOGW_IF(status != NO_ERROR,
4592 "Engine could not add preferred devices %s for audio source %d role %d",
4593 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4594
Eric Laurent2517af32020-11-25 15:31:27 +01004595 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004596 return status;
4597}
4598
4599status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4600 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4601{
4602 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4603 dumpAudioDeviceTypeAddrVector(devices).c_str());
4604
Eric Laurent78fedbf2023-03-09 14:40:44 +01004605 if (!areAllDevicesSupported(
4606 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004607 return BAD_VALUE;
4608 }
4609
4610 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4611 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004612 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004613 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004614 if (status == NO_ERROR) {
4615 updateInputRouting();
4616 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004617 return status;
4618}
4619
4620status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4621 device_role_t role) {
4622 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4623
4624 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004625 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004626 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004627 if (status == NO_ERROR) {
4628 updateInputRouting();
4629 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004630 return status;
4631}
4632
4633status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4634 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4635 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4636}
4637
Oscar Azucena90e77632019-11-27 17:12:28 -08004638status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004639 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004640 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004641 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4642 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004643 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004644 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4645 if (status != NO_ERROR) {
4646 ALOGE("%s() could not set device affinity for userId %d",
4647 __FUNCTION__, userId);
4648 return status;
4649 }
4650
4651 // reevaluate outputs for all devices
4652 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004653 changeOutputDevicesMuteState(devices);
4654 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4655 true /* skipDelays */);
4656 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004657
4658 return NO_ERROR;
4659}
4660
4661status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004662 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004663 AudioDeviceTypeAddrVector devices;
4664 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004665 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4666 if (status != NO_ERROR) {
4667 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4668 __FUNCTION__, userId);
4669 return status;
4670 }
4671
4672 // reevaluate outputs for all devices
4673 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004674 changeOutputDevicesMuteState(devices);
4675 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4676 true /* skipDelays */);
4677 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004678
4679 return NO_ERROR;
4680}
4681
Andy Hungc29d82b2018-10-05 12:23:17 -07004682void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004683{
Andy Hungc29d82b2018-10-05 12:23:17 -07004684 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004685 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004686 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004687 std::string stateLiteral;
4688 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004689 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004690 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4691 "communications", "media", "record", "dock", "system",
4692 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4693 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4694 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004695 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4696 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4697 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4698 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4699 dst->append(" (MANUAL: ");
4700 dumpManualSurroundFormats(dst);
4701 dst->append(")");
4702 }
4703 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004704 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004705 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4706 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004707 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004708 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004709
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004710 dst->append("\n");
4711 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4712 dst->append("\n");
4713 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004714 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004715 mOutputs.dump(dst);
4716 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004717 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004718 mAudioPatches.dump(dst);
4719 mPolicyMixes.dump(dst);
4720 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004721
Kevin Rocardb99cc752019-03-21 20:52:24 -07004722 dst->appendFormat(" AllowedCapturePolicies:\n");
4723 for (auto& policy : mAllowedCapturePolicies) {
4724 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4725 }
4726
jiabina84c3d32022-12-02 18:59:55 +00004727 dst->appendFormat(" Preferred mixer audio configuration:\n");
4728 for (const auto it : mPreferredMixerAttrInfos) {
4729 dst->appendFormat(" - device port id: %d\n", it.first);
4730 for (const auto preferredMixerInfoIt : it.second) {
4731 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4732 preferredMixerInfoIt.second->dump(dst);
4733 }
4734 }
4735
François Gaffiec005e562018-11-06 15:04:49 +01004736 dst->appendFormat("\nPolicy Engine dump:\n");
4737 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004738
4739 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4740 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4741 dst->appendFormat(" - device type: %s, driving stream %d\n",
4742 dumpDeviceTypes({it.first}).c_str(),
4743 mEngine->getVolumeGroupForAttributes(it.second));
4744 }
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00004745
4746 // dump mmap policy by device
4747 dst->appendFormat("\nMmap policy:\n");
4748 for (const auto& [policyType, policyByDevice] : mMmapPolicyByDeviceType) {
4749 std::stringstream ss;
4750 ss << '{';
4751 for (const auto& [deviceType, policy] : policyByDevice) {
4752 ss << deviceType.toString() << ":" << toString(policy) << " ";
4753 }
4754 ss << '}';
4755 dst->appendFormat(" - %s: %s\n", toString(policyType).c_str(), ss.str().c_str());
4756 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004757}
4758
4759status_t AudioPolicyManager::dump(int fd)
4760{
4761 String8 result;
4762 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004763 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004764 return NO_ERROR;
4765}
4766
Kevin Rocardb99cc752019-03-21 20:52:24 -07004767status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4768{
4769 mAllowedCapturePolicies[uid] = capturePolicy;
4770 return NO_ERROR;
4771}
4772
Eric Laurente552edb2014-03-10 17:42:56 -07004773// This function checks for the parameters which can be offloaded.
4774// This can be enhanced depending on the capability of the DSP and policy
4775// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004776audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004777{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004778 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004779 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004780 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004781 offloadInfo.format,
4782 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4783 offloadInfo.has_video);
4784
jiabin2b9d5a12021-12-10 01:06:29 +00004785 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004786 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004787 }
4788
4789 // See if there is a profile to support this.
4790 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004791 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004792 offloadInfo.sample_rate,
4793 offloadInfo.format,
4794 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004795 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4796 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004797 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4798 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4799 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004800 if (profile == nullptr) {
4801 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4802 }
4803 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4804 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4805 }
4806 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004807}
4808
Michael Chana94fbb22018-04-24 14:31:19 +10004809bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4810 const audio_attributes_t& attributes) {
4811 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004812 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004813 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4814 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004815 config.sample_rate,
4816 config.format,
4817 config.channel_mask,
4818 output_flags,
4819 true /* directOnly */);
4820 ALOGV("%s() profile %sfound with name: %s, "
4821 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4822 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004823 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004824 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004825
4826 // also try the MSD module if compatible profile not found
4827 if (profile == nullptr) {
4828 profile = getMsdProfileForOutput(outputDevices,
4829 config.sample_rate,
4830 config.format,
4831 config.channel_mask,
4832 output_flags,
4833 true /* directOnly */);
4834 ALOGV("%s() MSD profile %sfound with name: %s, "
4835 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4836 __FUNCTION__, profile != 0 ? "" : "NOT ",
4837 (profile != 0 ? profile->getTagName().c_str() : "null"),
4838 config.sample_rate, config.format, config.channel_mask, output_flags);
4839 }
4840 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004841}
4842
jiabin2b9d5a12021-12-10 01:06:29 +00004843bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4844 bool durationIgnored) {
4845 if (mMasterMono) {
4846 return false; // no offloading if mono is set.
4847 }
4848
4849 // Check if offload has been disabled
4850 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4851 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4852 return false;
4853 }
4854
4855 // Check if stream type is music, then only allow offload as of now.
4856 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4857 {
4858 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4859 return false;
4860 }
4861
4862 //TODO: enable audio offloading with video when ready
4863 const bool allowOffloadWithVideo =
4864 property_get_bool("audio.offload.video", false /* default_value */);
4865 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4866 ALOGV("%s: has_video == true, returning false", __func__);
4867 return false;
4868 }
4869
4870 //If duration is less than minimum value defined in property, return false
4871 const int min_duration_secs = property_get_int32(
4872 "audio.offload.min.duration.secs", -1 /* default_value */);
4873 if (!durationIgnored) {
4874 if (min_duration_secs >= 0) {
4875 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4876 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4877 __func__, min_duration_secs);
4878 return false;
4879 }
4880 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4881 ALOGV("%s: Offload denied by duration < default min(=%u)",
4882 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4883 return false;
4884 }
4885 }
4886
4887 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4888 // creating an offloaded track and tearing it down immediately after start when audioflinger
4889 // detects there is an active non offloadable effect.
4890 // FIXME: We should check the audio session here but we do not have it in this context.
4891 // This may prevent offloading in rare situations where effects are left active by apps
4892 // in the background.
4893 if (mEffects.isNonOffloadableEffectEnabled()) {
4894 return false;
4895 }
4896
4897 return true;
4898}
4899
4900audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4901 const audio_config_t *config) {
4902 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4903 offloadInfo.format = config->format;
4904 offloadInfo.sample_rate = config->sample_rate;
4905 offloadInfo.channel_mask = config->channel_mask;
4906 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4907 offloadInfo.has_video = false;
4908 offloadInfo.is_streaming = false;
4909 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4910
4911 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4912 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4913 audio_flags_to_audio_output_flags(attr->flags, &flags);
4914 // only retain flags that will drive compressed offload or passthrough
4915 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4916 if (offloadPossible) {
4917 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4918 }
4919 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4920
Dorin Drimusfae3c642022-03-17 18:36:30 +01004921 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin8a096672024-09-18 18:20:24 +00004922 if (std::any_of(engineOutputDevices.begin(), engineOutputDevices.end(),
4923 [this, attr](sp<DeviceDescriptor> device) {
4924 return getPreferredMixerAttributesInfo(
4925 device->getId(),
4926 mEngine->getProductStrategyForAttributes(*attr),
4927 true /*activeBitPerfectPreferred*/) != nullptr;
4928 })) {
4929 // Bit-perfect playback is active on one of the selected devices, direct output will
4930 // be rejected at this instant.
4931 return AUDIO_DIRECT_NOT_SUPPORTED;
4932 }
jiabin2b9d5a12021-12-10 01:06:29 +00004933 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004934 DeviceVector outputDevices = engineOutputDevices;
4935 // the MSD module checks for different conditions and output devices
4936 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4937 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4938 continue;
4939 }
4940 outputDevices = getMsdAudioOutDevices();
4941 }
jiabin2b9d5a12021-12-10 01:06:29 +00004942 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004943 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004944 config->sample_rate, nullptr /*updatedSamplingRate*/,
4945 config->format, nullptr /*updatedFormat*/,
4946 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004947 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004948 continue;
4949 }
4950 // reject profiles not corresponding to a device currently available
4951 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4952 continue;
4953 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004954 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4955 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004956 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004957 != AUDIO_DIRECT_NOT_SUPPORTED) {
4958 // Already reports offload gapless supported. No need to report offload support.
4959 continue;
4960 }
4961 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4962 != AUDIO_OUTPUT_FLAG_NONE) {
4963 // If offload gapless is reported, no need to report offload support.
4964 directMode = (audio_direct_mode_t) ((directMode &
4965 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4966 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4967 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004968 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004969 }
4970 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004971 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004972 }
4973 }
4974 }
4975 return directMode;
4976}
4977
Dorin Drimusf2196d82022-01-03 12:11:18 +01004978status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4979 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004980 if (mEffects.isNonOffloadableEffectEnabled()) {
4981 return OK;
4982 }
jiabinf1c73972022-04-14 16:28:52 -07004983 DeviceVector devices;
4984 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004985 if (status != OK) {
4986 return status;
4987 }
4988 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4989 if (devices.empty()) {
4990 return OK; // no output devices for the attributes
4991 }
jiabinf1c73972022-04-14 16:28:52 -07004992 return getProfilesForDevices(devices, audioProfilesVector,
4993 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004994}
4995
jiabina84c3d32022-12-02 18:59:55 +00004996status_t AudioPolicyManager::getSupportedMixerAttributes(
4997 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4998 ALOGV("%s, portId=%d", __func__, portId);
4999 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5000 if (deviceDescriptor == nullptr) {
5001 ALOGE("%s the requested device is currently unavailable", __func__);
5002 return BAD_VALUE;
5003 }
jiabin96daffc2023-05-11 17:51:55 +00005004 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5005 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
5006 deviceDescriptor->type());
5007 return BAD_VALUE;
5008 }
jiabina84c3d32022-12-02 18:59:55 +00005009 for (const auto& hwModule : mHwModules) {
5010 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5011 if (curProfile->supportsDevice(deviceDescriptor)) {
5012 curProfile->toSupportedMixerAttributes(&mixerAttrs);
5013 }
5014 }
5015 }
5016 return NO_ERROR;
5017}
5018
5019status_t AudioPolicyManager::setPreferredMixerAttributes(
5020 const audio_attributes_t *attr,
5021 audio_port_handle_t portId,
5022 uid_t uid,
5023 const audio_mixer_attributes_t *mixerAttributes) {
5024 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
5025 "mixerBehavior=%d}, uid=%d, portId=%u",
5026 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
5027 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
5028 mixerAttributes->mixer_behavior, uid, portId);
5029 if (attr->usage != AUDIO_USAGE_MEDIA) {
5030 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
5031 return BAD_VALUE;
5032 }
5033 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
5034 if (deviceDescriptor == nullptr) {
5035 ALOGE("%s the requested device is currently unavailable", __func__);
5036 return BAD_VALUE;
5037 }
5038 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
5039 ALOGE("%s(%d), type=%d, is not a usb output device",
5040 __func__, portId, deviceDescriptor->type());
5041 return BAD_VALUE;
5042 }
5043
5044 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5045 audio_flags_to_audio_output_flags(attr->flags, &flags);
5046 flags = (audio_output_flags_t) (flags |
5047 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
5048 sp<IOProfile> profile = nullptr;
5049 DeviceVector devices(deviceDescriptor);
5050 for (const auto& hwModule : mHwModules) {
5051 for (const auto& curProfile : hwModule->getOutputProfiles()) {
5052 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00005053 && curProfile->getCompatibilityScore(
5054 devices,
5055 mixerAttributes->config.sample_rate,
5056 nullptr /*updatedSamplingRate*/,
5057 mixerAttributes->config.format,
5058 nullptr /*updatedFormat*/,
5059 mixerAttributes->config.channel_mask,
5060 nullptr /*updatedChannelMask*/,
jiabin91beb492024-10-16 21:53:36 +00005061 flags)
jiabin66acc432024-02-06 00:57:36 +00005062 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00005063 profile = curProfile;
5064 break;
5065 }
5066 }
5067 }
5068 if (profile == nullptr) {
5069 ALOGE("%s, there is no compatible profile found", __func__);
5070 return BAD_VALUE;
5071 }
5072
5073 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
5074 sp<PreferredMixerAttributesInfo>::make(
5075 uid, portId, profile, flags, *mixerAttributes);
5076 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5077 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
5078
5079 // If 1) there is any client from the preferred mixer configuration owner that is currently
5080 // active and matches the strategy and 2) current output is on the preferred device and the
5081 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
5082 // configuration.
5083 std::vector<audio_io_handle_t> outputsToReopen;
5084 for (size_t i = 0; i < mOutputs.size(); i++) {
5085 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00005086 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
5087 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00005088 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00005089 } else {
5090 for (const auto &client: output->getActiveClients()) {
5091 if (client->uid() == uid && client->strategy() == strategy) {
5092 client->setIsInvalid();
5093 outputsToReopen.push_back(output->mIoHandle);
5094 }
jiabina84c3d32022-12-02 18:59:55 +00005095 }
5096 }
5097 }
5098 }
5099 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5100 config.sample_rate = mixerAttributes->config.sample_rate;
5101 config.channel_mask = mixerAttributes->config.channel_mask;
5102 config.format = mixerAttributes->config.format;
5103 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005104 sp<SwAudioOutputDescriptor> desc =
5105 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
5106 if (desc == nullptr) {
5107 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
5108 continue;
5109 }
jiabin220eea12024-05-17 17:55:20 +00005110 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00005111 }
5112
5113 return NO_ERROR;
5114}
5115
5116sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00005117 audio_port_handle_t devicePortId,
5118 product_strategy_t strategy,
5119 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00005120 auto it = mPreferredMixerAttrInfos.find(devicePortId);
5121 if (it == mPreferredMixerAttrInfos.end()) {
5122 return nullptr;
5123 }
jiabind9a58d32023-06-01 17:57:30 +00005124 if (activeBitPerfectPreferred) {
5125 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00005126 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00005127 return info;
5128 }
5129 }
jiabina84c3d32022-12-02 18:59:55 +00005130 }
jiabind9a58d32023-06-01 17:57:30 +00005131 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
5132 return strategyMatchedMixerAttrInfoIt == it->second.end()
5133 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00005134}
5135
5136status_t AudioPolicyManager::getPreferredMixerAttributes(
5137 const audio_attributes_t *attr,
5138 audio_port_handle_t portId,
5139 audio_mixer_attributes_t* mixerAttributes) {
5140 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
5141 portId, mEngine->getProductStrategyForAttributes(*attr));
5142 if (info == nullptr) {
5143 return NAME_NOT_FOUND;
5144 }
5145 *mixerAttributes = info->getMixerAttributes();
5146 return NO_ERROR;
5147}
5148
5149status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
5150 audio_port_handle_t portId,
5151 uid_t uid) {
5152 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
5153 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
5154 if (preferredMixerAttrInfo == nullptr) {
5155 return NAME_NOT_FOUND;
5156 }
5157 if (preferredMixerAttrInfo->getUid() != uid) {
5158 ALOGE("%s, requested uid=%d, owned uid=%d",
5159 __func__, uid, preferredMixerAttrInfo->getUid());
5160 return PERMISSION_DENIED;
5161 }
5162 mPreferredMixerAttrInfos[portId].erase(strategy);
5163 if (mPreferredMixerAttrInfos[portId].empty()) {
5164 mPreferredMixerAttrInfos.erase(portId);
5165 }
5166
5167 // Reconfig existing output
5168 std::vector<audio_io_handle_t> potentialOutputsToReopen;
5169 for (size_t i = 0; i < mOutputs.size(); i++) {
5170 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
5171 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
5172 }
5173 }
5174 for (const auto output : potentialOutputsToReopen) {
5175 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
5176 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
5177 preferredMixerAttrInfo->getFlags())) {
5178 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
5179 }
5180 }
5181 return NO_ERROR;
5182}
5183
Eric Laurent6a94d692014-05-20 11:18:06 -07005184status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
5185 audio_port_type_t type,
5186 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08005187 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07005188 unsigned int *generation)
5189{
jiabin19cdba52020-11-24 11:28:58 -08005190 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
5191 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005192 return BAD_VALUE;
5193 }
5194 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08005195 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005196 *num_ports = 0;
5197 }
5198
5199 size_t portsWritten = 0;
5200 size_t portsMax = *num_ports;
5201 *num_ports = 0;
5202 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005203 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5204 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005205 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005206 for (const auto& dev : mAvailableOutputDevices) {
5207 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005208 continue;
5209 }
5210 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005211 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005212 }
5213 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005214 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005215 }
5216 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005217 for (const auto& dev : mAvailableInputDevices) {
5218 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005219 continue;
5220 }
5221 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005222 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005223 }
5224 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005225 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005226 }
5227 }
5228 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5229 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5230 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5231 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5232 }
5233 *num_ports += mInputs.size();
5234 }
5235 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005236 size_t numOutputs = 0;
5237 for (size_t i = 0; i < mOutputs.size(); i++) {
5238 if (!mOutputs[i]->isDuplicated()) {
5239 numOutputs++;
5240 if (portsWritten < portsMax) {
5241 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5242 }
5243 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005244 }
Eric Laurent84c70242014-06-23 08:46:27 -07005245 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005246 }
5247 }
jiabina84c3d32022-12-02 18:59:55 +00005248
Eric Laurent6a94d692014-05-20 11:18:06 -07005249 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005250 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005251 return NO_ERROR;
5252}
5253
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005254status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5255 std::vector<media::AudioPortFw>* _aidl_return) {
5256 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5257 audio_port_v7 port;
5258 dev->toAudioPort(&port);
5259 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5260 _aidl_return->push_back(std::move(aidlPort));
5261 return OK;
5262 };
5263
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005264 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005265 for (const auto& dev : module->getDeclaredDevices()) {
5266 if (role == media::AudioPortRole::NONE ||
5267 ((role == media::AudioPortRole::SOURCE)
5268 == audio_is_input_device(dev->type()))) {
5269 RETURN_STATUS_IF_ERROR(pushPort(dev));
5270 }
5271 }
5272 }
5273 return OK;
5274}
5275
jiabin19cdba52020-11-24 11:28:58 -08005276status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005277{
Eric Laurent99fcae42018-05-17 16:59:18 -07005278 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5279 return BAD_VALUE;
5280 }
5281 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5282 if (dev != 0) {
5283 dev->toAudioPort(port);
5284 return NO_ERROR;
5285 }
5286 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5287 if (dev != 0) {
5288 dev->toAudioPort(port);
5289 return NO_ERROR;
5290 }
5291 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5292 if (out != 0) {
5293 out->toAudioPort(port);
5294 return NO_ERROR;
5295 }
5296 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5297 if (in != 0) {
5298 in->toAudioPort(port);
5299 return NO_ERROR;
5300 }
5301 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005302}
5303
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005304status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5305 audio_patch_handle_t *handle,
5306 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005307{
François Gaffieafd4cea2019-11-18 15:50:22 +01005308 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005309 if (handle == NULL || patch == NULL) {
5310 return BAD_VALUE;
5311 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005312 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005313 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005314 return BAD_VALUE;
5315 }
5316 // only one source per audio patch supported for now
5317 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005318 return INVALID_OPERATION;
5319 }
Eric Laurent874c42872014-08-08 15:13:39 -07005320 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005321 return INVALID_OPERATION;
5322 }
Eric Laurent874c42872014-08-08 15:13:39 -07005323 for (size_t i = 0; i < patch->num_sinks; i++) {
5324 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5325 return INVALID_OPERATION;
5326 }
5327 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005328
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005329 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5330 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5331 if (srcDevice == nullptr || sinkDevice == nullptr) {
5332 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5333 return BAD_VALUE;
5334 }
5335 ALOGV("%s between source %s and sink %s", __func__,
5336 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5337 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5338 // Default attributes, default volume priority, not to infer with non raw audio patches.
5339 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5340 const struct audio_port_config *source = &patch->sources[0];
5341 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005342 new SourceClientDescriptor(
5343 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5344 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00005345 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005346 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005347
5348 status_t status =
5349 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5350
5351 if (status != NO_ERROR) {
5352 return INVALID_OPERATION;
5353 }
5354 mAudioSources.add(portId, sourceDesc);
5355 return NO_ERROR;
5356}
5357
5358status_t AudioPolicyManager::connectAudioSourceToSink(
5359 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5360 const struct audio_patch *patch,
5361 audio_patch_handle_t &handle,
5362 uid_t uid, uint32_t delayMs)
5363{
5364 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5365 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5366 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5367 return INVALID_OPERATION;
5368 }
5369 sourceDesc->connect(handle, sinkDevice);
5370 if (isMsdPatch(handle)) {
5371 return NO_ERROR;
5372 }
5373 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5374 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5375 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5376 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5377 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5378 goto FailurePatchAdded;
5379 }
5380 status = swOutput->start();
5381 if (status != NO_ERROR) {
5382 goto FailureSourceAdded;
5383 }
5384 swOutput->addClient(sourceDesc);
5385 status = startSource(swOutput, sourceDesc, &delayMs);
5386 if (status != NO_ERROR) {
5387 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5388 goto FailureSourceActive;
5389 }
5390 if (delayMs != 0) {
5391 usleep(delayMs * 1000);
5392 }
5393 return NO_ERROR;
5394
5395FailureSourceActive:
5396 swOutput->stop();
5397 releaseOutput(sourceDesc->portId());
5398FailureSourceAdded:
5399 sourceDesc->setSwOutput(nullptr);
5400FailurePatchAdded:
5401 releaseAudioPatchInternal(handle);
5402 return INVALID_OPERATION;
5403}
5404
5405status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5406 audio_patch_handle_t *handle,
5407 uid_t uid, uint32_t delayMs,
5408 const sp<SourceClientDescriptor>& sourceDesc)
5409{
5410 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005411 sp<AudioPatch> patchDesc;
5412 ssize_t index = mAudioPatches.indexOfKey(*handle);
5413
François Gaffieafd4cea2019-11-18 15:50:22 +01005414 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5415 patch->sources[0].role,
5416 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005417#if LOG_NDEBUG == 0
5418 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005419 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5420 patch->sinks[i].role,
5421 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005422 }
5423#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005424
5425 if (index >= 0) {
5426 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005427 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5428 __func__, mUidCached, patchDesc->getUid(), uid);
5429 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005430 return INVALID_OPERATION;
5431 }
5432 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005433 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005434 }
5435
5436 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005437 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005438 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005439 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005440 return BAD_VALUE;
5441 }
Eric Laurent84c70242014-06-23 08:46:27 -07005442 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5443 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005444 if (patchDesc != 0) {
5445 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005446 ALOGV("%s source id differs for patch current id %d new id %d",
5447 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005448 return BAD_VALUE;
5449 }
5450 }
Eric Laurent874c42872014-08-08 15:13:39 -07005451 DeviceVector devices;
5452 for (size_t i = 0; i < patch->num_sinks; i++) {
5453 // Only support mix to devices connection
5454 // TODO add support for mix to mix connection
5455 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005456 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005457 return INVALID_OPERATION;
5458 }
5459 sp<DeviceDescriptor> devDesc =
5460 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5461 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005462 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005463 return BAD_VALUE;
5464 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005465
jiabin66acc432024-02-06 00:57:36 +00005466 if (outputDesc->mProfile->getCompatibilityScore(
5467 DeviceVector(devDesc),
5468 patch->sources[0].sample_rate,
5469 nullptr, // updatedSamplingRate
5470 patch->sources[0].format,
5471 nullptr, // updatedFormat
5472 patch->sources[0].channel_mask,
5473 nullptr, // updatedChannelMask
5474 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005475 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005476 return INVALID_OPERATION;
5477 }
5478 devices.add(devDesc);
5479 }
5480 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005481 return INVALID_OPERATION;
5482 }
Eric Laurent874c42872014-08-08 15:13:39 -07005483
Eric Laurent6a94d692014-05-20 11:18:06 -07005484 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005485 ALOGV("%s setting device %s on output %d",
5486 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305487 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005488 index = mAudioPatches.indexOfKey(*handle);
5489 if (index >= 0) {
5490 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005491 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005492 }
5493 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005494 patchDesc->setUid(uid);
5495 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005496 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005497 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005498 return INVALID_OPERATION;
5499 }
5500 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5501 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5502 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005503 // only one sink supported when connecting an input device to a mix
5504 if (patch->num_sinks > 1) {
5505 return INVALID_OPERATION;
5506 }
François Gaffie53615e22015-03-19 09:24:12 +01005507 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005508 if (inputDesc == NULL) {
5509 return BAD_VALUE;
5510 }
5511 if (patchDesc != 0) {
5512 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5513 return BAD_VALUE;
5514 }
5515 }
François Gaffie11d30102018-11-02 16:09:09 +01005516 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005517 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005518 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005519 return BAD_VALUE;
5520 }
5521
jiabin66acc432024-02-06 00:57:36 +00005522 if (inputDesc->mProfile->getCompatibilityScore(
5523 DeviceVector(device),
5524 patch->sinks[0].sample_rate,
5525 nullptr, /*updatedSampleRate*/
5526 patch->sinks[0].format,
5527 nullptr, /*updatedFormat*/
5528 patch->sinks[0].channel_mask,
5529 nullptr, /*updatedChannelMask*/
5530 // FIXME for the parameter type,
5531 // and the NONE
5532 (audio_output_flags_t)
5533 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005534 return INVALID_OPERATION;
5535 }
5536 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005537 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005538 device->toString().c_str(), inputDesc->mIoHandle);
5539 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005540 index = mAudioPatches.indexOfKey(*handle);
5541 if (index >= 0) {
5542 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005543 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005544 }
5545 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005546 patchDesc->setUid(uid);
5547 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005548 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005549 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005550 return INVALID_OPERATION;
5551 }
5552 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5553 // device to device connection
5554 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005555 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005556 return BAD_VALUE;
5557 }
5558 }
François Gaffie11d30102018-11-02 16:09:09 +01005559 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005560 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005561 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005562 return BAD_VALUE;
5563 }
Eric Laurent874c42872014-08-08 15:13:39 -07005564
Eric Laurent6a94d692014-05-20 11:18:06 -07005565 //update source and sink with our own data as the data passed in the patch may
5566 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005567 PatchBuilder patchBuilder;
5568 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005569
5570 // if first sink is to MSD, establish single MSD patch
5571 if (getMsdAudioOutDevices().contains(
5572 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5573 ALOGV("%s patching to MSD", __FUNCTION__);
5574 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5575 goto installPatch;
5576 }
5577
François Gaffieafd4cea2019-11-18 15:50:22 +01005578 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5579 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005580
Eric Laurent874c42872014-08-08 15:13:39 -07005581 for (size_t i = 0; i < patch->num_sinks; i++) {
5582 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005583 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005584 return INVALID_OPERATION;
5585 }
François Gaffie11d30102018-11-02 16:09:09 +01005586 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005587 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005588 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005589 return BAD_VALUE;
5590 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005591 audio_port_config sinkPortConfig = {};
5592 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5593 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005594
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005595 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5596 // volume management purpose (tracking activity)
5597 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5598 // in config XML to reach the sink so that is can be declared as available.
5599 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005600 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005601 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005602 // take care of dynamic routing for SwOutput selection,
5603 audio_attributes_t attributes = sourceDesc->attributes();
5604 audio_stream_type_t stream = sourceDesc->stream();
5605 audio_attributes_t resultAttr;
5606 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5607 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005608 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5609 config.channel_mask =
5610 (audio_channel_mask_get_representation(sourceMask)
5611 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5612 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005613 config.format = sourceDesc->config().format;
5614 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Robert Wufb971192024-10-30 21:54:35 +00005615 DeviceIdVector selectedDeviceIds;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005616 bool isRequestedDeviceForExclusiveUse = false;
5617 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005618 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005619 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005620 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5621 &stream, sourceDesc->uid(), &config, &flags,
Robert Wufb971192024-10-30 21:54:35 +00005622 &selectedDeviceIds, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005623 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005624 if (output == AUDIO_IO_HANDLE_NONE) {
5625 ALOGV("%s no output for device %s",
5626 __FUNCTION__, sinkDevice->toString().c_str());
5627 return INVALID_OPERATION;
5628 }
5629 outputDesc = mOutputs.valueFor(output);
5630 if (outputDesc->isDuplicated()) {
5631 ALOGE("%s output is duplicated", __func__);
5632 return INVALID_OPERATION;
5633 }
François Gaffie7e39df22022-04-26 12:48:49 +02005634 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5635 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005636 } else {
5637 // Same for "raw patches" aka created from createAudioPatch API
5638 SortedVector<audio_io_handle_t> outputs =
5639 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5640 // if the sink device is reachable via an opened output stream, request to
5641 // go via this output stream by adding a second source to the patch
5642 // description
5643 output = selectOutput(outputs);
5644 if (output == AUDIO_IO_HANDLE_NONE) {
5645 ALOGE("%s no output available for internal patch sink", __func__);
5646 return INVALID_OPERATION;
5647 }
5648 outputDesc = mOutputs.valueFor(output);
5649 if (outputDesc->isDuplicated()) {
5650 ALOGV("%s output for device %s is duplicated",
5651 __func__, sinkDevice->toString().c_str());
5652 return INVALID_OPERATION;
5653 }
François Gaffie7e39df22022-04-26 12:48:49 +02005654 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005655 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005656 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005657 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005658 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005659 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005660 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5661 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005662 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5663 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005664 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005665 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005666 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005667 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005668 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005669 return INVALID_OPERATION;
5670 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005671 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005672 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005673 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005674 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005675 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005676 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurentccbd7872024-06-20 12:34:15 +00005677 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005678 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5679 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005680 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005681 }
Eric Laurent83b88082014-06-20 18:31:16 -07005682 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005683 }
5684 // TODO: check from routing capabilities in config file and other conflicting patches
5685
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005686installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005687 status_t status = installPatch(
5688 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005689 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005690 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005691 return INVALID_OPERATION;
5692 }
5693 } else {
5694 return BAD_VALUE;
5695 }
5696 } else {
5697 return BAD_VALUE;
5698 }
5699 return NO_ERROR;
5700}
5701
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005702status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005703{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005704 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005705 ssize_t index = mAudioPatches.indexOfKey(handle);
5706
5707 if (index < 0) {
5708 return BAD_VALUE;
5709 }
5710 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005711 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5712 __func__, mUidCached, patchDesc->getUid(), uid);
5713 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005714 return INVALID_OPERATION;
5715 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005716 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5717 for (size_t i = 0; i < mAudioSources.size(); i++) {
5718 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5719 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5720 portId = sourceDesc->portId();
5721 break;
5722 }
5723 }
5724 return portId != AUDIO_PORT_HANDLE_NONE ?
5725 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005726}
Eric Laurent6a94d692014-05-20 11:18:06 -07005727
François Gaffieafd4cea2019-11-18 15:50:22 +01005728status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005729 uint32_t delayMs,
5730 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005731{
5732 ALOGV("%s patch %d", __func__, handle);
5733 if (mAudioPatches.indexOfKey(handle) < 0) {
5734 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5735 return BAD_VALUE;
5736 }
5737 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005738 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005739 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005740 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005741 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005742 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005743 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005744 return BAD_VALUE;
5745 }
5746
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305747 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005748 getNewOutputDevices(outputDesc, true /*fromCache*/),
5749 true,
5750 0,
5751 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005752 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5753 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005754 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005755 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005756 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005757 return BAD_VALUE;
5758 }
5759 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005760 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005761 true,
5762 NULL);
5763 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005764 status_t status =
5765 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5766 ALOGV("%s patch panel returned %d patchHandle %d",
5767 __func__, status, patchDesc->getAfHandle());
5768 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005769 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005770 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005771 // SW or HW Bridge
5772 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5773 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005774 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005775 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5776 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5777 outputDesc = sourceDesc->swOutput().promote();
5778 }
5779 if (outputDesc == nullptr) {
5780 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5781 // releaseOutput has already called closeOutput in case of direct output
5782 return NO_ERROR;
5783 }
François Gaffie7e39df22022-04-26 12:48:49 +02005784 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005785 // While using a HwBridge, force reconsidering device only if not reusing an existing
5786 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005787 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005788 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5789 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5790 // Reconsider device only for cases:
5791 // 1 / Active Output
5792 // 2 / Inactive Output previously hosting HwBridge
5793 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5794 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5795 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305796 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005797 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5798 outputDesc->devices(),
5799 force,
5800 0,
5801 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005802 } else {
5803 return BAD_VALUE;
5804 }
5805 } else {
5806 return BAD_VALUE;
5807 }
5808 return NO_ERROR;
5809}
5810
5811status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5812 struct audio_patch *patches,
5813 unsigned int *generation)
5814{
François Gaffie53615e22015-03-19 09:24:12 +01005815 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005816 return BAD_VALUE;
5817 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005818 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005819 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005820}
5821
Eric Laurente1715a42014-05-20 11:30:42 -07005822status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005823{
Eric Laurente1715a42014-05-20 11:30:42 -07005824 ALOGV("setAudioPortConfig()");
5825
5826 if (config == NULL) {
5827 return BAD_VALUE;
5828 }
5829 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5830 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005831 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5832 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005833 }
5834
Eric Laurenta121f902014-06-03 13:32:54 -07005835 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005836 if (config->type == AUDIO_PORT_TYPE_MIX) {
5837 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005838 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005839 if (outputDesc == NULL) {
5840 return BAD_VALUE;
5841 }
Eric Laurent84c70242014-06-23 08:46:27 -07005842 ALOG_ASSERT(!outputDesc->isDuplicated(),
5843 "setAudioPortConfig() called on duplicated output %d",
5844 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005845 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005846 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005847 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005848 if (inputDesc == NULL) {
5849 return BAD_VALUE;
5850 }
Eric Laurenta121f902014-06-03 13:32:54 -07005851 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005852 } else {
5853 return BAD_VALUE;
5854 }
5855 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5856 sp<DeviceDescriptor> deviceDesc;
5857 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5858 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5859 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5860 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5861 } else {
5862 return BAD_VALUE;
5863 }
5864 if (deviceDesc == NULL) {
5865 return BAD_VALUE;
5866 }
Eric Laurenta121f902014-06-03 13:32:54 -07005867 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005868 } else {
5869 return BAD_VALUE;
5870 }
5871
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005872 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005873 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5874 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005875 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005876 audioPortConfig->toAudioPortConfig(&newConfig, config);
5877 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005878 }
Eric Laurenta121f902014-06-03 13:32:54 -07005879 if (status != NO_ERROR) {
5880 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005881 }
Eric Laurente1715a42014-05-20 11:30:42 -07005882
5883 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005884}
5885
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005886void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5887{
Eric Laurentd60560a2015-04-10 11:31:20 -07005888 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005889 clearAudioPatches(uid);
5890 clearSessionRoutes(uid);
5891}
5892
Eric Laurent6a94d692014-05-20 11:18:06 -07005893void AudioPolicyManager::clearAudioPatches(uid_t uid)
5894{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005895 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005896 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005897 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005898 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005899 }
5900 }
5901}
5902
François Gaffiec005e562018-11-06 15:04:49 +01005903void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005904{
François Gaffiec005e562018-11-06 15:04:49 +01005905 // Take the first attributes following the product strategy as it is used to retrieve the routed
5906 // device. All attributes wihin a strategy follows the same "routing strategy"
5907 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5908 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005909 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005910 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005911 for (size_t j = 0; j < mOutputs.size(); j++) {
5912 if (mOutputs.keyAt(j) == ouptutToSkip) {
5913 continue;
5914 }
5915 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005916 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005917 continue;
5918 }
5919 // If the default device for this strategy is on another output mix,
5920 // invalidate all tracks in this strategy to force re connection.
5921 // Otherwise select new device on the output mix.
5922 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005923 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005924 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005925 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005926 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005927 // If the device is using preferred mixer attributes, the output need to reopen
5928 // with default configuration when the new selected devices are different from
5929 // current routing devices.
5930 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5931 continue;
5932 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305933 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005934 }
5935 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005936 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005937}
5938
5939void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5940{
5941 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005942 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005943 for (size_t i = 0; i < mOutputs.size(); i++) {
5944 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005945 for (const auto& client : outputDesc->getClientIterable()) {
5946 if (client->hasPreferredDevice() && client->uid() == uid) {
5947 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005948 auto clientStrategy = client->strategy();
5949 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5950 end(affectedStrategies)) {
5951 continue;
5952 }
5953 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005954 }
5955 }
5956 }
5957 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005958 for (const auto& strategy : affectedStrategies) {
5959 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005960 }
5961
5962 // remove input routes associated with this uid
5963 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005964 for (size_t i = 0; i < mInputs.size(); i++) {
5965 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005966 for (const auto& client : inputDesc->getClientIterable()) {
5967 if (client->hasPreferredDevice() && client->uid() == uid) {
5968 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5969 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005970 }
5971 }
5972 }
5973 // reroute inputs if necessary
5974 SortedVector<audio_io_handle_t> inputsToClose;
5975 for (size_t i = 0; i < mInputs.size(); i++) {
5976 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005977 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005978 inputsToClose.add(inputDesc->mIoHandle);
5979 }
5980 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005981 for (const auto& input : inputsToClose) {
5982 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005983 }
5984}
5985
Eric Laurentd60560a2015-04-10 11:31:20 -07005986void AudioPolicyManager::clearAudioSources(uid_t uid)
5987{
5988 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005989 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5990 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005991 stopAudioSource(mAudioSources.keyAt(i));
5992 }
5993 }
5994}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005995
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005996status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5997 audio_io_handle_t *ioHandle,
5998 audio_devices_t *device)
5999{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08006000 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
6001 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01006002 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00006003 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
6004 if (deviceDesc == nullptr) {
6005 return INVALID_OPERATION;
6006 }
6007 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006008
François Gaffiedf372692015-03-19 10:43:27 +01006009 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07006010}
6011
Eric Laurentd60560a2015-04-10 11:31:20 -07006012status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006013 const audio_attributes_t *attributes,
6014 audio_port_handle_t *portId,
Eric Laurentccbd7872024-06-20 12:34:15 +00006015 uid_t uid) {
6016 return startAudioSourceInternal(source, attributes, portId, uid,
David Lif85c5e32024-07-01 13:14:10 +00006017 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurentccbd7872024-06-20 12:34:15 +00006018}
6019
6020status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
6021 const audio_attributes_t *attributes,
6022 audio_port_handle_t *portId,
David Lif85c5e32024-07-01 13:14:10 +00006023 uid_t uid, bool internal, bool isCallRx,
6024 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07006025{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006026 ALOGV("%s", __FUNCTION__);
6027 *portId = AUDIO_PORT_HANDLE_NONE;
6028
6029 if (source == NULL || attributes == NULL || portId == NULL) {
6030 ALOGW("%s invalid argument: source %p attributes %p handle %p",
6031 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006032 return BAD_VALUE;
6033 }
6034
Eric Laurentd60560a2015-04-10 11:31:20 -07006035 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
6036 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006037 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
6038 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006039 return INVALID_OPERATION;
6040 }
6041
François Gaffie11d30102018-11-02 16:09:09 +01006042 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07006043 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006044 String8(source->ext.device.address),
6045 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01006046 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006047 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07006048 return BAD_VALUE;
6049 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006050
jiabin4ef93452019-09-10 14:29:54 -07006051 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07006052
François Gaffieaaac0fd2018-11-22 17:56:39 +01006053 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01006054 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01006055 mEngine->getStreamTypeForAttributes(*attributes),
6056 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurentccbd7872024-06-20 12:34:15 +00006057 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07006058
David Lif85c5e32024-07-01 13:14:10 +00006059 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07006060 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006061 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07006062 }
6063 return status;
6064}
6065
David Lif85c5e32024-07-01 13:14:10 +00006066status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
6067 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07006068{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006069 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07006070
6071 // make sure we only have one patch per source.
6072 disconnectAudioSource(sourceDesc);
6073
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006074 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006075 // May the device (dynamic) have been disconnected/reconnected, id has changed.
6076 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
6077 sourceDesc->srcDevice()->type(),
6078 String8(sourceDesc->srcDevice()->address().c_str()),
6079 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01006080 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02006081 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01006082 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01006083 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006084 if (!mAvailableOutputDevices.contains(sinkDevice)) {
6085 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
6086 return INVALID_OPERATION;
6087 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006088 PatchBuilder patchBuilder;
6089 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
6090 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01006091
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006092 return connectAudioSourceToSink(
David Lif85c5e32024-07-01 13:14:10 +00006093 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07006094}
6095
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006096status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07006097{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006098 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
6099 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006100 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006101 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006102 return BAD_VALUE;
6103 }
6104 status_t status = disconnectAudioSource(sourceDesc);
6105
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006106 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07006107 return status;
6108}
6109
Andy Hung2ddee192015-12-18 17:34:44 -08006110status_t AudioPolicyManager::setMasterMono(bool mono)
6111{
6112 if (mMasterMono == mono) {
6113 return NO_ERROR;
6114 }
6115 mMasterMono = mono;
6116 // if enabling mono we close all offloaded devices, which will invalidate the
6117 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
6118 // for recreating the new AudioTrack as non-offloaded PCM.
6119 //
6120 // If disabling mono, we leave all tracks as is: we don't know which clients
6121 // and tracks are able to be recreated as offloaded. The next "song" should
6122 // play back offloaded.
6123 if (mMasterMono) {
6124 Vector<audio_io_handle_t> offloaded;
6125 for (size_t i = 0; i < mOutputs.size(); ++i) {
6126 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6127 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
6128 offloaded.push(desc->mIoHandle);
6129 }
6130 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08006131 for (const auto& handle : offloaded) {
6132 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08006133 }
6134 }
6135 // update master mono for all remaining outputs
6136 for (size_t i = 0; i < mOutputs.size(); ++i) {
6137 updateMono(mOutputs.keyAt(i));
6138 }
6139 return NO_ERROR;
6140}
6141
6142status_t AudioPolicyManager::getMasterMono(bool *mono)
6143{
6144 *mono = mMasterMono;
6145 return NO_ERROR;
6146}
6147
Eric Laurentac9cef52017-06-09 15:46:26 -07006148float AudioPolicyManager::getStreamVolumeDB(
6149 audio_stream_type_t stream, int index, audio_devices_t device)
6150{
Vlad Popa9d482762024-06-21 16:40:23 -07006151 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index,
6152 {device}, /* adjustAttenuation= */false);
Eric Laurentac9cef52017-06-09 15:46:26 -07006153}
6154
jiabin81772902018-04-02 17:52:27 -07006155status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
6156 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01006157 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07006158{
Kriti Dang6537def2021-03-02 13:46:59 +01006159 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
6160 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07006161 return BAD_VALUE;
6162 }
Kriti Dang6537def2021-03-02 13:46:59 +01006163 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
6164 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07006165
6166 size_t formatsWritten = 0;
6167 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01006168
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006169 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006170 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
6171 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006172 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07006173 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01006174 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006175 bool formatEnabled = true;
6176 switch (forceUse) {
6177 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01006178 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08006179 break;
6180 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
6181 formatEnabled = false;
6182 break;
6183 default: // AUTO or ALWAYS => true
6184 break;
jiabin81772902018-04-02 17:52:27 -07006185 }
6186 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
6187 }
jiabin81772902018-04-02 17:52:27 -07006188 }
6189 return NO_ERROR;
6190}
6191
Kriti Dang6537def2021-03-02 13:46:59 +01006192status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
6193 audio_format_t *surroundFormats) {
6194 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
6195 return BAD_VALUE;
6196 }
6197 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
6198 __func__, *numSurroundFormats, surroundFormats);
6199
6200 size_t formatsWritten = 0;
6201 size_t formatsMax = *numSurroundFormats;
6202 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6203
6204 // Return formats from all device profiles that have already been resolved by
6205 // checkOutputsForDevice().
6206 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6207 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6208 audio_devices_t deviceType = device->type();
6209 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6210 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006211 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6212 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006213 continue;
6214 }
6215 // Formats reported by sink devices
6216 std::unordered_set<audio_format_t> formatset;
6217 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6218 formatset.insert(it->second.begin(), it->second.end());
6219 }
6220
6221 // Formats hard-coded in the in policy configuration file (if any).
6222 FormatVector encodedFormats = device->encodedFormats();
6223 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6224 // Filter the formats which are supported by the vendor hardware.
6225 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006226 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006227 formats.insert(*it);
6228 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006229 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006230 if (pair.second.count(*it) != 0) {
6231 formats.insert(pair.first);
6232 break;
6233 }
6234 }
6235 }
6236 }
6237 }
6238 *numSurroundFormats = formats.size();
6239 for (const auto& format: formats) {
6240 if (formatsWritten < formatsMax) {
6241 surroundFormats[formatsWritten++] = format;
6242 }
6243 }
6244 return NO_ERROR;
6245}
6246
jiabin81772902018-04-02 17:52:27 -07006247status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6248{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006249 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006250 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6251 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006252 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006253 return BAD_VALUE;
6254 }
6255
Mikhail Naganov100f0122018-11-29 11:22:16 -08006256 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6257 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006258 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006259 return INVALID_OPERATION;
6260 }
6261
Mikhail Naganov100f0122018-11-29 11:22:16 -08006262 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006263 return NO_ERROR;
6264 }
6265
Mikhail Naganov100f0122018-11-29 11:22:16 -08006266 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006267 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006268 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006269 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006270 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006271 }
6272 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006273 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006274 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006275 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006276 }
6277 }
6278
6279 sp<SwAudioOutputDescriptor> outputDesc;
6280 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006281 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6282 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006283 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6284 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006285 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006286 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006287 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006288 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6289 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006290 name.c_str(),
6291 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006292 if (status != NO_ERROR) {
6293 continue;
6294 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006295 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006296 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6297 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006298 name.c_str(),
6299 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006300 profileUpdated |= (status == NO_ERROR);
6301 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006302 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006303 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006304 AUDIO_DEVICE_IN_HDMI);
6305 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6306 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006307 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006308 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006309 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6310 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6311 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006312 name.c_str(),
6313 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006314 if (status != NO_ERROR) {
6315 continue;
6316 }
6317 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6318 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6319 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006320 name.c_str(),
6321 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006322 profileUpdated |= (status == NO_ERROR);
6323 }
6324
jiabin81772902018-04-02 17:52:27 -07006325 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006326 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006327 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006328 }
6329
6330 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6331}
6332
Eric Laurent5ada82e2019-08-29 17:53:54 -07006333void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006334{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006335 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006336 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006337 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006338 }
6339}
6340
jiabin6012f912018-11-02 17:06:30 -07006341bool AudioPolicyManager::isHapticPlaybackSupported()
6342{
6343 for (const auto& hwModule : mHwModules) {
6344 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6345 for (const auto &outProfile : outputProfiles) {
6346 struct audio_port audioPort;
6347 outProfile->toAudioPort(&audioPort);
6348 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6349 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6350 return true;
6351 }
6352 }
6353 }
6354 }
6355 return false;
6356}
6357
Carter Hsu325a8eb2022-01-19 19:56:51 +08006358bool AudioPolicyManager::isUltrasoundSupported()
6359{
6360 bool hasUltrasoundOutput = false;
6361 bool hasUltrasoundInput = false;
6362 for (const auto& hwModule : mHwModules) {
6363 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6364 if (!hasUltrasoundOutput) {
6365 for (const auto &outProfile : outputProfiles) {
6366 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6367 hasUltrasoundOutput = true;
6368 break;
6369 }
6370 }
6371 }
6372
6373 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6374 if (!hasUltrasoundInput) {
6375 for (const auto &inputProfile : inputProfiles) {
6376 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6377 hasUltrasoundInput = true;
6378 break;
6379 }
6380 }
6381 }
6382
6383 if (hasUltrasoundOutput && hasUltrasoundInput)
6384 return true;
6385 }
6386 return false;
6387}
6388
Atneya Nair698f5ef2022-12-15 16:15:09 -08006389bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6390{
6391 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6392 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6393 for (const auto& hwModule : mHwModules) {
6394 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6395 for (const auto &inputProfile : inputProfiles) {
6396 if ((inputProfile->getFlags() & mask) == mask) {
6397 return true;
6398 }
6399 }
6400 }
6401 return false;
6402}
6403
Eric Laurent8340e672019-11-06 11:01:08 -08006404bool AudioPolicyManager::isCallScreenModeSupported()
6405{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006406 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006407}
6408
6409
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006410status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006411{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006412 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006413 if (!sourceDesc->isConnected()) {
6414 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6415 return NO_ERROR;
6416 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006417 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6418 if (swOutput != 0) {
6419 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006420 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006421 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006422 }
jiabinbce0c1d2020-10-05 11:20:18 -07006423 if (releaseOutput(sourceDesc->portId())) {
6424 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6425 // no need to release audio patch here but just return NO_ERROR.
6426 return NO_ERROR;
6427 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006428 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006429 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006430 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006431 // close Hwoutput and remove from mHwOutputs
6432 } else {
6433 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6434 }
6435 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006436 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006437 sourceDesc->disconnect();
6438 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006439}
6440
François Gaffiec005e562018-11-06 15:04:49 +01006441sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6442 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006443{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006444 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006445 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006446 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006447 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006448 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6449 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006450 source = sourceDesc;
6451 break;
6452 }
6453 }
6454 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006455}
6456
Eric Laurentb4f42a92022-01-17 17:37:31 +01006457bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006458 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006459 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006460{
6461 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6462 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006463 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006464 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006465 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6466 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6467 return false;
6468 }
6469 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6470 return false;
6471 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006472 }
6473
Eric Laurentd332bc82023-08-04 11:45:23 +02006474 // The caller can have the audio config criteria ignored by either passing a null ptr or
6475 // the AUDIO_CONFIG_INITIALIZER value.
6476 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006477 // some positional channel masks and PCM format and for stereo if low latency performance
6478 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006479
6480 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006481 const bool channel_mask_spatialized =
Shunkai Yao2dcd60c2024-08-27 21:08:53 +00006482 SpatializerHelper::isStereoSpatializationFeatureEnabled()
6483 ? audio_channel_mask_contains_stereo(config->channel_mask)
6484 : audio_is_channel_mask_spatialized(config->channel_mask);
Andy Hung481bfe32023-12-18 14:00:29 -08006485 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006486 return false;
6487 }
6488 if (!audio_is_linear_pcm(config->format)) {
6489 return false;
6490 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006491 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6492 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6493 return false;
6494 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006495 }
6496
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006497 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006498 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006499 if (profile == nullptr) {
6500 return false;
6501 }
6502
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006503 return true;
6504}
6505
Shunkai Yao4c3af932024-04-26 04:12:21 +00006506// The Spatializer output is compatible with Haptic use cases if:
6507// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6508// with client if client haptic channel bits were set, or
6509// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6510// including the haptic bits or creating the HapticGenerator effect for same session.
6511bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6512 const audio_config_t* config, audio_session_t sessionId) const {
6513 const auto clientHapticChannel =
6514 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6515 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6516 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6517
6518 if (threadOutputHapticChannel) {
6519 // check format and sampleRate match if client haptic channel mask exist
6520 if (clientHapticChannel) {
6521 return mSpatializerOutput->getFormat() == config->format &&
6522 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6523 }
6524 return true;
6525 } else {
6526 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6527 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6528 // HapticGenerator effect for this session) are not supported.
6529 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006530 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao4c3af932024-04-26 04:12:21 +00006531 }
6532}
6533
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006534void AudioPolicyManager::checkVirtualizerClientRoutes() {
6535 std::set<audio_stream_type_t> streamsToInvalidate;
6536 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006537 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6538 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006539 audio_attributes_t attr = client->attributes();
6540 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6541 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6542 audio_config_base_t clientConfig = client->config();
6543 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006544 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006545 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006546 streamsToInvalidate.insert(client->stream());
6547 }
6548 }
6549 }
6550
jiabinc44b3462022-12-08 12:52:31 -08006551 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006552}
6553
Eric Laurente191d1b2022-04-15 11:59:25 +02006554
6555bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6556 const sp<SwAudioOutputDescriptor>& outputDesc) {
6557 if (outputDesc->isDuplicated()) {
6558 return false;
6559 }
6560 DeviceVector devices = outputDesc->supportedDevices();
6561 for (size_t i = 0; i < mOutputs.size(); i++) {
6562 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6563 if (desc == outputDesc || desc->isDuplicated()) {
6564 continue;
6565 }
6566 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6567 if (!sharedDevices.isEmpty()
6568 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6569 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6570 return false;
6571 }
6572 }
6573 return true;
6574}
6575
6576
Eric Laurentfa0f6742021-08-17 18:39:44 +02006577status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006578 const audio_attributes_t *attr,
6579 audio_io_handle_t *output) {
6580 *output = AUDIO_IO_HANDLE_NONE;
6581
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006582 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6583 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6584 audio_config_t *configPtr = nullptr;
6585 audio_config_t config;
6586 if (mixerConfig != nullptr) {
6587 config = audio_config_initializer(mixerConfig);
6588 configPtr = &config;
6589 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006590 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006591 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006592 return BAD_VALUE;
6593 }
6594
6595 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006596 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006597 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006598 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006599 return BAD_VALUE;
6600 }
6601
Eric Laurente191d1b2022-04-15 11:59:25 +02006602 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006603 for (size_t i = 0; i < mOutputs.size(); i++) {
6604 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006605 if (!desc->isDuplicated()
6606 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6607 spatializerOutputs.push_back(desc);
6608 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006609 }
6610 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006611 mSpatializerOutput.clear();
6612 bool outputsChanged = false;
6613 for (const auto& desc : spatializerOutputs) {
6614 if (desc->mProfile == profile
6615 && (configPtr == nullptr
6616 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6617 mSpatializerOutput = desc;
6618 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6619 } else {
6620 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6621 " and devices %s", __func__, desc->mIoHandle,
6622 configPtr != nullptr ? configPtr->channel_mask : 0,
6623 devices.toString().c_str());
6624 closeOutput(desc->mIoHandle);
6625 outputsChanged = true;
6626 }
Eric Laurent39095982021-08-24 18:29:27 +02006627 }
6628
Eric Laurente191d1b2022-04-15 11:59:25 +02006629 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006630 sp<SwAudioOutputDescriptor> desc =
6631 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006632 if (desc != nullptr) {
6633 mSpatializerOutput = desc;
6634 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006635 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006636 }
6637
6638 checkVirtualizerClientRoutes();
6639
Eric Laurente191d1b2022-04-15 11:59:25 +02006640 if (outputsChanged) {
6641 mPreviousOutputs = mOutputs;
6642 mpClientInterface->onAudioPortListUpdate();
6643 }
6644
6645 if (mSpatializerOutput == nullptr) {
6646 ALOGV("%s could not open spatializer output with requested config", __func__);
6647 return BAD_VALUE;
6648 }
Eric Laurent39095982021-08-24 18:29:27 +02006649 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006650 ALOGV("%s returning new spatializer output %d", __func__, *output);
6651 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006652}
6653
Eric Laurentfa0f6742021-08-17 18:39:44 +02006654status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6655 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006656 return INVALID_OPERATION;
6657 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006658 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006659 return BAD_VALUE;
6660 }
Eric Laurent39095982021-08-24 18:29:27 +02006661
Eric Laurente191d1b2022-04-15 11:59:25 +02006662 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6663 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6664 closeOutput(mSpatializerOutput->mIoHandle);
6665 //from now on mSpatializerOutput is null
6666 checkVirtualizerClientRoutes();
6667 }
Eric Laurent39095982021-08-24 18:29:27 +02006668
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006669 return NO_ERROR;
6670}
6671
Eric Laurente552edb2014-03-10 17:42:56 -07006672// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006673// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006674// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006675uint32_t AudioPolicyManager::nextAudioPortGeneration()
6676{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006677 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006678}
6679
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006680AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006681 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006682 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006683 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006684 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006685 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006686 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006687 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006688 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006689 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006690 mAudioPortGeneration(1),
6691 mBeaconMuteRefCount(0),
6692 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006693 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006694 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006695 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006696 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006697{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006698}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006699
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006700status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006701 if (mEngine == nullptr) {
6702 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006703 }
6704 mEngine->setObserver(this);
6705 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006706 if (status != NO_ERROR) {
6707 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6708 return status;
6709 }
François Gaffie2110e042015-03-24 08:41:51 +01006710
jiabin29230182023-04-04 21:02:36 +00006711 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6712 // at the end of this function.
6713 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006714 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6715 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6716
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006717 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006718 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006719 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006720
Eric Laurent3a4311c2014-03-17 12:00:47 -07006721 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006722 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6723 defaultOutputDevice == nullptr ||
6724 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6725 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6726 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006727 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006728 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006729 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006730
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006731 // Silence ALOGV statements
6732 property_set("log.tag." LOG_TAG, "D");
6733
Eric Laurente552edb2014-03-10 17:42:56 -07006734 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006735 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006736}
6737
Eric Laurente0720872014-03-11 09:30:41 -07006738AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006739{
Eric Laurente552edb2014-03-10 17:42:56 -07006740 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006741 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006742 }
6743 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006744 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006745 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006746 mAvailableOutputDevices.clear();
6747 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006748 mOutputs.clear();
6749 mInputs.clear();
6750 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006751 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006752 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006753}
6754
Eric Laurente0720872014-03-11 09:30:41 -07006755status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006756{
Eric Laurent87ffa392015-05-22 10:32:38 -07006757 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006758}
6759
Eric Laurente552edb2014-03-10 17:42:56 -07006760// ---
6761
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006762void AudioPolicyManager::onNewAudioModulesAvailable()
6763{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006764 DeviceVector newDevices;
6765 onNewAudioModulesAvailableInt(&newDevices);
6766 if (!newDevices.empty()) {
6767 nextAudioPortGeneration();
6768 mpClientInterface->onAudioPortListUpdate();
6769 }
6770}
6771
6772void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6773{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006774 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006775 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6776 continue;
6777 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006778 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006779 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6780 handle != AUDIO_MODULE_HANDLE_NONE) {
6781 hwModule->setHandle(handle);
6782 } else {
6783 ALOGW("could not load HW module %s", hwModule->getName());
6784 continue;
6785 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006786 }
6787 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006788 // open all output streams needed to access attached devices.
6789 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006790 // This also validates mAvailableOutputDevices list
6791 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6792 if (!outProfile->canOpenNewIo()) {
6793 ALOGE("Invalid Output profile max open count %u for profile %s",
6794 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6795 continue;
6796 }
6797 if (!outProfile->hasSupportedDevices()) {
6798 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6799 continue;
6800 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006801 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6802 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006803 mTtsOutputAvailable = true;
6804 }
6805
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006806 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006807 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006808 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006809 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6810 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006811 } else {
6812 // choose first device present in profile's SupportedDevices also part of
6813 // mAvailableOutputDevices.
6814 if (availProfileDevices.isEmpty()) {
6815 continue;
6816 }
6817 supportedDevice = availProfileDevices.itemAt(0);
6818 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006819 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006820 continue;
6821 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306822
6823 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6824 && availProfileDevices.areAllDevicesAttached()) {
6825 ALOGV("%s skip opening output for mmap profile %s", __func__,
6826 outProfile->getTagName().c_str());
6827 continue;
6828 }
6829
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006830 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6831 mpClientInterface);
6832 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006833 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07006834 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006835 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6836 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006837 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006838 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006839 if (status != NO_ERROR) {
6840 ALOGW("Cannot open output stream for devices %s on hw module %s",
6841 supportedDevice->toString().c_str(), hwModule->getName());
6842 continue;
6843 }
6844 for (const auto &device : availProfileDevices) {
6845 // give a valid ID to an attached device once confirmed it is reachable
6846 if (!device->isAttached()) {
6847 device->attach(hwModule);
6848 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006849 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006850 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006851 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6852 }
6853 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006854 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006855 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6856 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006857 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006858 }
Eric Laurent39095982021-08-24 18:29:27 +02006859 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006860 outputDesc->close();
6861 } else {
6862 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306863 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006864 DeviceVector(supportedDevice),
6865 true,
6866 0,
6867 NULL);
6868 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006869 }
6870 // open input streams needed to access attached devices to validate
6871 // mAvailableInputDevices list
6872 for (const auto& inProfile : hwModule->getInputProfiles()) {
6873 if (!inProfile->canOpenNewIo()) {
6874 ALOGE("Invalid Input profile max open count %u for profile %s",
6875 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6876 continue;
6877 }
6878 if (!inProfile->hasSupportedDevices()) {
6879 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6880 continue;
6881 }
6882 // chose first device present in profile's SupportedDevices also part of
6883 // available input devices
6884 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006885 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006886 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006887 ALOGV("%s: Input device list is empty! for profile %s",
6888 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006889 continue;
6890 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05306891
6892 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6893 && availProfileDevices.areAllDevicesAttached()) {
6894 ALOGV("%s skip opening input for mmap profile %s", __func__,
6895 inProfile->getTagName().c_str());
6896 continue;
6897 }
6898
Eric Laurentc71b11b2024-06-03 12:54:53 +00006899 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(
6900 inProfile, mpClientInterface, false /*isPreemptor*/);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006901
6902 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6903 status_t status = inputDesc->open(nullptr,
6904 availProfileDevices.itemAt(0),
6905 AUDIO_SOURCE_MIC,
Jaideep Sharma26e31c22024-06-18 14:12:50 +05306906 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006907 &input);
6908 if (status != NO_ERROR) {
Jaideep Sharma33173202024-06-18 17:46:45 +05306909 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6910 __func__, availProfileDevices.toString().c_str(),
6911 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006912 continue;
6913 }
6914 for (const auto &device : availProfileDevices) {
6915 // give a valid ID to an attached device once confirmed it is reachable
6916 if (!device->isAttached()) {
6917 device->attach(hwModule);
6918 device->importAudioPortAndPickAudioProfile(inProfile, true);
6919 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006920 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006921 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6922 }
6923 }
6924 inputDesc->close();
6925 }
6926 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006927
6928 // Check if spatializer outputs can be closed until used.
6929 // mOutputs vector never contains duplicated outputs at this point.
6930 std::vector<audio_io_handle_t> outputsClosed;
6931 for (size_t i = 0; i < mOutputs.size(); i++) {
6932 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6933 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6934 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6935 outputsClosed.push_back(desc->mIoHandle);
Eric Laurenta70bc372024-04-30 02:10:04 +00006936 nextAudioPortGeneration();
6937 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6938 if (index >= 0) {
6939 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6940 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6941 patchDesc->getAfHandle(), 0);
6942 mAudioPatches.removeItemsAt(index);
6943 mpClientInterface->onAudioPatchListUpdate();
6944 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006945 desc->close();
6946 }
6947 }
6948 for (auto output : outputsClosed) {
6949 removeOutput(output);
6950 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006951}
6952
Eric Laurent98e38192018-02-15 18:31:53 -08006953void AudioPolicyManager::addOutput(audio_io_handle_t output,
6954 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006955{
Eric Laurent1c333e22014-05-20 10:48:17 -07006956 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006957 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006958 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006959 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006960 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006961}
6962
François Gaffie53615e22015-03-19 09:24:12 +01006963void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6964{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006965 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6966 ALOGV("%s: removing primary output", __func__);
6967 mPrimaryOutput = nullptr;
6968 }
François Gaffie53615e22015-03-19 09:24:12 +01006969 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006970 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006971}
6972
Eric Laurent98e38192018-02-15 18:31:53 -08006973void AudioPolicyManager::addInput(audio_io_handle_t input,
6974 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006975{
Eric Laurent1c333e22014-05-20 10:48:17 -07006976 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006977 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006978}
Eric Laurente552edb2014-03-10 17:42:56 -07006979
François Gaffie11d30102018-11-02 16:09:09 +01006980status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006981 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006982 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006983{
François Gaffie11d30102018-11-02 16:09:09 +01006984 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006985 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006986 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006987
François Gaffie11d30102018-11-02 16:09:09 +01006988 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006989 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006990 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006991 }
Eric Laurente552edb2014-03-10 17:42:56 -07006992
Eric Laurent3b73df72014-03-11 09:06:29 -07006993 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006994 // first call getAudioPort to get the supported attributes from the HAL
6995 struct audio_port_v7 port = {};
6996 device->toAudioPort(&port);
6997 status_t status = mpClientInterface->getAudioPort(&port);
6998 if (status == NO_ERROR) {
6999 device->importAudioPort(port);
7000 }
7001
7002 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07007003 for (size_t i = 0; i < mOutputs.size(); i++) {
7004 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007005 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07007006 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01007007 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
7008 mOutputs.keyAt(i), device->toString().c_str());
7009 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007010 }
7011 }
7012 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007013 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007014 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007015 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7016 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01007017 if (profile->supportsDevice(device)) {
7018 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307019 ALOGV("%s(): adding profile %s from module %s",
7020 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07007021 }
7022 }
7023 }
7024
Eric Laurent7b279bb2015-12-14 10:18:23 -08007025 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007026
Eric Laurente552edb2014-03-10 17:42:56 -07007027 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007028 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007029 return BAD_VALUE;
7030 }
7031
7032 // open outputs for matching profiles if needed. Direct outputs are also opened to
7033 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7034 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007035 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07007036
7037 // nothing to do if one output is already opened for this profile
7038 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007039 for (j = 0; j < outputs.size(); j++) {
7040 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07007041 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007042 // matching profile: save the sample rates, format and channel masks supported
7043 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01007044 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07007045 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007046 }
Eric Laurente552edb2014-03-10 17:42:56 -07007047 break;
7048 }
7049 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007050 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07007051 continue;
7052 }
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307053 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7054 ALOGV("%s skip opening output for mmap profile %s",
7055 __func__, profile->getTagName().c_str());
7056 continue;
7057 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007058 if (!profile->canOpenNewIo()) {
7059 ALOGW("Max Output number %u already opened for this profile %s",
7060 profile->maxOpenCount, profile->getTagName().c_str());
7061 continue;
7062 }
7063
Eric Laurent83efe1c2017-07-09 16:51:08 -07007064 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00007065 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07007066 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
7067 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07007068 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01007069 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007070 profiles.removeAt(profile_index);
7071 profile_index--;
7072 } else {
7073 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07007074 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01007075 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07007076 // TODO: when getAudioPort is ready, it may not be needed to import the audio
7077 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07007078 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007079 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07007080
François Gaffie11d30102018-11-02 16:09:09 +01007081 if (device_distinguishes_on_address(deviceType)) {
7082 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
7083 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307084 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
7085 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007086 }
Eric Laurente552edb2014-03-10 17:42:56 -07007087 ALOGV("checkOutputsForDevice(): adding output %d", output);
7088 }
7089 }
7090
7091 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007092 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07007093 return BAD_VALUE;
7094 }
Eric Laurentd4692962014-05-05 18:13:44 -07007095 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07007096 // check if one opened output is not needed any more after disconnecting one device
7097 for (size_t i = 0; i < mOutputs.size(); i++) {
7098 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007099 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08007100 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007101 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01007102 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01007103 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01007104 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007105 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
7106 mOutputs.keyAt(i));
7107 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07007108 }
Eric Laurente552edb2014-03-10 17:42:56 -07007109 }
7110 }
Eric Laurentd4692962014-05-05 18:13:44 -07007111 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007112 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007113 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
7114 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07007115 if (!profile->supportsDevice(device)) {
7116 continue;
7117 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307118 ALOGV("%s(): clearing direct output profile %s on module %s",
7119 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07007120 profile->clearAudioProfiles();
7121 if (!profile->hasDynamicAudioProfile()) {
7122 continue;
7123 }
7124 // When a device is disconnected, if there is an IOProfile that contains dynamic
7125 // profiles and supports the disconnected device, call getAudioPort to repopulate
7126 // the capabilities of the devices that is supported by the IOProfile.
7127 for (const auto& supportedDevice : profile->getSupportedDevices()) {
7128 if (supportedDevice == device ||
7129 !mAvailableOutputDevices.contains(supportedDevice)) {
7130 continue;
7131 }
7132 struct audio_port_v7 port;
7133 supportedDevice->toAudioPort(&port);
7134 status_t status = mpClientInterface->getAudioPort(&port);
7135 if (status == NO_ERROR) {
7136 supportedDevice->importAudioPort(port);
7137 }
Eric Laurente552edb2014-03-10 17:42:56 -07007138 }
7139 }
7140 }
7141 }
7142 return NO_ERROR;
7143}
7144
François Gaffie11d30102018-11-02 16:09:09 +01007145status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07007146 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07007147{
François Gaffie11d30102018-11-02 16:09:09 +01007148 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07007149 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01007150 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07007151 }
7152
Eric Laurentd4692962014-05-05 18:13:44 -07007153 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007154 sp<AudioInputDescriptor> desc;
7155
jiabinbf5f4262023-04-12 21:48:34 +00007156 // first call getAudioPort to get the supported attributes from the HAL
7157 struct audio_port_v7 port = {};
7158 device->toAudioPort(&port);
7159 status_t status = mpClientInterface->getAudioPort(&port);
7160 if (status == NO_ERROR) {
7161 device->importAudioPort(port);
7162 }
7163
Eric Laurent0dd51852019-04-19 18:18:58 -07007164 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07007165 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007166 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007167 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007168 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08007169 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007170 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08007171
François Gaffie11d30102018-11-02 16:09:09 +01007172 if (profile->supportsDevice(device)) {
7173 profiles.add(profile);
Jaideep Sharma33173202024-06-18 17:46:45 +05307174 ALOGV("%s : adding profile %s from module %s", __func__,
7175 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07007176 }
7177 }
7178 }
7179
Eric Laurent0dd51852019-04-19 18:18:58 -07007180 if (profiles.isEmpty()) {
7181 ALOGW("%s: No input profile available for device %s",
7182 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007183 return BAD_VALUE;
7184 }
7185
7186 // open inputs for matching profiles if needed. Direct inputs are also opened to
7187 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
7188 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
7189
Eric Laurent1c333e22014-05-20 10:48:17 -07007190 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08007191
Eric Laurentd4692962014-05-05 18:13:44 -07007192 // nothing to do if one input is already opened for this profile
7193 size_t input_index;
7194 for (input_index = 0; input_index < mInputs.size(); input_index++) {
7195 desc = mInputs.valueAt(input_index);
7196 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01007197 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007198 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007199 }
Eric Laurentd4692962014-05-05 18:13:44 -07007200 break;
7201 }
7202 }
7203 if (input_index != mInputs.size()) {
7204 continue;
7205 }
7206
Jaideep Sharma2cfa7ef2024-06-18 16:32:34 +05307207 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7208 ALOGV("%s skip opening input for mmap profile %s",
7209 __func__, profile->getTagName().c_str());
7210 continue;
7211 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007212 if (!profile->canOpenNewIo()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307213 ALOGW("%s Max Input number %u already opened for this profile %s",
7214 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007215 continue;
7216 }
7217
Eric Laurentc71b11b2024-06-03 12:54:53 +00007218 desc = new AudioInputDescriptor(profile, mpClientInterface, false /*isPreemptor*/);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007219 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharma33173202024-06-18 17:46:45 +05307220 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Jaideep Sharma26e31c22024-06-18 14:12:50 +05307221 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7222 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007223
Eric Laurentcf2c0212014-07-25 16:20:43 -07007224 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007225 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007226 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007227 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007228 mpClientInterface->setParameters(input, String8(param));
7229 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007230 }
jiabin12537fc2023-10-12 17:56:08 +00007231 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007232 if (!profile->hasValidAudioProfile()) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307233 ALOGW("%s direct input missing param for profile %s", __func__,
7234 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007235 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007236 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007237 }
7238
Eric Laurent0dd51852019-04-19 18:18:58 -07007239 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007240 addInput(input, desc);
7241 }
7242 } // endif input != 0
7243
Eric Laurentcf2c0212014-07-25 16:20:43 -07007244 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307245 ALOGW("%s could not open input for device %s on profile %s", __func__,
7246 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007247 profiles.removeAt(profile_index);
7248 profile_index--;
7249 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007250 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007251 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007252 }
Jaideep Sharma33173202024-06-18 17:46:45 +05307253 ALOGV("%s: adding input %d for profile %s", __func__,
7254 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007255
7256 if (checkCloseInput(desc)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307257 ALOGV("%s: closing input %d for profile %s", __func__,
7258 input, profile->getTagName().c_str());
Mikhail Naganovc66ffc12024-05-30 16:56:25 -07007259 closeInput(input);
7260 }
Eric Laurentd4692962014-05-05 18:13:44 -07007261 }
7262 } // end scan profiles
7263
7264 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007265 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007266 return BAD_VALUE;
7267 }
7268 } else {
7269 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007270 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007271 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007272 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007273 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007274 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007275 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007276 if (profile->supportsDevice(device)) {
Jaideep Sharma33173202024-06-18 17:46:45 +05307277 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7278 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007279 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007280 }
7281 }
7282 }
7283 } // end disconnect
7284
7285 return NO_ERROR;
7286}
7287
7288
Eric Laurente0720872014-03-11 09:30:41 -07007289void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007290{
7291 ALOGV("closeOutput(%d)", output);
7292
François Gaffie1c878552018-11-22 16:53:21 +01007293 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7294 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007295 ALOGW("closeOutput() unknown output %d", output);
7296 return;
7297 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007298 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007299 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007300
Eric Laurente552edb2014-03-10 17:42:56 -07007301 // look for duplicated outputs connected to the output being removed.
7302 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007303 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7304 if (dupOutput->isDuplicated() &&
7305 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7306 sp<SwAudioOutputDescriptor> remainingOutput =
7307 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007308 // As all active tracks on duplicated output will be deleted,
7309 // and as they were also referenced on the other output, the reference
7310 // count for their stream type must be adjusted accordingly on
7311 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007312 const bool wasActive = remainingOutput->isActive();
7313 // Note: no-op on the closing output where all clients has already been set inactive
7314 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007315 // stop() will be a no op if the output is still active but is needed in case all
7316 // active streams refcounts where cleared above
7317 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007318 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007319 }
Eric Laurente552edb2014-03-10 17:42:56 -07007320 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7321 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7322
7323 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007324 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007325 }
7326 }
7327
Eric Laurent05b90f82014-08-27 15:32:29 -07007328 nextAudioPortGeneration();
7329
François Gaffie1c878552018-11-22 16:53:21 +01007330 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007331 if (index >= 0) {
7332 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007333 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7334 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007335 mAudioPatches.removeItemsAt(index);
7336 mpClientInterface->onAudioPatchListUpdate();
7337 }
7338
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007339 if (closingOutputWasActive) {
7340 closingOutput->stop();
7341 }
François Gaffie1c878552018-11-22 16:53:21 +01007342 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007343 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007344 for (const auto device : closingOutput->devices()) {
7345 device->setPreferredConfig(nullptr);
7346 }
7347 }
Eric Laurente552edb2014-03-10 17:42:56 -07007348
François Gaffie53615e22015-03-19 09:24:12 +01007349 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007350 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007351 if (closingOutput == mSpatializerOutput) {
7352 mSpatializerOutput.clear();
7353 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007354
7355 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7356 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007357 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007358 bool directOutputOpen = false;
7359 for (size_t i = 0; i < mOutputs.size(); i++) {
7360 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7361 directOutputOpen = true;
7362 break;
7363 }
7364 }
7365 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007366 ALOGV("no direct outputs open, reset MSD patches");
7367 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7368 // how output devices for patching are resolved. Avoid by caching and reusing the
7369 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7370 // devices to patch to. This may be complicated by the fact that devices may become
7371 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007372 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007373 }
7374 }
jiabin220eea12024-05-17 17:55:20 +00007375
7376 if (closingOutput->mPreferredAttrInfo != nullptr) {
7377 closingOutput->mPreferredAttrInfo->resetActiveClient();
7378 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007379}
7380
7381void AudioPolicyManager::closeInput(audio_io_handle_t input)
7382{
7383 ALOGV("closeInput(%d)", input);
7384
7385 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7386 if (inputDesc == NULL) {
7387 ALOGW("closeInput() unknown input %d", input);
7388 return;
7389 }
7390
Eric Laurent6a94d692014-05-20 11:18:06 -07007391 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007392
François Gaffie11d30102018-11-02 16:09:09 +01007393 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007394 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007395 if (index >= 0) {
7396 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007397 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7398 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007399 mAudioPatches.removeItemsAt(index);
7400 mpClientInterface->onAudioPatchListUpdate();
7401 }
7402
François Gaffie6ebbce02023-07-19 13:27:53 +02007403 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007404 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007405 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007406
François Gaffie11d30102018-11-02 16:09:09 +01007407 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7408 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007409 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007410 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007411 }
Eric Laurente552edb2014-03-10 17:42:56 -07007412}
7413
François Gaffie11d30102018-11-02 16:09:09 +01007414SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7415 const DeviceVector &devices,
7416 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007417{
7418 SortedVector<audio_io_handle_t> outputs;
7419
François Gaffie11d30102018-11-02 16:09:09 +01007420 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007421 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007422 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007423 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007424 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007425 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007426 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007427 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007428 outputs.add(openOutputs.keyAt(i));
7429 }
7430 }
7431 return outputs;
7432}
7433
Mikhail Naganov37977152018-07-11 15:54:44 -07007434void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7435{
7436 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7437 // output is suspended before any tracks are moved to it
7438 checkA2dpSuspend();
7439 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007440 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007441 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007442 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007443 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007444 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7445 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7446 // configuration changes will ultimately be rerouted correctly. We can still avoid
7447 // unnecessary rerouting by caching and reusing the arguments to
7448 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7449 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007450 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007451 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007452 // an event that changed routing likely occurred, inform upper layers
7453 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007454}
7455
François Gaffiec005e562018-11-06 15:04:49 +01007456bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7457 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007458{
François Gaffiec005e562018-11-06 15:04:49 +01007459 return mEngine->getProductStrategyForAttributes(lAttr) ==
7460 mEngine->getProductStrategyForAttributes(rAttr);
7461}
7462
Francois Gaffieff1eb522020-05-06 18:37:04 +02007463void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7464{
7465 for (size_t i = 0; i < mAudioSources.size(); i++) {
7466 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7467 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007468 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurentccbd7872024-06-20 12:34:15 +00007469 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007470 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007471 }
7472 }
7473}
7474
7475void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7476{
7477 for (size_t i = 0; i < mAudioSources.size(); i++) {
7478 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7479 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7480 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7481 disconnectAudioSource(sourceDesc);
7482 }
7483 }
7484}
7485
François Gaffiec005e562018-11-06 15:04:49 +01007486void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7487{
7488 auto psId = mEngine->getProductStrategyForAttributes(attr);
7489
7490 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7491 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007492
François Gaffie11d30102018-11-02 16:09:09 +01007493 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7494 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007495
Eric Laurentc209fe42020-06-05 18:11:23 -07007496 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007497 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007498 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007499 // take into account dynamic audio policies related changes: if a client is now associated
7500 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007501 // invalidate clients on outputs that do not support all the newly selected devices for the
7502 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007503 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007504 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007505 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007506 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007507 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007508
Eric Laurentc209fe42020-06-05 18:11:23 -07007509 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7510 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7511 continue;
7512 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007513 if (!desc->supportsAllDevices(newDevices)) {
7514 invalidatedOutputs.push_back(desc);
7515 break;
7516 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007517 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007518 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007519 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7520 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7521 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007522 if (status == OK) {
7523 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7524 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7525 maxLatency = desc->latency();
7526 }
7527 invalidatedOutputs.push_back(desc);
7528 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007529 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007530 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007531 }
7532 }
7533
Eric Laurent56ed8842022-11-15 16:04:41 +01007534 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007535 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7536 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007537 for (audio_io_handle_t srcOut : srcOutputs) {
7538 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007539 if (desc == nullptr) continue;
7540
7541 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007542 maxLatency = desc->latency();
7543 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007544
Eric Laurent56ed8842022-11-15 16:04:41 +01007545 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007546 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007547 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007548 // a client on a non direct outputs has necessarily a linear PCM format
7549 // so we can call selectOutput() safely
7550 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7551 client->flags(),
7552 client->config().format,
7553 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007554 client->config().sample_rate,
7555 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007556 if (newOutput != srcOut) {
7557 invalidate = true;
7558 break;
7559 }
7560 } else {
7561 sp<IOProfile> profile = getProfileForOutput(newDevices,
7562 client->config().sample_rate,
7563 client->config().format,
7564 client->config().channel_mask,
7565 client->flags(),
7566 true /* directOnly */);
7567 if (profile != desc->mProfile) {
7568 invalidate = true;
7569 break;
7570 }
7571 }
7572 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007573 // mute strategy while moving tracks from one output to another
7574 if (invalidate) {
7575 invalidatedOutputs.push_back(desc);
7576 if (desc->isStrategyActive(psId)) {
7577 setStrategyMute(psId, true, desc);
7578 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7579 newDevices.types());
7580 }
Eric Laurente552edb2014-03-10 17:42:56 -07007581 }
François Gaffiec005e562018-11-06 15:04:49 +01007582 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurentccbd7872024-06-20 12:34:15 +00007583 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Lif85c5e32024-07-01 13:14:10 +00007584 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007585 }
Eric Laurente552edb2014-03-10 17:42:56 -07007586 }
7587
Eric Laurent56ed8842022-11-15 16:04:41 +01007588 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7589 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7590 std::to_string(srcOutputs[0]).c_str(),
7591 std::to_string(dstOutputs[0]).c_str());
7592
François Gaffiec005e562018-11-06 15:04:49 +01007593 // Move effects associated to this stream from previous output to new output
7594 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007595 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007596 }
François Gaffiec005e562018-11-06 15:04:49 +01007597 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007598 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007599 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007600 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007601 desc->setTracksInvalidatedStatusByStrategy(psId);
7602 }
Eric Laurente552edb2014-03-10 17:42:56 -07007603 }
7604 }
7605}
7606
Eric Laurente0720872014-03-11 09:30:41 -07007607void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007608{
François Gaffiec005e562018-11-06 15:04:49 +01007609 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7610 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7611 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007612 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007613 }
Eric Laurente552edb2014-03-10 17:42:56 -07007614}
7615
Kevin Rocard153f92d2018-12-18 18:33:28 -08007616void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007617 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007618 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007619 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007620 for (size_t i = 0; i < mOutputs.size(); i++) {
7621 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7622 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007623 sp<AudioPolicyMix> primaryMix;
7624 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007625 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007626 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7627 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7628 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007629 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7630 for (auto &secondaryMix : secondaryMixes) {
7631 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7632 if (outputDesc != nullptr &&
7633 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7634 secondaryDescs.push_back(outputDesc);
7635 }
7636 }
7637
jiabinc44b3462022-12-08 12:52:31 -08007638 if (status != OK &&
7639 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7640 // When it failed to query secondary output, only invalidate the client that is not
7641 // MMAP. The reason is that MMAP stream will not support secondary output.
7642 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007643 } else if (!std::equal(
7644 client->getSecondaryOutputs().begin(),
7645 client->getSecondaryOutputs().end(),
7646 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungdb27c442024-08-14 11:37:57 -07007647 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7648 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007649 // If the format is not PCM, the tracks should be invalidated to get correct
7650 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007651 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007652 } else {
7653 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7654 std::vector<audio_io_handle_t> secondaryOutputIds;
7655 for (const auto &secondaryDesc: secondaryDescs) {
7656 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7657 weakSecondaryDescs.push_back(secondaryDesc);
7658 }
7659 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7660 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007661 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007662 }
7663 }
7664 }
jiabin10a03f12021-05-07 23:46:28 +00007665 if (!trackSecondaryOutputs.empty()) {
7666 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7667 }
jiabinc44b3462022-12-08 12:52:31 -08007668 if (!clientsToInvalidate.empty()) {
7669 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7670 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007671 }
7672}
7673
Eric Laurent2517af32020-11-25 15:31:27 +01007674bool AudioPolicyManager::isScoRequestedForComm() const {
7675 AudioDeviceTypeAddrVector devices;
7676 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7677 for (const auto &device : devices) {
7678 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7679 return true;
7680 }
7681 }
7682 return false;
7683}
7684
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007685bool AudioPolicyManager::isHearingAidUsedForComm() const {
7686 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7687 true /*fromCache*/);
7688 for (const auto &device : devices) {
7689 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7690 return true;
7691 }
7692 }
7693 return false;
7694}
7695
7696
Eric Laurente0720872014-03-11 09:30:41 -07007697void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007698{
François Gaffie53615e22015-03-19 09:24:12 +01007699 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007700 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007701 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007702 return;
7703 }
7704
Eric Laurent3a4311c2014-03-17 12:00:47 -07007705 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007706 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7707 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007708 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007709
7710 // if suspended, restore A2DP output if:
7711 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007712 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007713 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007714 //
Eric Laurentf732e072016-08-03 19:30:28 -07007715 // if not suspended, suspend A2DP output if:
7716 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007717 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007718 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007719 //
7720 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007721 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007722 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007723 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007724 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007725
7726 mpClientInterface->restoreOutput(a2dpOutput);
7727 mA2dpSuspended = false;
7728 }
7729 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007730 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007731 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007732 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007733 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007734
7735 mpClientInterface->suspendOutput(a2dpOutput);
7736 mA2dpSuspended = true;
7737 }
7738 }
7739}
7740
François Gaffie11d30102018-11-02 16:09:09 +01007741DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7742 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007743{
François Gaffiedb1755b2023-09-01 11:50:35 +02007744 if (outputDesc == nullptr) {
7745 return DeviceVector{};
7746 }
François Gaffie11d30102018-11-02 16:09:09 +01007747
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007748 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007749 if (index >= 0) {
7750 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007751 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007752 ALOGV("%s device %s forced by patch %d", __func__,
7753 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7754 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007755 }
7756 }
7757
Dean Wheatley514b4312020-06-17 21:45:00 +10007758 // Do not retrieve engine device for outputs through MSD
7759 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7760 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7761 return outputDesc->devices();
7762 }
7763
Eric Laurent97ac8712018-07-27 18:59:02 -07007764 // Honor explicit routing requests only if no client using default routing is active on this
7765 // input: a specific app can not force routing for other apps by setting a preferred device.
7766 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007767 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007768 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007769 if (device != nullptr) {
7770 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007771 }
7772
François Gaffiea807ef92018-11-05 10:44:33 +01007773 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7774 // of setForceUse / Default Bus device here
7775 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7776 if (device != nullptr) {
7777 return DeviceVector(device);
7778 }
7779
François Gaffiedb1755b2023-09-01 11:50:35 +02007780 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007781 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7782 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307783 auto hasStreamActive = [&](auto stream) {
7784 return hasStream(streams, stream) && isStreamActive(stream, 0);
7785 };
Eric Laurent484e9272018-06-07 17:29:23 -07007786
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307787 auto doGetOutputDevicesForVoice = [&]() {
7788 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007789 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307790 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007791 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7792 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307793 };
7794
7795 // With low-latency playing on speaker, music on WFD, when the first low-latency
7796 // output is stopped, getNewOutputDevices checks for a product strategy
7797 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007798 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307799 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7800 // stream is associated to the output descriptor.
7801 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7802 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7803 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7804 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007805 // Retrieval of devices for voice DL is done on primary output profile, cannot
7806 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007807 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007808 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7809 break;
7810 }
Eric Laurente552edb2014-03-10 17:42:56 -07007811 }
François Gaffiec005e562018-11-06 15:04:49 +01007812 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007813 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007814}
7815
François Gaffie11d30102018-11-02 16:09:09 +01007816sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7817 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007818{
François Gaffie11d30102018-11-02 16:09:09 +01007819 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007820
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007821 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007822 if (index >= 0) {
7823 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007824 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007825 ALOGV("getNewInputDevice() device %s forced by patch %d",
7826 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7827 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007828 }
7829 }
7830
Eric Laurent97ac8712018-07-27 18:59:02 -07007831 // Honor explicit routing requests only if no client using default routing is active on this
7832 // input: a specific app can not force routing for other apps by setting a preferred device.
7833 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007834 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7835 if (device != nullptr) {
7836 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007837 }
7838
Eric Laurentdc95a252018-04-12 12:46:56 -07007839 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007840 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007841 audio_attributes_t attributes;
7842 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007843 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007844 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7845 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007846 attributes = topClient->attributes();
7847 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007848 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007849 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007850 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7851 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007852 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007853 }
7854
Francois Gaffie716e1432019-01-14 16:58:59 +01007855 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7856 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007857 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007858 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007859 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007860 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007861
Eric Laurente552edb2014-03-10 17:42:56 -07007862 return device;
7863}
7864
Eric Laurent794fde22016-03-11 09:50:45 -08007865bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7866 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007867 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007868}
7869
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007870status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007871 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007872 if (devices == nullptr) {
7873 return BAD_VALUE;
7874 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007875
Andy Hung6d23c0f2022-02-16 09:37:15 -08007876 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007877 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7878 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007879 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007880 for (const auto& device : curDevices) {
7881 devices->push_back(device->getDeviceTypeAddr());
7882 }
7883 return NO_ERROR;
7884}
7885
Eric Laurente0720872014-03-11 09:30:41 -07007886void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007887 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007888 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007889 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007890 updateDevicesAndOutputs();
7891 break;
7892 default:
7893 break;
7894 }
7895}
7896
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007897uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007898
7899 // skip beacon mute management if a dedicated TTS output is available
7900 if (mTtsOutputAvailable) {
7901 return 0;
7902 }
7903
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007904 switch(event) {
7905 case STARTING_OUTPUT:
7906 mBeaconMuteRefCount++;
7907 break;
7908 case STOPPING_OUTPUT:
7909 if (mBeaconMuteRefCount > 0) {
7910 mBeaconMuteRefCount--;
7911 }
7912 break;
7913 case STARTING_BEACON:
7914 mBeaconPlayingRefCount++;
7915 break;
7916 case STOPPING_BEACON:
7917 if (mBeaconPlayingRefCount > 0) {
7918 mBeaconPlayingRefCount--;
7919 }
7920 break;
7921 }
7922
7923 if (mBeaconMuteRefCount > 0) {
7924 // any playback causes beacon to be muted
7925 return setBeaconMute(true);
7926 } else {
7927 // no other playback: unmute when beacon starts playing, mute when it stops
7928 return setBeaconMute(mBeaconPlayingRefCount == 0);
7929 }
7930}
7931
7932uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7933 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7934 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7935 // keep track of muted state to avoid repeating mute/unmute operations
7936 if (mBeaconMuted != mute) {
7937 // mute/unmute AUDIO_STREAM_TTS on all outputs
7938 ALOGV("\t muting %d", mute);
7939 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007940 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7941 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7942 ALOGV("\t no tts volume source available");
7943 return 0;
7944 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007945 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007946 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Vlad Popa1e865e62024-08-15 19:11:42 -07007947 setVolumeSourceMutedInternally(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/,
7948 DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007949 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007950 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007951 maxLatency = latency;
7952 }
7953 }
7954 mBeaconMuted = mute;
7955 return maxLatency;
7956 }
7957 return 0;
7958}
7959
Eric Laurente0720872014-03-11 09:30:41 -07007960void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007961{
François Gaffiec005e562018-11-06 15:04:49 +01007962 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007963 mPreviousOutputs = mOutputs;
7964}
7965
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007966uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007967 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007968 uint32_t delayMs)
7969{
7970 // mute/unmute strategies using an incompatible device combination
7971 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7972 // if unmuting, unmute only after the specified delay
7973 if (outputDesc->isDuplicated()) {
7974 return 0;
7975 }
7976
7977 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007978 DeviceVector devices = outputDesc->devices();
7979 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007980
François Gaffiec005e562018-11-06 15:04:49 +01007981 auto productStrategies = mEngine->getOrderedProductStrategies();
7982 for (const auto &productStrategy : productStrategies) {
7983 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7984 DeviceVector curDevices =
7985 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7986 curDevices = curDevices.filter(outputDesc->supportedDevices());
7987 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007988 bool doMute = false;
7989
François Gaffiec005e562018-11-06 15:04:49 +01007990 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007991 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007992 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7993 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007994 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007995 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007996 }
Eric Laurent99401132014-05-07 19:48:15 -07007997 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007998 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007999 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07008000 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01008001 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07008002 continue;
8003 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308004 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01008005 mute ? "muting" : "unmuting", curDevices.toString().c_str());
8006 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
8007 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07008008 if (mute) {
8009 // FIXME: should not need to double latency if volume could be applied
8010 // immediately by the audioflinger mixer. We must account for the delay
8011 // between now and the next time the audioflinger thread for this output
8012 // will process a buffer (which corresponds to one buffer size,
8013 // usually 1/2 or 1/4 of the latency).
8014 if (muteWaitMs < desc->latency() * 2) {
8015 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07008016 }
8017 }
8018 }
8019 }
8020 }
8021 }
8022
Eric Laurent99401132014-05-07 19:48:15 -07008023 // temporary mute output if device selection changes to avoid volume bursts due to
8024 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01008025 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07008026 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008027
Eric Laurentdc462862016-07-19 12:29:53 -07008028 if (muteWaitMs < tempMuteWaitMs) {
8029 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07008030 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08008031
8032 // If recommended duration is defined, replace temporary mute duration to avoid
8033 // truncated notifications at beginning, which depends on duration of changing path in HAL.
8034 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
8035 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
8036 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
8037 tempRecommendedMuteDuration : outputDesc->latency() * 4;
8038
François Gaffieaaac0fd2018-11-22 17:56:39 +01008039 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
8040 // make sure that we do not start the temporary mute period too early in case of
8041 // delayed device change
Vlad Popa1e865e62024-08-15 19:11:42 -07008042 setVolumeSourceMutedInternally(activeVs, true, outputDesc, delayMs);
8043 setVolumeSourceMutedInternally(activeVs, false, outputDesc,
8044 delayMs + tempMuteDurationMs,
8045 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07008046 }
8047 }
8048
Eric Laurente552edb2014-03-10 17:42:56 -07008049 // wait for the PCM output buffers to empty before proceeding with the rest of the command
8050 if (muteWaitMs > delayMs) {
8051 muteWaitMs -= delayMs;
8052 usleep(muteWaitMs * 1000);
8053 return muteWaitMs;
8054 }
8055 return 0;
8056}
8057
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308058uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
8059 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01008060 const DeviceVector &devices,
8061 bool force,
8062 int delayMs,
8063 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008064 bool requiresMuteCheck, bool requiresVolumeCheck,
8065 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07008066{
jiabin3ff8d7d2022-12-13 06:27:44 +00008067 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308068 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
8069 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
8070 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008071 uint32_t muteWaitMs;
8072
8073 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308074 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008075 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308076 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008077 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07008078 return muteWaitMs;
8079 }
Eric Laurente552edb2014-03-10 17:42:56 -07008080
8081 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01008082 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008083 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02008084 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008085
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308086 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
8087 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01008088
8089 if (!filteredDevices.isEmpty()) {
8090 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07008091 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008092
8093 // if the outputs are not materially active, there is no need to mute.
8094 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01008095 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008096 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308097 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
8098 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00008099 muteWaitMs = 0;
8100 }
Eric Laurente552edb2014-03-10 17:42:56 -07008101
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008102 bool outputRouted = outputDesc->isRouted();
8103
Eric Laurent79ea9582020-06-11 18:49:24 -07008104 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
8105 // output profile or if new device is not supported AND previous device(s) is(are) still
8106 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02008107 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308108 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
8109 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07008110 // restore previous device after evaluating strategy mute state
8111 outputDesc->setDevices(prevDevices);
8112 return muteWaitMs;
8113 }
8114
Eric Laurente552edb2014-03-10 17:42:56 -07008115 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07008116 // the requested device is AUDIO_DEVICE_NONE
8117 // OR the requested device is the same as current device
8118 // AND force is not specified
8119 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01008120 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008121 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308122 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
8123 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
8124 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008125 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308126 ALOGV("%s %s setting same device on routed output, force apply volumes",
8127 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02008128 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
8129 }
Eric Laurente552edb2014-03-10 17:42:56 -07008130 return muteWaitMs;
8131 }
8132
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05308133 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
8134 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07008135
Eric Laurente552edb2014-03-10 17:42:56 -07008136 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02008137 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07008138 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07008139 } else {
François Gaffie11d30102018-11-02 16:09:09 +01008140 PatchBuilder patchBuilder;
8141 patchBuilder.addSource(outputDesc);
8142 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
8143 for (const auto &filteredDevice : filteredDevices) {
8144 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07008145 }
8146
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08008147 // Add half reported latency to delayMs when muteWaitMs is null in order
8148 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008149 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
8150 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
8151 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008152 }
Eric Laurente552edb2014-03-10 17:42:56 -07008153
Oscar Azucena6acf34b2023-04-27 16:32:09 -07008154 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
8155 if (!skipMuteDelay) {
8156 // update stream volumes according to new device
8157 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
8158 }
Eric Laurente552edb2014-03-10 17:42:56 -07008159
8160 return muteWaitMs;
8161}
8162
Eric Laurentc75307b2015-03-17 15:29:32 -07008163status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07008164 int delayMs,
8165 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008166{
Eric Laurent6a94d692014-05-20 11:18:06 -07008167 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02008168 if (patchHandle == nullptr && !outputDesc->isRouted()) {
8169 return INVALID_OPERATION;
8170 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008171 if (patchHandle) {
8172 index = mAudioPatches.indexOfKey(*patchHandle);
8173 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08008174 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008175 }
8176 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008177 return INVALID_OPERATION;
8178 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008179 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008180 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07008181 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008182 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008183 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008184 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008185 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008186 return status;
8187}
8188
8189status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01008190 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07008191 bool force,
8192 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008193{
8194 status_t status = NO_ERROR;
8195
Eric Laurent1f2f2232014-06-02 12:01:23 -07008196 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01008197 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
8198 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07008199
François Gaffie11d30102018-11-02 16:09:09 +01008200 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008201 PatchBuilder patchBuilder;
8202 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008203 // AUDIO_SOURCE_HOTWORD is for internal use only:
8204 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008205 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8206 auto result = usecase;
8207 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8208 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8209 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008210 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008211 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008212 if (audio_is_remote_submix_device(device->type())) {
8213 // remote submix HAL does not support audio conversion, need source device
8214 // audio config to match the sink input descriptor audio config, otherwise AIDL
8215 // HAL patching will fail
8216 audio_port_config srcDevicePortConfig = {};
8217 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8218 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8219 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8220 srcDevicePortConfig.format = inputDesc->getFormat();
8221 patchBuilder.addSource(srcDevicePortConfig);
8222 } else {
8223 patchBuilder.addSource(device);
8224 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008225 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008226 }
8227 }
8228 return status;
8229}
8230
Eric Laurent6a94d692014-05-20 11:18:06 -07008231status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8232 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008233{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008234 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008235 ssize_t index;
8236 if (patchHandle) {
8237 index = mAudioPatches.indexOfKey(*patchHandle);
8238 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008239 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008240 }
8241 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008242 return INVALID_OPERATION;
8243 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008244 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008245 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008246 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008247 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008248 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008249 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008250 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008251 return status;
8252}
8253
François Gaffie11d30102018-11-02 16:09:09 +01008254sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008255 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008256 audio_format_t& format,
8257 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008258 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008259{
8260 // Choose an input profile based on the requested capture parameters: select the first available
8261 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008262 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008263
Atneya Nair0f0a8032022-12-12 16:20:12 -08008264 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8265 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8266 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8267
8268 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008269
jiabin2fd710d2022-05-02 23:20:22 +00008270 for (;;) {
jiabin91beb492024-10-16 21:53:36 +00008271 sp<IOProfile> inexact = nullptr;
jiabin5e02d2b2024-09-23 19:26:19 +00008272 uint32_t inexactSamplingRate = 0;
8273 audio_format_t inexactFormat = AUDIO_FORMAT_INVALID;
8274 audio_channel_mask_t inexactChannelMask = AUDIO_CHANNEL_INVALID;
jiabin2fd710d2022-05-02 23:20:22 +00008275 uint32_t updatedSamplingRate = 0;
8276 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8277 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8278 for (const auto& hwModule : mHwModules) {
8279 for (const auto& profile : hwModule->getInputProfiles()) {
8280 // profile->log();
8281 //updatedFormat = format;
jiabin91beb492024-10-16 21:53:36 +00008282 auto compatibleScore = profile->getCompatibilityScore(
jiabin66acc432024-02-06 00:57:36 +00008283 DeviceVector(device),
8284 samplingRate,
8285 &updatedSamplingRate,
8286 format,
8287 &updatedFormat,
8288 channelMask,
8289 &updatedChannelMask,
8290 // FIXME ugly cast
jiabin91beb492024-10-16 21:53:36 +00008291 (audio_output_flags_t) flags);
8292 if (compatibleScore == IOProfile::EXACT_MATCH) {
jiabin66acc432024-02-06 00:57:36 +00008293 samplingRate = updatedSamplingRate;
8294 format = updatedFormat;
8295 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008296 return profile;
jiabin91beb492024-10-16 21:53:36 +00008297 } else if ((flags != AUDIO_INPUT_FLAG_NONE
8298 && compatibleScore == IOProfile::PARTIAL_MATCH_WITH_FLAG)
8299 || (inexact == nullptr && compatibleScore != IOProfile::NO_MATCH)) {
8300 inexact = profile;
jiabin5e02d2b2024-09-23 19:26:19 +00008301 inexactSamplingRate = updatedSamplingRate;
8302 inexactFormat = updatedFormat;
8303 inexactChannelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008304 }
8305 }
8306 }
8307
jiabin91beb492024-10-16 21:53:36 +00008308 if (inexact != nullptr) {
jiabin5e02d2b2024-09-23 19:26:19 +00008309 samplingRate = inexactSamplingRate;
8310 format = inexactFormat;
8311 channelMask = inexactChannelMask;
jiabin91beb492024-10-16 21:53:36 +00008312 return inexact;
jiabin2fd710d2022-05-02 23:20:22 +00008313 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8314 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8315 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8316 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8317 flags = AUDIO_INPUT_FLAG_NONE;
8318 } else { // fail
8319 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8320 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8321 samplingRate, format, channelMask, oriFlags);
8322 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008323 }
8324 }
jiabin2fd710d2022-05-02 23:20:22 +00008325
8326 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008327}
8328
Vlad Popa87e0e582024-05-20 18:49:20 -07008329float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8330 VolumeSource volumeSource,
8331 int index,
8332 const DeviceTypeSet &deviceTypes)
8333{
8334 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8335 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8336 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8337
8338 if (com_android_media_audio_abs_volume_index_fix()) {
Vlad Popa08502d82024-10-22 20:17:47 -07008339 const auto it = mAbsoluteVolumeDrivingStreams.find(volumeDevice);
8340 if (it != mAbsoluteVolumeDrivingStreams.end()) {
8341 audio_attributes_t attributesToDriveAbs = it->second;
Vlad Popa87e0e582024-05-20 18:49:20 -07008342 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8343 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8344 ALOGD("%s: no group matching with %s", __FUNCTION__,
8345 toString(attributesToDriveAbs).c_str());
8346 return volumeDb;
8347 }
8348
8349 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8350 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8351 if (vsToDriveAbs == volumeSource) {
8352 // attenuation is applied by the abs volume controller
Vlad Popa444e95e2024-11-07 18:26:20 -08008353 // do not mute LE broadcast to allow the secondary device to continue playing
8354 return (index != 0 || volumeDevice == AUDIO_DEVICE_OUT_BLE_BROADCAST) ? volumeDbMax
8355 : volumeDb;
Vlad Popa87e0e582024-05-20 18:49:20 -07008356 } else {
8357 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8358 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8359 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8360 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8361 curvesAbs.getVolumeIndexMax());
8362 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8363 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8364 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8365 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8366 return newVolumeDb;
8367 }
8368 }
8369 return volumeDb;
8370 } else {
8371 return volumeDb;
8372 }
8373}
8374
François Gaffieaaac0fd2018-11-22 17:56:39 +01008375float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8376 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008377 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008378 const DeviceTypeSet& deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008379 bool adjustAttenuation,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008380 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008381{
Vlad Popa9d482762024-06-21 16:40:23 -07008382 float volumeDb;
8383 if (adjustAttenuation) {
8384 volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
8385 } else {
8386 volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
8387 }
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008388 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8389 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8390
8391 if (!computeInternalInteraction) {
8392 return volumeDb;
8393 }
8394
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008395 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8396 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8397 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8398 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008399 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8400 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8401 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8402 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8403 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008404 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008405 mOutputs.isActive(ringVolumeSrc, 0)) {
8406 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008407 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008408 adjustAttenuation,
8409 /* computeInternalInteraction= */false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008410 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008411 }
8412
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008413 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008414 if ((volumeSource != callVolumeSrc && (isInCall() ||
8415 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008416 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008417 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8418 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008419 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8420 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8421 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008422 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008423 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008424 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008425 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008426 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
Vlad Popa9d482762024-06-21 16:40:23 -07008427 adjustAttenuation, /* computeInternalInteraction= */false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008428 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008429 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8430 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8431 // programmatically muted.
8432 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8433 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8434 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008435 bool exemptFromCapping =
8436 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8437 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008438 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8439 volumeSource, volumeDb);
8440 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008441 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8442 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8443 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008444 }
8445 }
Eric Laurente552edb2014-03-10 17:42:56 -07008446 // if a headset is connected, apply the following rules to ring tones and notifications
8447 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008448 // - always attenuate notifications volume by 6dB
8449 // - attenuate ring tones volume by 6dB unless music is not playing and
8450 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008451 // - if music is playing, always limit the volume to current music volume,
8452 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008453 if (!Intersection(deviceTypes,
8454 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8455 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008456 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8457 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008458 ((volumeSource == alarmVolumeSrc ||
8459 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008460 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8461 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8462 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008463 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8464 curves.canBeMuted()) {
8465
Eric Laurente552edb2014-03-10 17:42:56 -07008466 // when the phone is ringing we must consider that music could have been paused just before
8467 // by the music application and behave as if music was active if the last music track was
8468 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008469 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8470 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008471 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008472 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008473 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8474 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008475 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008476 float musicVolDb = computeVolume(musicCurves,
8477 musicVolumeSrc,
8478 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008479 musicDevice,
Vlad Popa9d482762024-06-21 16:40:23 -07008480 adjustAttenuation,
8481 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008482 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8483 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8484 if (volumeDb > minVolDb) {
8485 volumeDb = minVolDb;
8486 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008487 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008488 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8489 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008490 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8491 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8492 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8493 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008494 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008495 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008496 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8497 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008498 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8499 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008500 }
8501 }
jiabin9a3361e2019-10-01 09:38:30 -07008502 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008503 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008504 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008505 }
8506 }
8507
François Gaffie43c73442018-11-08 08:21:55 +01008508 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008509}
8510
Eric Laurent3839bc02018-07-10 18:33:34 -07008511int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008512 VolumeSource fromVolumeSource,
8513 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008514{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008515 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008516 return srcIndex;
8517 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008518 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8519 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008520 float minSrc = (float)srcCurves.getVolumeIndexMin();
8521 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8522 float minDst = (float)dstCurves.getVolumeIndexMin();
8523 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008524
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008525 // preserve mute request or correct range
8526 if (srcIndex < minSrc) {
8527 if (srcIndex == 0) {
8528 return 0;
8529 }
8530 srcIndex = minSrc;
8531 } else if (srcIndex > maxSrc) {
8532 srcIndex = maxSrc;
8533 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008534 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8535}
8536
François Gaffieaaac0fd2018-11-22 17:56:39 +01008537status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8538 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008539 int index,
8540 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008541 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008542 int delayMs,
8543 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008544{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008545 // APM is single threaded, and single instance.
8546 static std::set<IVolumeCurves*> invalidCurvesReported;
8547
François Gaffieaaac0fd2018-11-22 17:56:39 +01008548 // do not change actual attributes volume if the attributes is muted
Vlad Popa1e865e62024-08-15 19:11:42 -07008549 if (!com_android_media_audio_ring_my_car() && outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008550 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8551 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008552 return NO_ERROR;
8553 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008554
Eric Laurentae6e88c2024-01-10 14:42:57 +01008555 bool isVoiceVolSrc;
8556 bool isBtScoVolSrc;
8557 if (!isVolumeConsistentForCalls(
8558 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008559 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01008560 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008561 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008562 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01008563
jiabin9a3361e2019-10-01 09:38:30 -07008564 if (deviceTypes.empty()) {
8565 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008566 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008567 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008568 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008569 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008570
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008571 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008572 if (!invalidCurvesReported.count(&curves)) {
8573 invalidCurvesReported.insert(&curves);
8574 String8 dump;
8575 curves.dump(&dump);
8576 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8577 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008578 return BAD_VALUE;
8579 }
8580
jiabin9a3361e2019-10-01 09:38:30 -07008581 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
Eric Laurentc32e6692024-10-04 14:32:28 +00008582 const VolumeSource dtmfVolSrc = toVolumeSource(AUDIO_STREAM_DTMF, false);
jiabin9a3361e2019-10-01 09:38:30 -07008583 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008584 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurentc32e6692024-10-04 14:32:28 +00008585 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc
8586 || (isInCall() && (dtmfVolSrc == volumeSource))) &&
chenxin2095559032024-06-15 13:59:29 +08008587 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8588 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008589 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008590 }
Vlad Popa1e865e62024-08-15 19:11:42 -07008591
8592 bool muted;
8593 if (!com_android_media_audio_ring_my_car()) {
8594 muted = (index == 0) && (volumeDb != 0.0f);
8595 } else {
8596 muted = curves.isMuted();
8597 }
Eric Laurent31a428a2023-08-11 12:16:28 +02008598 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8599 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008600
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008601 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Vlad Popad80ed572024-11-06 18:28:17 -08008602 bool voiceVolumeManagedByHost = !isBtScoVolSrc &&
chenxin2095559032024-06-15 13:59:29 +08008603 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8604 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008605 }
Eric Laurente552edb2014-03-10 17:42:56 -07008606 return NO_ERROR;
8607}
8608
Eric Laurentae6e88c2024-01-10 14:42:57 +01008609void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008610 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008611 float voiceVolume;
Vlad Popa1e865e62024-08-15 19:11:42 -07008612
8613 if (com_android_media_audio_ring_my_car() && curves.isMuted()) {
8614 index = 0;
8615 }
8616
chenxin2095559032024-06-15 13:59:29 +08008617 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurentae6e88c2024-01-10 14:42:57 +01008618 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008619 if (voiceVolumeManagedByHost) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01008620 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8621 } else {
8622 voiceVolume = index == 0 ? 0.0 : 1.0;
8623 }
8624 if (voiceVolume != mLastVoiceVolume) {
8625 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8626 mLastVoiceVolume = voiceVolume;
8627 }
8628}
8629
8630bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8631 const DeviceTypeSet& deviceTypes,
8632 bool& isVoiceVolSrc,
8633 bool& isBtScoVolSrc,
8634 const char* caller) {
8635 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
Vlad Popa695b76b2024-06-14 16:49:25 -07008636 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8637
Eric Laurentae6e88c2024-01-10 14:42:57 +01008638 const bool isScoRequested = isScoRequestedForComm();
8639 const bool isHAUsed = isHearingAidUsedForComm();
8640
Vlad Popa695b76b2024-06-14 16:49:25 -07008641 if (com_android_media_audio_replace_stream_bt_sco()) {
8642 ALOGV("%s stream bt sco is replaced, no volume consistency check for calls", __func__);
8643 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource) &&
8644 (isScoRequested || isHAUsed);
8645 return true;
8646 }
8647
8648 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
Eric Laurentae6e88c2024-01-10 14:42:57 +01008649 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8650
8651 if ((callVolSrc != btScoVolSrc) &&
8652 ((isVoiceVolSrc && isScoRequested) ||
8653 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8654 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8655 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8656 volumeSource, isScoRequested ? " " : " not ");
8657 return false;
8658 }
8659 return true;
8660}
8661
Eric Laurentc75307b2015-03-17 15:29:32 -07008662void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008663 const DeviceTypeSet& deviceTypes,
8664 int delayMs,
8665 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008666{
jiabincd510522020-01-22 09:40:55 -08008667 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008668 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8669 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
Vlad Popa1e865e62024-08-15 19:11:42 -07008670 checkAndSetVolume(curves, toVolumeSource(volumeGroup), curves.getVolumeIndex(deviceTypes),
jiabin9a3361e2019-10-01 09:38:30 -07008671 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008672 }
8673}
8674
François Gaffiec005e562018-11-06 15:04:49 +01008675void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8676 bool on,
8677 const sp<AudioOutputDescriptor>& outputDesc,
8678 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008679 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008680{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008681 std::vector<VolumeSource> sourcesToMute;
8682 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8683 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8684 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008685 VolumeSource source = toVolumeSource(attributes, false);
8686 if ((source != VOLUME_SOURCE_NONE) &&
8687 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8688 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008689 sourcesToMute.push_back(source);
8690 }
Eric Laurente552edb2014-03-10 17:42:56 -07008691 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008692 for (auto source : sourcesToMute) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008693 setVolumeSourceMutedInternally(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008694 }
8695
Eric Laurente552edb2014-03-10 17:42:56 -07008696}
8697
Vlad Popa1e865e62024-08-15 19:11:42 -07008698void AudioPolicyManager::setVolumeSourceMutedInternally(VolumeSource volumeSource,
8699 bool on,
8700 const sp<AudioOutputDescriptor>& outputDesc,
8701 int delayMs,
8702 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008703{
jiabin9a3361e2019-10-01 09:38:30 -07008704 if (deviceTypes.empty()) {
8705 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008706 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008707 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008708 if (on) {
Vlad Popa1e865e62024-08-15 19:11:42 -07008709 if (!outputDesc->isMutedInternally(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008710 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008711 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008712 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8713 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008714 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008715 }
8716 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008717 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8718 // ignored
8719 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008720 } else {
Vlad Popa1e865e62024-08-15 19:11:42 -07008721 if (!outputDesc->isMutedInternally(volumeSource)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008722 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008723 return;
8724 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008725 if (outputDesc->decMuteCount(volumeSource) == 0) {
8726 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008727 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008728 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008729 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008730 delayMs);
8731 }
8732 }
8733}
8734
François Gaffie53615e22015-03-19 09:24:12 +01008735bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8736{
Vlad Popa7f1823b2024-11-05 15:37:52 -08008737 if ((paa->flags & AUDIO_FLAG_SCO) != 0) {
8738 ALOGW("%s: deprecated use of AUDIO_FLAG_SCO in attributes flags %d", __func__, paa->flags);
8739 }
8740
François Gaffiec005e562018-11-06 15:04:49 +01008741 // has flags that map to a stream type?
Vlad Popa7f1823b2024-11-05 15:37:52 -08008742 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_BEACON)) != 0) {
Eric Laurente83b55d2014-11-14 10:06:21 -08008743 return true;
8744 }
8745
8746 // has known usage?
8747 switch (paa->usage) {
8748 case AUDIO_USAGE_UNKNOWN:
8749 case AUDIO_USAGE_MEDIA:
8750 case AUDIO_USAGE_VOICE_COMMUNICATION:
8751 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8752 case AUDIO_USAGE_ALARM:
8753 case AUDIO_USAGE_NOTIFICATION:
8754 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8755 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8756 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8757 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8758 case AUDIO_USAGE_NOTIFICATION_EVENT:
8759 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8760 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8761 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8762 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008763 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008764 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008765 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008766 case AUDIO_USAGE_EMERGENCY:
8767 case AUDIO_USAGE_SAFETY:
8768 case AUDIO_USAGE_VEHICLE_STATUS:
8769 case AUDIO_USAGE_ANNOUNCEMENT:
Jean-Michel Trivid9add572024-11-05 14:48:40 -08008770 case AUDIO_USAGE_SPEAKER_CLEANUP:
Eric Laurente83b55d2014-11-14 10:06:21 -08008771 break;
8772 default:
8773 return false;
8774 }
8775 return true;
8776}
8777
François Gaffie2110e042015-03-24 08:41:51 +01008778audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8779{
8780 return mEngine->getForceUse(usage);
8781}
8782
Eric Laurent96d1dda2022-03-14 17:14:19 +01008783bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008784 return isStateInCall(mEngine->getPhoneState());
8785}
8786
Eric Laurent96d1dda2022-03-14 17:14:19 +01008787bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008788 return is_state_in_call(state);
8789}
8790
Eric Laurentf9cccec2022-11-16 19:12:00 +01008791bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008792 audio_mode_t mode = mEngine->getPhoneState();
8793 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008794 || (mode == AUDIO_MODE_CALL_SCREEN)
8795 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008796}
8797
Eric Laurentf9cccec2022-11-16 19:12:00 +01008798bool AudioPolicyManager::isInCallOrScreening() const {
8799 audio_mode_t mode = mEngine->getPhoneState();
8800 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8801}
8802
Eric Laurentd60560a2015-04-10 11:31:20 -07008803void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8804{
8805 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008806 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008807 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008808 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurentccbd7872024-06-20 12:34:15 +00008809 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008810 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008811 }
8812 }
8813
8814 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8815 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8816 bool release = false;
8817 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8818 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8819 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8820 source->ext.device.type == deviceDesc->type()) {
8821 release = true;
8822 }
8823 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008824 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008825 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8826 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8827 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008828 sink->ext.device.type == deviceDesc->type() &&
8829 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8830 || strncmp(sink->ext.device.address, address,
8831 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008832 release = true;
8833 }
8834 }
8835 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008836 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8837 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008838 }
8839 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008840
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008841 mInputs.clearSessionRoutesForDevice(deviceDesc);
8842
Francois Gaffie716e1432019-01-14 16:58:59 +01008843 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008844}
8845
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008846void AudioPolicyManager::modifySurroundFormats(
8847 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008848 std::unordered_set<audio_format_t> enforcedSurround(
8849 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008850 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008851 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008852 allSurround.insert(pair.first);
8853 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8854 }
Phil Burk09bc4612016-02-24 15:58:15 -08008855
8856 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8857 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008858 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008859 // This is the resulting set of formats depending on the surround mode:
8860 // 'all surround' = allSurround
8861 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8862 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8863 // 'manual surround' = mManualSurroundFormats
8864 // AUTO: formats v 'enforced surround'
8865 // ALWAYS: formats v 'all surround' v 'enforced surround'
8866 // NEVER: formats ^ 'non-surround'
8867 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008868
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008869 std::unordered_set<audio_format_t> formatSet;
8870 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8871 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008872 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008873 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008874 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008875 formatSet.insert(*formatIter);
8876 }
8877 }
8878 } else {
8879 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8880 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008881 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008882
jiabin81772902018-04-02 17:52:27 -07008883 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008884 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008885 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8886 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8887 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008888 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008889 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8890 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8891 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008892 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008893 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008894 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008895 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008896 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008897 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008898}
8899
jiabin06e4bab2019-07-29 10:13:34 -07008900void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8901 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008902 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8903 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8904
8905 // If NEVER, then remove support for channelMasks > stereo.
8906 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008907 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8908 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008909 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008910 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008911 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008912 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008913 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008914 }
8915 }
jiabin81772902018-04-02 17:52:27 -07008916 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8917 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8918 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008919 bool supports5dot1 = false;
8920 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008921 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008922 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8923 supports5dot1 = true;
8924 break;
8925 }
8926 }
8927 // If not then add 5.1 support.
8928 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008929 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008930 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008931 }
Phil Burk09bc4612016-02-24 15:58:15 -08008932 }
8933}
8934
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008935void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008936 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008937 const sp<IOProfile>& profile) {
8938 if (!profile->hasDynamicAudioProfile()) {
8939 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008940 }
François Gaffie112b0af2015-11-19 16:13:25 +01008941
jiabin12537fc2023-10-12 17:56:08 +00008942 audio_port_v7 devicePort;
8943 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008944
jiabin12537fc2023-10-12 17:56:08 +00008945 audio_port_v7 mixPort;
8946 profile->toAudioPort(&mixPort);
8947 mixPort.ext.mix.handle = ioHandle;
8948
8949 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8950 if (status != NO_ERROR) {
8951 ALOGE("%s failed to query the attributes of the mix port", __func__);
8952 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008953 }
jiabin12537fc2023-10-12 17:56:08 +00008954
8955 std::set<audio_format_t> supportedFormats;
8956 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8957 supportedFormats.insert(mixPort.audio_profiles[i].format);
8958 }
8959 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8960 mReportedFormatsMap[devDesc] = formats;
8961
8962 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008963 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8964 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008965 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8966 modifySurroundFormats(devDesc, &formats);
8967 size_t modifiedNumProfiles = 0;
8968 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8969 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8970 formats.end()) {
8971 // Skip the format that is not present after modifying surround formats.
8972 continue;
8973 }
8974 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8975 sizeof(struct audio_profile));
8976 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8977 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8978 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8979 modifySurroundChannelMasks(&channels);
8980 std::copy(channels.begin(), channels.end(),
8981 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8982 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8983 }
8984 mixPort.num_audio_profiles = modifiedNumProfiles;
8985 }
8986 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008987}
Eric Laurentd60560a2015-04-10 11:31:20 -07008988
Mikhail Naganovdc769682018-05-04 15:34:08 -07008989status_t AudioPolicyManager::installPatch(const char *caller,
8990 audio_patch_handle_t *patchHandle,
8991 AudioIODescriptorInterface *ioDescriptor,
8992 const struct audio_patch *patch,
8993 int delayMs)
8994{
8995 ssize_t index = mAudioPatches.indexOfKey(
8996 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8997 *patchHandle : ioDescriptor->getPatchHandle());
8998 sp<AudioPatch> patchDesc;
8999 status_t status = installPatch(
9000 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
9001 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01009002 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07009003 }
9004 return status;
9005}
9006
9007status_t AudioPolicyManager::installPatch(const char *caller,
9008 ssize_t index,
9009 audio_patch_handle_t *patchHandle,
9010 const struct audio_patch *patch,
9011 int delayMs,
9012 uid_t uid,
9013 sp<AudioPatch> *patchDescPtr)
9014{
9015 sp<AudioPatch> patchDesc;
9016 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
9017 if (index >= 0) {
9018 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01009019 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009020 }
9021
9022 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
9023 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
9024 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
9025 if (status == NO_ERROR) {
9026 if (index < 0) {
9027 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01009028 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009029 } else {
9030 patchDesc->mPatch = *patch;
9031 }
François Gaffieafd4cea2019-11-18 15:50:22 +01009032 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07009033 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01009034 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07009035 }
9036 nextAudioPortGeneration();
9037 mpClientInterface->onAudioPatchListUpdate();
9038 }
9039 if (patchDescPtr) *patchDescPtr = patchDesc;
9040 return status;
9041}
9042
jiabinbce0c1d2020-10-05 11:20:18 -07009043bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
9044{
9045 const TrackClientVector activeClients = output->getActiveClients();
9046 if (activeClients.empty()) {
9047 return true;
9048 }
9049 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
9050 if (index < 0) {
9051 ALOGE("%s, no audio patch found while there are active clients on output %d",
9052 __func__, output->getId());
9053 return false;
9054 }
9055 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
9056 DeviceVector routedDevices;
9057 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
9058 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
9059 patchDesc->mPatch.sinks[i].id);
9060 if (device == nullptr) {
9061 ALOGE("%s, no audio device found with id(%d)",
9062 __func__, patchDesc->mPatch.sinks[i].id);
9063 return false;
9064 }
9065 routedDevices.add(device);
9066 }
9067 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08009068 if (client->isInvalid()) {
9069 // No need to take care about invalidated clients.
9070 continue;
9071 }
jiabinbce0c1d2020-10-05 11:20:18 -07009072 sp<DeviceDescriptor> preferredDevice =
9073 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
9074 if (mEngine->getOutputDevicesForAttributes(
9075 client->attributes(), preferredDevice, false) == routedDevices) {
9076 return false;
9077 }
9078 }
9079 return true;
9080}
9081
9082sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01009083 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00009084 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
9085 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07009086{
9087 for (const auto& device : devices) {
9088 // TODO: This should be checking if the profile supports the device combo.
9089 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00009090 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
9091 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07009092 return nullptr;
9093 }
9094 }
9095 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
9096 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangf6e304f2024-07-09 23:06:58 -07009097 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00009098 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009099 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009100 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00009101 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07009102 return nullptr;
9103 }
jiabin14b50cc2023-12-13 19:01:52 +00009104 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
9105 auto portConfig = desc->getConfig();
9106 for (const auto& device : devices) {
9107 device->setPreferredConfig(&portConfig);
9108 }
9109 }
jiabinbce0c1d2020-10-05 11:20:18 -07009110
9111 // Here is where the out_set_parameters() for card & device gets called
9112 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
9113 const audio_devices_t deviceType = device->type();
9114 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00009115 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07009116 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
9117 mpClientInterface->setParameters(output, String8(param));
9118 free(param);
9119 }
jiabin12537fc2023-10-12 17:56:08 +00009120 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07009121 if (!profile->hasValidAudioProfile()) {
9122 ALOGW("%s() missing param", __func__);
9123 desc->close();
9124 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00009125 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
9126 // Reopen the output with the best audio profile picked by APM when the profile supports
9127 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07009128 desc->close();
9129 output = AUDIO_IO_HANDLE_NONE;
9130 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
9131 profile->pickAudioProfile(
9132 config.sample_rate, config.channel_mask, config.format);
9133 config.offload_info.sample_rate = config.sample_rate;
9134 config.offload_info.channel_mask = config.channel_mask;
9135 config.offload_info.format = config.format;
9136
Dean Wheatleydfb67b82024-01-23 09:36:29 +11009137 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangf6e304f2024-07-09 23:06:58 -07009138 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07009139 if (status != NO_ERROR) {
9140 return nullptr;
9141 }
9142 }
9143
9144 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07009145 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
9146 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
9147 hwModule->getHalVersionMajor() >= 3) {
9148 setOutputDevices(__func__, desc, devices, true, 0, NULL);
9149 }
baek.kim -61c20122022-07-27 10:05:32 +00009150 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
9151 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
9152
jiabinbce0c1d2020-10-05 11:20:18 -07009153 if (audio_is_remote_submix_device(deviceType) && address != "0") {
9154 sp<AudioPolicyMix> policyMix;
9155 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
9156 policyMix->setOutput(desc);
9157 desc->mPolicyMix = policyMix;
9158 } else {
9159 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00009160 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07009161 }
9162
baek.kim -61c20122022-07-27 10:05:32 +00009163 } else if (hasPrimaryOutput() && speaker != nullptr
9164 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01009165 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
9166 // no duplicated output for:
9167 // - direct outputs
9168 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00009169 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07009170 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
9171
9172 //TODO: configure audio effect output stage here
9173
9174 // open a duplicating output thread for the new output and the primary output
9175 sp<SwAudioOutputDescriptor> dupOutputDesc =
9176 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
9177 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
9178 if (status == NO_ERROR) {
9179 // add duplicated output descriptor
9180 addOutput(duplicatedOutput, dupOutputDesc);
9181 } else {
9182 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
9183 mPrimaryOutput->mIoHandle, output);
9184 desc->close();
9185 removeOutput(output);
9186 nextAudioPortGeneration();
9187 return nullptr;
9188 }
9189 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009190 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
9191 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
9192 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02009193 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02009194 }
jiabinbce0c1d2020-10-05 11:20:18 -07009195 return desc;
9196}
9197
jiabinf1c73972022-04-14 16:28:52 -07009198status_t AudioPolicyManager::getDevicesForAttributes(
9199 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
wenyu zhang8558a332024-09-09 15:12:48 +00009200 // attr containing source set by AudioAttributes.Builder.setCapturePreset() has precedence
9201 // over any usage or content type also present in attr.
9202 if (com::android::media::audioserver::enable_audio_input_device_routing() &&
9203 attr.source != AUDIO_SOURCE_INVALID) {
9204 return getInputDevicesForAttributes(attr, devices);
9205 }
9206
jiabinf1c73972022-04-14 16:28:52 -07009207 // Devices are determined in the following precedence:
9208 //
9209 // 1) Devices associated with a dynamic policy matching the attributes. This is often
9210 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
9211 //
9212 // If no such dynamic policy then
9213 // 2) Devices containing an active client using setPreferredDevice
9214 // with same strategy as the attributes.
9215 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9216 //
9217 // If no corresponding active client with setPreferredDevice then
9218 // 3) Devices associated with the strategy determined by the attributes
9219 // (from the default Engine::getOutputDevicesForAttributes() implementation).
9220 //
9221 // See related getOutputForAttrInt().
9222
9223 // check dynamic policies but only for primary descriptors (secondary not used for audible
9224 // audio routing, only used for duplication for playback capture)
9225 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08009226 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07009227 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08009228 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
9229 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
9230 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07009231 if (status != OK) {
9232 return status;
9233 }
9234
9235 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
9236 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9237 // as they are unaffected by device/stream volume
9238 // (per SwAudioOutputDescriptor::isFixedVolume()).
9239 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9240 ) {
9241 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9242 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9243 devices.add(deviceDesc);
9244 } else {
9245 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9246 // which selects setPreferredDevice if active. This means forVolume call
9247 // will take an active setPreferredDevice, if such exists.
9248
9249 devices = mEngine->getOutputDevicesForAttributes(
9250 attr, nullptr /* preferredDevice */, false /* fromCache */);
9251 }
9252
9253 if (forVolume) {
9254 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9255 // for single volume control in AudioService (such relationship should exist if
9256 // SPEAKER_SAFE is present).
9257 //
9258 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9259 DeviceVector speakerSafeDevices =
9260 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9261 if (!speakerSafeDevices.isEmpty()) {
9262 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9263 devices.remove(speakerSafeDevices);
9264 }
9265 }
9266
9267 return NO_ERROR;
9268}
9269
wenyu zhang8558a332024-09-09 15:12:48 +00009270status_t AudioPolicyManager::getInputDevicesForAttributes(
9271 const audio_attributes_t &attr, DeviceVector &devices) {
9272 devices = DeviceVector(
9273 mEngine->getInputDeviceForAttributes(attr, 0 /*uid unknown here*/,
9274 AUDIO_SESSION_NONE,
9275 nullptr /* mix */));
9276 return NO_ERROR;
9277}
9278
jiabinf1c73972022-04-14 16:28:52 -07009279status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9280 AudioProfileVector& audioProfiles,
9281 uint32_t flags,
9282 bool isInput) {
9283 for (const auto& hwModule : mHwModules) {
9284 // the MSD module checks for different conditions
9285 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9286 continue;
9287 }
9288 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9289 : hwModule->getOutputProfiles();
9290 for (const auto& profile : ioProfiles) {
9291 if (!profile->areAllDevicesSupported(devices) ||
jiabin91beb492024-10-16 21:53:36 +00009292 !profile->isCompatibleProfileForFlags(flags)) {
jiabinf1c73972022-04-14 16:28:52 -07009293 continue;
9294 }
9295 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9296 }
9297 }
9298
9299 if (!isInput) {
9300 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9301 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9302 if (msdModule != nullptr) {
9303 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9304 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9305 for (const auto &profile: msdModule->getOutputProfiles()) {
9306 if (!profile->asAudioPort()->isDirectOutput()) {
9307 continue;
9308 }
9309 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9310 }
9311 } else {
9312 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9313 }
9314 }
9315 }
9316
9317 return NO_ERROR;
9318}
9319
jiabin3ff8d7d2022-12-13 06:27:44 +00009320sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9321 const audio_config_t *config,
9322 audio_output_flags_t flags,
9323 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009324 closeOutput(outputDesc->mIoHandle);
9325 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9326 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9327 if (preferredOutput == nullptr) {
9328 ALOGE("%s failed to reopen output device=%d, caller=%s",
9329 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009330 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009331 return preferredOutput;
9332}
9333
9334void AudioPolicyManager::reopenOutputsWithDevices(
9335 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9336 for (const auto& [output, devices] : outputsToReopen) {
9337 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9338 closeOutput(output);
9339 openOutputWithProfileAndDevice(desc->mProfile, devices);
9340 }
jiabina84c3d32022-12-02 18:59:55 +00009341}
9342
jiabinc44b3462022-12-08 12:52:31 -08009343PortHandleVector AudioPolicyManager::getClientsForStream(
9344 audio_stream_type_t streamType) const {
9345 PortHandleVector clients;
9346 for (size_t i = 0; i < mOutputs.size(); ++i) {
9347 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9348 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9349 }
9350 return clients;
9351}
9352
9353void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9354 PortHandleVector clients;
9355 for (auto stream : streams) {
9356 PortHandleVector clientsForStream = getClientsForStream(stream);
9357 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9358 }
9359 mpClientInterface->invalidateTracks(clients);
9360}
9361
jiabin220eea12024-05-17 17:55:20 +00009362void AudioPolicyManager::updateClientsInternalMute(
9363 const sp<android::SwAudioOutputDescriptor> &desc) {
9364 if (!desc->isBitPerfect() ||
9365 !com::android::media::audioserver::
9366 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9367 // This is only used for bit perfect output now.
9368 return;
9369 }
9370 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9371 bool bitPerfectClientInternalMute = false;
9372 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9373 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9374 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9375 bitPerfectClient = client;
9376 continue;
9377 }
9378 bool muted = false;
9379 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9380 // System sound is muted.
9381 muted = true;
9382 } else {
9383 bitPerfectClientInternalMute = true;
9384 }
9385 if (client->setInternalMute(muted)) {
9386 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9387 if (!result.ok()) {
9388 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9389 continue;
9390 }
9391 media::TrackInternalMuteInfo info;
9392 info.portId = result.value();
9393 info.muted = client->getInternalMute();
9394 clientsInternalMute.push_back(std::move(info));
9395 }
9396 }
9397 if (bitPerfectClient != nullptr &&
9398 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9399 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9400 if (result.ok()) {
9401 media::TrackInternalMuteInfo info;
9402 info.portId = result.value();
9403 info.muted = bitPerfectClient->getInternalMute();
9404 clientsInternalMute.push_back(std::move(info));
9405 } else {
9406 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9407 __func__, bitPerfectClient->portId());
9408 }
9409 }
9410 if (!clientsInternalMute.empty()) {
9411 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9412 status != NO_ERROR) {
9413 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9414 }
9415 }
9416}
9417
Jiabin Huangaa6e9e32024-10-21 17:19:28 +00009418status_t AudioPolicyManager::getMmapPolicyInfos(AudioMMapPolicyType policyType,
9419 std::vector<AudioMMapPolicyInfo> *policyInfos) {
9420 if (policyType != AudioMMapPolicyType::DEFAULT &&
9421 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9422 return BAD_VALUE;
9423 }
9424 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9425 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9426 return status;
9427 }
9428 }
9429 *policyInfos = mMmapPolicyInfos[policyType];
9430 return NO_ERROR;
9431}
9432
9433status_t AudioPolicyManager::getMmapPolicyForDevice(
9434 AudioMMapPolicyType policyType, AudioMMapPolicyInfo *policyInfo) {
9435 if (policyType != AudioMMapPolicyType::DEFAULT &&
9436 policyType != AudioMMapPolicyType::EXCLUSIVE) {
9437 return BAD_VALUE;
9438 }
9439 if (mMmapPolicyByDeviceType.count(policyType) == 0) {
9440 if (status_t status = updateMmapPolicyInfos(policyType); status != NO_ERROR) {
9441 return status;
9442 }
9443 }
9444 auto it = mMmapPolicyByDeviceType[policyType].find(policyInfo->device.type);
9445 policyInfo->mmapPolicy = it == mMmapPolicyByDeviceType[policyType].end()
9446 ? AudioMMapPolicy::NEVER : it->second;
9447 return NO_ERROR;
9448}
9449
9450status_t AudioPolicyManager::updateMmapPolicyInfos(AudioMMapPolicyType policyType) {
9451 std::vector<AudioMMapPolicyInfo> policyInfos;
9452 if (status_t status = mpClientInterface->getMmapPolicyInfos(policyType, &policyInfos);
9453 status != NO_ERROR) {
9454 ALOGE("%s, failed, error = %d", __func__, status);
9455 return status;
9456 }
9457 std::map<AudioDeviceDescription, AudioMMapPolicy> mmapPolicyByDeviceType;
9458 if (policyInfos.size() == 1 && policyInfos[0].device == AudioDevice()) {
9459 // When there is only one AudioMMapPolicyInfo instance and the device is a default value,
9460 // it indicates the mmap policy is reported via system property. In that case, use the
9461 // routing information to fill details for how mmap is supported for a particular device.
9462 for (const auto &hwModule: mHwModules) {
9463 for (const auto &profile: hwModule->getInputProfiles()) {
9464 if ((profile->getFlags() & AUDIO_INPUT_FLAG_MMAP_NOIRQ)
9465 != AUDIO_INPUT_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 for (const auto &profile: hwModule->getOutputProfiles()) {
9478 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)
9479 != AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) {
9480 continue;
9481 }
9482 for (const auto &device: profile->getSupportedDevices()) {
9483 auto deviceDesc =
9484 legacy2aidl_audio_devices_t_AudioDeviceDescription(device->type());
9485 if (deviceDesc.ok()) {
9486 mmapPolicyByDeviceType.emplace(
9487 deviceDesc.value(), policyInfos[0].mmapPolicy);
9488 }
9489 }
9490 }
9491 }
9492 } else {
9493 for (const auto &info: policyInfos) {
9494 mmapPolicyByDeviceType[info.device.type] = info.mmapPolicy;
9495 }
9496 }
9497 mMmapPolicyByDeviceType.emplace(policyType, mmapPolicyByDeviceType);
9498 mMmapPolicyInfos.emplace(policyType, policyInfos);
9499 return NO_ERROR;
9500}
9501
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009502} // namespace android