blob: 354c59caff4db8d9f46f16a406de934f8541eb58 [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
21// to enable VERBOSE logging dynamically.
22// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Marvin Raminbdefaf02023-11-01 09:10:32 +010045#include <android_media_audiopolicy.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080046#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070047#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070048#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070049#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070050#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070051#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070052#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070053#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070054#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070055#include <utils/Log.h>
56
Eric Laurentd4692962014-05-05 18:13:44 -070057#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010058#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070059
Eric Laurent3b73df72014-03-11 09:06:29 -070060namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070061
Marvin Raminbdefaf02023-11-01 09:10:32 +010062
63namespace audio_flags = android::media::audiopolicy;
64
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010065using android::media::audio::common::AudioDevice;
66using android::media::audio::common::AudioDeviceAddress;
67using android::media::audio::common::AudioPortDeviceExt;
68using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000069using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070070
Eric Laurentdc462862016-07-19 12:29:53 -070071//FIXME: workaround for truncated touch sounds
72// to be removed when the problem is handled by system UI
73#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070074
75// Largest difference in dB on earpiece in call between the voice volume and another
76// media / notification / system volume.
77constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
78
jiabin06e4bab2019-07-29 10:13:34 -070079template <typename T>
80bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
81{
82 if (left.size() != right.size()) {
83 return false;
84 }
85 for (size_t index = 0; index < right.size(); index++) {
86 if (left[index] != right[index]) {
87 return false;
88 }
89 }
90 return true;
91}
92
93template <typename T>
94bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
95{
96 return !(left == right);
97}
98
Eric Laurente552edb2014-03-10 17:42:56 -070099// ----------------------------------------------------------------------------
100// AudioPolicyInterface implementation
101// ----------------------------------------------------------------------------
102
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100103status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
104 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
105 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800106 nextAudioPortGeneration();
107 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800108}
109
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100110status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
111 audio_policy_dev_state_t state,
112 const char* device_address,
113 const char* device_name,
114 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800115 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100116 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
117 status == OK) {
118 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
119 } else {
120 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
121 return status;
122 }
123}
124
Ping Tsai2a5a5242024-08-16 13:39:10 +0800125status_t AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000126 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200127{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000128 audio_port_v7 devicePort;
129 device->toAudioPort(&devicePort);
Ping Tsai2a5a5242024-08-16 13:39:10 +0800130 status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
131 ALOGE_IF(status != OK, "Error %d while setting connected state %d for device %s", status,
132 static_cast<int>(state), device->getDeviceTypeAddr().toString(false).c_str());
133
134 return status;
François Gaffie44481e72016-04-20 07:49:57 +0200135}
136
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100137status_t AudioPolicyManager::setDeviceConnectionStateInt(
138 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
139 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100140 if (port.ext.getTag() != AudioPortExt::device) {
141 return BAD_VALUE;
142 }
143 audio_devices_t device_type;
144 std::string device_address;
145 if (status_t status = aidl2legacy_AudioDevice_audio_device(
146 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
147 status != OK) {
148 return status;
149 };
150 const char* device_name = port.name.c_str();
151 // connect/disconnect only 1 device at a time
152 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
153 return BAD_VALUE;
154
155 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
156 device_type, device_address.c_str(), device_name, encodedFormat,
157 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000158 if (device == nullptr) {
159 return INVALID_OPERATION;
160 }
161 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
162 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
163 }
164 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100165}
166
François Gaffie11d30102018-11-02 16:09:09 +0100167status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800168 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100169 const char* device_address,
170 const char* device_name,
171 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800172 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100173 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
174 status == OK) {
175 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
176 } else {
177 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
178 return status;
179 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700180}
Paul McLeane743a472015-01-28 11:07:31 -0800181
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700182status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
183 audio_policy_dev_state_t state)
184{
Eric Laurente552edb2014-03-10 17:42:56 -0700185 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700186 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700187 SortedVector <audio_io_handle_t> outputs;
188
François Gaffie11d30102018-11-02 16:09:09 +0100189 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700190
Eric Laurente552edb2014-03-10 17:42:56 -0700191 // save a copy of the opened output descriptors before any output is opened or closed
192 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
193 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100194
195 bool wasLeUnicastActive = isLeUnicastActive();
196
Eric Laurente552edb2014-03-10 17:42:56 -0700197 switch (state)
198 {
199 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800200 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700201 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100202 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700203 return INVALID_OPERATION;
204 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800205 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700206 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700207
Eric Laurente552edb2014-03-10 17:42:56 -0700208 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200209 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700210 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700211 }
212
François Gaffie44481e72016-04-20 07:49:57 +0200213 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
214 // parameters on newly connected devices (instead of opening the outputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800215 if (broadcastDeviceConnectionState(
216 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
217 mAvailableOutputDevices.remove(device);
218 mHwModules.cleanUpForDevice(device);
219 ALOGE("%s() device %s format %x connection failed", __func__,
220 device->toString().c_str(), device->getEncodedFormat());
221 return INVALID_OPERATION;
222 }
François Gaffie44481e72016-04-20 07:49:57 +0200223
François Gaffie11d30102018-11-02 16:09:09 +0100224 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
225 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200226
jiabinc0048632023-04-27 22:04:31 +0000227 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Mikhail Naganov3754b642024-04-17 18:31:04 +0000228
229 mHwModules.cleanUpForDevice(device);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700230 return INVALID_OPERATION;
231 }
François Gaffie2110e042015-03-24 08:41:51 +0100232
jiabin1c4794b2020-05-05 10:08:05 -0700233 // Populate encapsulation information when a output device is connected.
234 device->setEncapsulationInfoFromHal(mpClientInterface);
235
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700236 // outputs should never be empty here
237 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
238 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100239 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800240
Eric Laurent3ae5f312015-02-03 17:12:08 -0800241 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700242 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700243 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700244 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100245 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700246 return INVALID_OPERATION;
247 }
248
François Gaffie11d30102018-11-02 16:09:09 +0100249 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700250
jiabinc0048632023-04-27 22:04:31 +0000251 // Notify the HAL to prepare to disconnect device
252 broadcastDeviceConnectionState(
253 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700254
Eric Laurente552edb2014-03-10 17:42:56 -0700255 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100256 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700257
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100258 mOutputs.clearSessionRoutesForDevice(device);
259
François Gaffie11d30102018-11-02 16:09:09 +0100260 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100261
jiabinc0048632023-04-27 22:04:31 +0000262 // Send Disconnect to HALs
263 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
264
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800265 // Reset active device codec
266 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
267
Kriti Dangef6be8f2020-11-05 11:58:19 +0100268 // remove device from mReportedFormatsMap cache
269 mReportedFormatsMap.erase(device);
270
jiabina84c3d32022-12-02 18:59:55 +0000271 // remove preferred mixer configurations
272 mPreferredMixerAttrInfos.erase(device->getId());
273
Eric Laurente552edb2014-03-10 17:42:56 -0700274 } break;
275
276 default:
François Gaffie11d30102018-11-02 16:09:09 +0100277 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700278 return BAD_VALUE;
279 }
280
Eric Laurent736a1022019-03-27 18:28:46 -0700281 // Propagate device availability to Engine
282 setEngineDeviceConnectionState(device, state);
283
Eric Laurentae970022019-01-29 14:25:04 -0800284 // No need to evaluate playback routing when connecting a remote submix
285 // output device used by a dynamic policy of type recorder as no
286 // playback use case is affected.
287 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700288 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800289 for (audio_io_handle_t output : outputs) {
290 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800291 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
292 if (policyMix != nullptr
293 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +0000294 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800295 doCheckForDeviceAndOutputChanges = false;
296 break;
297 }
298 }
299 }
300
301 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700302 // outputs must be closed after checkOutputForAllStrategies() is executed
303 if (!outputs.isEmpty()) {
304 for (audio_io_handle_t output : outputs) {
305 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100306 // close unused outputs after device disconnection or direct outputs that have
307 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200308 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200309 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
310 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200311 (desc->mDirectOpenCount == 0))
312 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
313 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200314 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700315 closeOutput(output);
316 }
Eric Laurente552edb2014-03-10 17:42:56 -0700317 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700318 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
319 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700320 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700321 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800322 };
323
324 if (doCheckForDeviceAndOutputChanges) {
325 checkForDeviceAndOutputChanges(checkCloseOutputs);
326 } else {
327 checkCloseOutputs();
328 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100329 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100330 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700331 const DeviceVector activeMediaDevices =
332 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000333 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700334 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700335 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530336 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
337 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100338 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700339 // do not force device change on duplicated output because if device is 0, it will
340 // also force a device 0 for the two outputs it is duplicated to which may override
341 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100342 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100343 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700344 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700345 // always force when disconnecting (a non-duplicated device)
346 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin220eea12024-05-17 17:55:20 +0000347 if (desc->mPreferredAttrInfo != nullptr && newDevices != desc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000348 // If the device is using preferred mixer attributes, the output need to reopen
349 // with default configuration when the new selected devices are different from
350 // current routing devices
351 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
352 continue;
353 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530354 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700355 }
jiabinbce0c1d2020-10-05 11:20:18 -0700356 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000357 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700358 desc->supportsDevicesForPlayback(activeMediaDevices)) {
359 // Reopen the output to query the dynamic profiles when there is not active
360 // clients or all active clients will be rerouted. Otherwise, set the flag
361 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
362 // can be reopened to query dynamic profiles when all clients are inactive.
363 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000364 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700365 } else {
366 desc->mPendingReopenToQueryProfiles = true;
367 }
368 }
369 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
370 // Clear the flag that previously set for re-querying profiles.
371 desc->mPendingReopenToQueryProfiles = false;
372 }
373 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000374 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700375
Eric Laurentd60560a2015-04-10 11:31:20 -0700376 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100377 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700378 }
379
Eric Laurent96d1dda2022-03-14 17:14:19 +0100380 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
381
Eric Laurent72aa32f2014-05-30 18:51:48 -0700382 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530383 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurentb71e58b2014-05-29 16:08:11 -0700384 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700385 } // end if is output device
386
Eric Laurente552edb2014-03-10 17:42:56 -0700387 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700388 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100389 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700390 switch (state)
391 {
392 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700393 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700394 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100395 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700396 return INVALID_OPERATION;
397 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700398
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530399 ALOGV("%s() connecting device %s", __func__, device->toString().c_str());
400
Eric Laurent0dd51852019-04-19 18:18:58 -0700401 if (mAvailableInputDevices.add(device) < 0) {
402 return NO_MEMORY;
403 }
404
François Gaffie44481e72016-04-20 07:49:57 +0200405 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
406 // parameters on newly connected devices (instead of opening the inputs...)
Ping Tsai2a5a5242024-08-16 13:39:10 +0800407 if (broadcastDeviceConnectionState(
408 device, media::DeviceConnectedState::CONNECTED) != NO_ERROR) {
409 mAvailableInputDevices.remove(device);
410 mHwModules.cleanUpForDevice(device);
411 ALOGE("%s() device %s format %x connection failed", __func__,
412 device->toString().c_str(), device->getEncodedFormat());
413 return INVALID_OPERATION;
414 }
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700415 // Propagate device availability to Engine
416 setEngineDeviceConnectionState(device, state);
François Gaffie44481e72016-04-20 07:49:57 +0200417
Eric Laurent0dd51852019-04-19 18:18:58 -0700418 if (checkInputsForDevice(device, state) != NO_ERROR) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700419 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE);
420
Eric Laurent0dd51852019-04-19 18:18:58 -0700421 mAvailableInputDevices.remove(device);
422
jiabinc0048632023-04-27 22:04:31 +0000423 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100424
425 mHwModules.cleanUpForDevice(device);
426
Eric Laurentd4692962014-05-05 18:13:44 -0700427 return INVALID_OPERATION;
428 }
429
Eric Laurentd4692962014-05-05 18:13:44 -0700430 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700431
432 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700433 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700434 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100435 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700436 return INVALID_OPERATION;
437 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700438
François Gaffie11d30102018-11-02 16:09:09 +0100439 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700440
jiabinc0048632023-04-27 22:04:31 +0000441 // Notify the HAL to prepare to disconnect device
442 broadcastDeviceConnectionState(
443 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700444
François Gaffie11d30102018-11-02 16:09:09 +0100445 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700446
447 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100448
jiabinc0048632023-04-27 22:04:31 +0000449 // Set Disconnect to HALs
450 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
451
Kriti Dangef6be8f2020-11-05 11:58:19 +0100452 // remove device from mReportedFormatsMap cache
453 mReportedFormatsMap.erase(device);
Mikhail Naganov2b61ab52024-05-30 16:56:25 -0700454
455 // Propagate device availability to Engine
456 setEngineDeviceConnectionState(device, state);
Eric Laurentd4692962014-05-05 18:13:44 -0700457 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700458
459 default:
François Gaffie11d30102018-11-02 16:09:09 +0100460 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700461 return BAD_VALUE;
462 }
463
Eric Laurent0dd51852019-04-19 18:18:58 -0700464 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700465 // As the input device list can impact the output device selection, update
466 // getDeviceForStrategy() cache
467 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700468
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100469 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200470 // Reconnect Audio Source
471 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
472 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
473 checkAudioSourceForAttributes(attributes);
474 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700475 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100476 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700477 }
478
Eric Laurentb52c1522014-05-20 11:27:36 -0700479 mpClientInterface->onAudioPortListUpdate();
Jaideep Sharmac1857d42024-06-18 17:46:45 +0530480 ALOGV("%s() completed for device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700481 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700482 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700483
François Gaffie11d30102018-11-02 16:09:09 +0100484 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700485 return BAD_VALUE;
486}
487
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100488status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
489 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800490 media::AudioPortFw* aidlPort) {
Andy Hunged722372023-09-18 22:00:21 +0000491 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
492 devDescr->setName(device_name);
493 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100494}
495
Eric Laurent736a1022019-03-27 18:28:46 -0700496void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
497 audio_policy_dev_state_t state) {
498
499 // the Engine does not have to know about remote submix devices used by dynamic audio policies
500 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
501 return;
502 }
503 mEngine->setDeviceConnectionState(device, state);
504}
505
506
Eric Laurente0720872014-03-11 09:30:41 -0700507audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100508 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700509{
Eric Laurent634b7142016-04-20 13:48:02 -0700510 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800511 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
512 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700513 (strlen(device_address) != 0)/*matchAddress*/);
514
515 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100516 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700517 device, device_address);
518 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
519 }
François Gaffie53615e22015-03-19 09:24:12 +0100520
Eric Laurent3a4311c2014-03-17 12:00:47 -0700521 DeviceVector *deviceVector;
522
Eric Laurente552edb2014-03-10 17:42:56 -0700523 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700524 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700525 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700526 deviceVector = &mAvailableInputDevices;
527 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100528 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700529 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700530 }
Eric Laurent634b7142016-04-20 13:48:02 -0700531
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800532 return (deviceVector->getDevice(
533 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700534 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800535}
536
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800537status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
538 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800539 const char *device_name,
540 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800541{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800542 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
543 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800544
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800545 // connect/disconnect only 1 device at a time
546 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
547
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800548 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700549 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800550 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800551 // Nothing to do: device is not connected
552 return NO_ERROR;
553 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800554 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800555
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700556 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800557 // configure codecs.
558 // Handle two specific cases by sending a set parameter to
559 // configure A2DP codecs. No need to toggle device state.
560 // Case 1: A2DP active device switches from primary to primary
561 // module
562 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100563 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700564 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800565 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
566 if (availablePrimaryOutputDevices().contains(devDesc) &&
567 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100568 bool isA2dp = audio_is_a2dp_out_device(device);
569 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
570 : String8(AudioParameter::keyReconfigLeSupported);
571 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800572 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100573 int isReconfigSupported;
574 repliedParameters.getInt(supportKey, isReconfigSupported);
575 if (isReconfigSupported) {
576 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
577 : String8(AudioParameter::keyReconfigLe);
578 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800579 param.add(key, String8("true"));
580 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
581 devDesc->setEncodedFormat(encodedFormat);
582 return NO_ERROR;
583 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700584 }
585 }
cnx421bd2dcc42020-07-11 14:58:44 +0800586 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000587 uint32_t muteWaitMs = 0;
cnx421bd2dcc42020-07-11 14:58:44 +0800588 for (size_t i = 0; i < mOutputs.size(); i++) {
589 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000590 // mute media strategies to avoid sending the music tail into
591 // the earpiece or headset.
592 if (desc->isStrategyActive(musicStrategy)) {
593 uint32_t tempRecommendedMuteDuration = desc->getRecommendedMuteDurationMs();
594 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
595 tempRecommendedMuteDuration : desc->latency() * 4;
596 if (muteWaitMs < tempMuteDurationMs) {
597 muteWaitMs = tempMuteDurationMs;
598 }
599 }
cnx421bd2dcc42020-07-11 14:58:44 +0800600 setStrategyMute(musicStrategy, true, desc);
601 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
602 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
603 nullptr, true /*fromCache*/).types());
604 }
Eric Laurentcd0f24f2024-05-16 13:11:39 +0000605 // Wait for the muted audio to propagate down the audio path see checkDeviceMuteStrategies().
606 // We assume that MUTE_TIME_MS is way larger than muteWaitMs so that unmuting still
607 // happens after the actual device switch.
608 if (muteWaitMs > 0) {
609 ALOGW_IF(MUTE_TIME_MS < muteWaitMs * 2, "%s excessive mute wait %d", __func__, muteWaitMs);
610 usleep(muteWaitMs * 1000);
611 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800612 // Toggle the device state: UNAVAILABLE -> AVAILABLE
613 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100614 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800615 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800616 device_address, device_name,
617 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800618 if (status != NO_ERROR) {
619 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
620 status);
621 return status;
622 }
623
624 status = setDeviceConnectionState(device,
625 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800626 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800627 if (status != NO_ERROR) {
628 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
629 status);
630 return status;
631 }
632
633 return NO_ERROR;
634}
635
Pattydd807582021-11-04 21:01:03 +0800636status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
637 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800638{
Pattydd807582021-11-04 21:01:03 +0800639 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800640 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800641 std::unordered_set<audio_format_t> formatSet;
642 sp<HwModule> primaryModule =
643 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700644 if (primaryModule == nullptr) {
645 ALOGE("%s() unable to get primary module", __func__);
646 return NO_INIT;
647 }
Pattydd807582021-11-04 21:01:03 +0800648
649 DeviceTypeSet audioDeviceSet;
650
651 switch(device) {
652 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
653 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
654 break;
655 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800656 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
657 break;
658 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
659 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800660 break;
661 default:
662 ALOGE("%s() device type 0x%08x not supported", __func__, device);
663 return BAD_VALUE;
664 }
665
jiabin9a3361e2019-10-01 09:38:30 -0700666 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800667 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800668 for (const auto& device : declaredDevices) {
669 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800670 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800671 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800672 return status;
673}
674
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100675DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
676{
677 DeviceVector rxSinkdevices{};
678 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
679 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
680 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
681 auto rxSinkDevice = rxSinkdevices.itemAt(0);
682 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
683 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
684 // retrieve Rx Source device descriptor
685 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
686 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
687
688 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
689 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
690 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
691 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
692 return DeviceVector(rxSinkDevice);
693 }
694 }
695 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
696 // the device returned is not necessarily reachable via this output
697 // (filter later by setOutputDevices())
698 return getNewOutputDevices(mPrimaryOutput, fromCache);
699}
700
701status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
702{
François Gaffiedb1755b2023-09-01 11:50:35 +0200703 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100704 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
705 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
706 }
707 return INVALID_OPERATION;
708}
709
710status_t AudioPolicyManager::updateCallRoutingInternal(
711 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700712{
713 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100714 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700715 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200716 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700717 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100718 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700719 }
François Gaffie11d30102018-11-02 16:09:09 +0100720
Francois Gaffie716e1432019-01-14 16:58:59 +0100721 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100722 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200723
724 disconnectTelephonyAudioSource(mCallRxSourceClient);
725 disconnectTelephonyAudioSource(mCallTxSourceClient);
726
727 if (rxDevices.isEmpty()) {
728 ALOGW("%s() no selected output device", __func__);
729 return INVALID_OPERATION;
730 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000731 if (txSourceDevice == nullptr) {
732 ALOGE("%s() selected input device not available", __func__);
733 return INVALID_OPERATION;
734 }
François Gaffiec005e562018-11-06 15:04:49 +0100735
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100736 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100737 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700738
François Gaffie9eb18552018-11-05 10:33:26 +0100739 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700740 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100741 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700742 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100743 // retrieve Rx Source and Tx Sink device descriptors
744 sp<DeviceDescriptor> rxSourceDevice =
745 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
746 String8(),
747 AUDIO_FORMAT_DEFAULT);
748 sp<DeviceDescriptor> txSinkDevice =
749 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
750 String8(),
751 AUDIO_FORMAT_DEFAULT);
752
753 // RX and TX Telephony device are declared by Primary Audio HAL
754 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
755 (telephonyRxModule->getHalVersionMajor() >= 3)) {
756 if (rxSourceDevice == 0 || txSinkDevice == 0) {
757 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100758 ALOGE("%s() no telephony Tx and/or RX device", __func__);
759 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100760 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100761 // createAudioPatchInternal now supports both HW / SW bridging
762 createRxPatch = true;
763 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100764 } else {
765 // If the RX device is on the primary HW module, then use legacy routing method for
766 // voice calls via setOutputDevice() on primary output.
767 // Otherwise, create two audio patches for TX and RX path.
768 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
769 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700770 // If the TX device is also on the primary HW module, setOutputDevice() will take care
771 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100772 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
773 (txSinkDevice != 0);
774 }
775 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
776 // Otherwise, create two audio patches for TX and RX path.
777 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200778 if (!hasPrimaryOutput()) {
779 ALOGW("%s() no primary output available", __func__);
780 return INVALID_OPERATION;
781 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530782 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700783 } else { // create RX path audio patch
David Li48b6a832024-07-01 13:14:10 +0000784 connectTelephonyRxAudioSource(delayMs);
juyuchen2224c5a2019-01-21 12:00:58 +0800785 // If the TX device is on the primary HW module but RX device is
786 // on other HW module, SinkMetaData of telephony input should handle it
787 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700788 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700789 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100790 // terminate active capture if on the same HW module as the call TX source device
791 // FIXME: would be better to refine to only inputs whose profile connects to the
792 // call TX device but this information is not in the audio patch and logic here must be
793 // symmetric to the one in startInput()
794 for (const auto& activeDesc : mInputs.getActiveInputs()) {
795 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
796 closeActiveClients(activeDesc);
797 }
798 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200799 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800800 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100801 if (waitMs != nullptr) {
802 *waitMs = muteWaitMs;
803 }
804 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800805}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700806
Mikhail Naganov100f0122018-11-29 11:22:16 -0800807bool AudioPolicyManager::isDeviceOfModule(
808 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
809 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
810 if (module != 0) {
811 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
812 .indexOf(devDesc) != NAME_NOT_FOUND
813 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
814 .indexOf(devDesc) != NAME_NOT_FOUND;
815 }
816 return false;
817}
818
David Li48b6a832024-07-01 13:14:10 +0000819void AudioPolicyManager::connectTelephonyRxAudioSource(uint32_t delayMs)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200820{
Francois Gaffie601801d2021-06-22 13:27:39 +0200821 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200822 const struct audio_port_config source = {
823 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
824 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
825 };
826 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100827
828 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
Eric Laurent963dbcc2024-06-20 12:34:15 +0000829 status_t status = startAudioSourceInternal(&source, &aa, &portId, 0 /*uid*/,
David Li48b6a832024-07-01 13:14:10 +0000830 true /*internal*/, true /*isCallRx*/, delayMs);
Eric Laurent541a2002024-01-15 18:11:42 +0100831 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
832 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200833 ALOGE_IF(mCallRxSourceClient == nullptr,
834 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200835}
836
Francois Gaffie601801d2021-06-22 13:27:39 +0200837void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200838{
Francois Gaffie601801d2021-06-22 13:27:39 +0200839 if (clientDesc == nullptr) {
840 return;
841 }
842 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
843 "%s error stopping audio source", __func__);
844 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200845}
846
847void AudioPolicyManager::connectTelephonyTxAudioSource(
848 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
849 uint32_t delayMs)
850{
Francois Gaffie601801d2021-06-22 13:27:39 +0200851 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200852 if (srcDevice == nullptr || sinkDevice == nullptr) {
853 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
854 return;
855 }
856 PatchBuilder patchBuilder;
857 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
858 ALOGV("%s between source %s and sink %s", __func__,
859 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200860 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200861 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
862
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200863 struct audio_port_config source = {};
864 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100865 mCallTxSourceClient = new SourceClientDescriptor(
866 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
Eric Laurent963dbcc2024-06-20 12:34:15 +0000867 mCommunnicationStrategy, toVolumeSource(aa), true,
868 false /*isCallRx*/, true /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +0100869 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
870
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200871 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
872 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200873 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
874 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200875 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
876 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200877 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200878 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200879}
880
Eric Laurente0720872014-03-11 09:30:41 -0700881void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700882{
883 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100884 // store previous phone state for management of sonification strategy below
885 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100886 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100887
888 if (mEngine->setPhoneState(state) != NO_ERROR) {
889 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700890 return;
891 }
François Gaffie2110e042015-03-24 08:41:51 +0100892 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700893 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700894 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700895 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800896 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700897 }
898
François Gaffie2110e042015-03-24 08:41:51 +0100899 /**
900 * Switching to or from incall state or switching between telephony and VoIP lead to force
901 * routing command.
902 */
Eric Laurent74b71512019-11-06 17:21:57 -0800903 bool force = ((isStateInCall(oldState) != isStateInCall(state))
904 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700905
906 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700907 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700908
Eric Laurente552edb2014-03-10 17:42:56 -0700909 int delayMs = 0;
910 if (isStateInCall(state)) {
911 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100912 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
913 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700914 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700915 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700916 // mute media and sonification strategies and delay device switch by the largest
917 // latency of any output where either strategy is active.
918 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100919 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
920 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
921 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700922 (delayMs < (int)desc->latency()*2)) {
923 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700924 }
François Gaffiec005e562018-11-06 15:04:49 +0100925 setStrategyMute(musicStrategy, true, desc);
926 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
927 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
928 nullptr, true /*fromCache*/).types());
929 setStrategyMute(sonificationStrategy, true, desc);
930 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
931 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
932 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700933 }
934 }
935
François Gaffiedb1755b2023-09-01 11:50:35 +0200936 if (state == AUDIO_MODE_IN_CALL) {
937 (void)updateCallRouting(false /*fromCache*/, delayMs);
938 } else {
939 if (oldState == AUDIO_MODE_IN_CALL) {
940 disconnectTelephonyAudioSource(mCallRxSourceClient);
941 disconnectTelephonyAudioSource(mCallTxSourceClient);
942 }
943 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100944 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
945 // force routing command to audio hardware when ending call
946 // even if no device change is needed
947 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
948 rxDevices = mPrimaryOutput->devices();
949 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530950 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700951 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700952 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700953
jiabin3ff8d7d2022-12-13 06:27:44 +0000954 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700955 // reevaluate routing on all outputs in case tracks have been started during the call
956 for (size_t i = 0; i < mOutputs.size(); i++) {
957 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100958 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +0000959 if (state != AUDIO_MODE_NORMAL && oldState == AUDIO_MODE_NORMAL
960 && desc->mPreferredAttrInfo != nullptr) {
961 // If the output is using preferred mixer attributes and the audio mode is not normal,
962 // the output need to reopen with default configuration.
963 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
964 continue;
965 }
Francois Gaffie601801d2021-06-22 13:27:39 +0200966 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
967 bool forceRouting = !newDevices.isEmpty();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530968 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200969 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700970 }
971 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000972 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700973
Eric Laurent96d1dda2022-03-14 17:14:19 +0100974 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
975
Eric Laurente552edb2014-03-10 17:42:56 -0700976 if (isStateInCall(state)) {
977 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700978 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800979 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700980 }
981
982 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100983 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
984 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700985}
986
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700987audio_mode_t AudioPolicyManager::getPhoneState() {
988 return mEngine->getPhoneState();
989}
990
Eric Laurente0720872014-03-11 09:30:41 -0700991void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100992 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700993{
François Gaffie2110e042015-03-24 08:41:51 +0100994 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700995 if (config == mEngine->getForceUse(usage)) {
996 return;
997 }
Eric Laurente552edb2014-03-10 17:42:56 -0700998
François Gaffie2110e042015-03-24 08:41:51 +0100999 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
1000 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
1001 return;
Eric Laurente552edb2014-03-10 17:42:56 -07001002 }
François Gaffie2110e042015-03-24 08:41:51 +01001003 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
1004 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
1005 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -07001006
1007 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -07001008 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -08001009
Eric Laurent22fcda22019-05-17 16:28:47 -07001010 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
1011 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -08001012 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -07001013 }
1014
Eric Laurentdc462862016-07-19 12:29:53 -07001015 //FIXME: workaround for truncated touch sounds
1016 // to be removed when the problem is handled by system UI
1017 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001018 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1019 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1020 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001021
1022 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001023 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001024}
1025
Eric Laurente0720872014-03-11 09:30:41 -07001026void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001027{
1028 ALOGV("setSystemProperty() property %s, value %s", property, value);
1029}
1030
Dorin Drimusecc9f422022-03-09 17:57:40 +01001031// Find an MSD output profile compatible with the parameters passed.
1032// When "directOnly" is set, restrict search to profiles for direct outputs.
1033sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1034 const DeviceVector& devices,
1035 uint32_t samplingRate,
1036 audio_format_t format,
1037 audio_channel_mask_t channelMask,
1038 audio_output_flags_t flags,
1039 bool directOnly)
1040{
1041 flags = getRelevantFlags(flags, directOnly);
1042
1043 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1044 if (msdModule != nullptr) {
1045 // for the msd module check if there are patches to the output devices
1046 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1047 HwModuleCollection modules;
1048 modules.add(msdModule);
1049 return searchCompatibleProfileHwModules(
1050 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1051 flags, directOnly);
1052 }
1053 }
1054 return nullptr;
1055}
1056
Michael Chana94fbb22018-04-24 14:31:19 +10001057// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1058// search to profiles for direct outputs.
1059sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001060 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001061 uint32_t samplingRate,
1062 audio_format_t format,
1063 audio_channel_mask_t channelMask,
1064 audio_output_flags_t flags,
1065 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001066{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001067 flags = getRelevantFlags(flags, directOnly);
1068
1069 return searchCompatibleProfileHwModules(
1070 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1071}
1072
1073audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1074 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001075 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001076 // only retain flags that will drive the direct output profile selection
1077 // if explicitly requested
1078 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001079 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001080 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1081 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001082 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001083 return flags;
1084}
Eric Laurent861a6282015-05-18 15:40:16 -07001085
Dorin Drimusecc9f422022-03-09 17:57:40 +01001086sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1087 const HwModuleCollection& hwModules,
1088 const DeviceVector& devices,
1089 uint32_t samplingRate,
1090 audio_format_t format,
1091 audio_channel_mask_t channelMask,
1092 audio_output_flags_t flags,
1093 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001094 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001095 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001096 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001097 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001098 samplingRate, NULL /*updatedSamplingRate*/,
1099 format, NULL /*updatedFormat*/,
1100 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001101 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001102 continue;
1103 }
1104 // reject profiles not corresponding to a device currently available
1105 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1106 continue;
1107 }
1108 // reject profiles if connected device does not support codec
1109 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1110 continue;
1111 }
1112 if (!directOnly) {
1113 return curProfile;
1114 }
1115
1116 // when searching for direct outputs, if several profiles are compatible, give priority
1117 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001118 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001119 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001120 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001121 }
1122 profile = curProfile;
1123 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1124 break;
1125 }
Eric Laurente552edb2014-03-10 17:42:56 -07001126 }
1127 }
Eric Laurent861a6282015-05-18 15:40:16 -07001128 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001129}
1130
Eric Laurentfa0f6742021-08-17 18:39:44 +02001131sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001132 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001133{
1134 for (const auto& hwModule : mHwModules) {
1135 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001136 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001137 continue;
1138 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001139 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001140 // reject profiles not corresponding to a device currently available
1141 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1142 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1143 continue;
1144 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001145 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1146 != devices.size()) {
1147 continue;
1148 }
1149 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001150 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1151 return curProfile;
1152 }
1153 }
1154 return nullptr;
1155}
1156
Eric Laurentf4e63452017-11-06 19:31:46 +00001157audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001158{
François Gaffiec005e562018-11-06 15:04:49 +01001159 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001160
1161 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1162 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1163 // format, flags, etc. This may result in some discrepancy for functions that utilize
1164 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1165 // and AudioSystem::getOutputSamplingRate().
1166
François Gaffie11d30102018-11-02 16:09:09 +01001167 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001168 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Mikhail Naganov285c1732024-09-05 17:26:50 -07001169 if (stream == AUDIO_STREAM_MUSIC && mConfig->useDeepBufferForMedia()) {
Mingyu Shih75563d32023-05-24 04:47:40 +08001170 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1171 }
1172 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001173
François Gaffie11d30102018-11-02 16:09:09 +01001174 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1175 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001176 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001177}
1178
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001179status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1180 const audio_attributes_t *srcAttr,
1181 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001182{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001183 if (srcAttr != NULL) {
1184 if (!isValidAttributes(srcAttr)) {
1185 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1186 __func__,
1187 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1188 srcAttr->tags);
1189 return BAD_VALUE;
1190 }
1191 *dstAttr = *srcAttr;
1192 } else {
1193 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1194 ALOGE("%s: invalid stream type", __func__);
1195 return BAD_VALUE;
1196 }
François Gaffiec005e562018-11-06 15:04:49 +01001197 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001198 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001199
1200 // Only honor audibility enforced when required. The client will be
1201 // forced to reconnect if the forced usage changes.
1202 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001203 dstAttr->flags = static_cast<audio_flags_mask_t>(
1204 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001205 }
1206
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001207 return NO_ERROR;
1208}
1209
Kevin Rocard153f92d2018-12-18 18:33:28 -08001210status_t AudioPolicyManager::getOutputForAttrInt(
1211 audio_attributes_t *resultAttr,
1212 audio_io_handle_t *output,
1213 audio_session_t session,
1214 const audio_attributes_t *attr,
1215 audio_stream_type_t *stream,
1216 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001217 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001218 audio_output_flags_t *flags,
1219 audio_port_handle_t *selectedDeviceId,
1220 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001221 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001222 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001223 bool *isSpatialized,
1224 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001225{
François Gaffiec005e562018-11-06 15:04:49 +01001226 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001227 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001228 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001229 const sp<DeviceDescriptor> requestedDevice =
1230 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1231
Eric Laurent8a1095a2019-11-08 14:44:16 -08001232 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001233 *isSpatialized = false;
1234
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001235 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1236 if (status != NO_ERROR) {
1237 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001238 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001239 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001240 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001241 }
François Gaffiec005e562018-11-06 15:04:49 +01001242 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001243
François Gaffiec005e562018-11-06 15:04:49 +01001244 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1245 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001246
Oscar Azucena873d10f2023-01-12 18:34:42 -08001247 bool usePrimaryOutputFromPolicyMixes = false;
1248
Kevin Rocard153f92d2018-12-18 18:33:28 -08001249 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1250 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1251 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001252 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001253 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1254 .channel_mask = config->channel_mask,
1255 .format = config->format,
1256 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001257 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001258 mAvailableOutputDevices, requestedDevice, primaryMix,
1259 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001260 if (status != OK) {
1261 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001262 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001263
Kevin Rocard153f92d2018-12-18 18:33:28 -08001264 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001265 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
Andy Hungced57302024-08-14 11:37:57 -07001266 && (!audio_is_linear_pcm(config->format) ||
1267 *flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)) {
Dean Wheatleyd082f472022-02-04 11:10:48 +11001268 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001269 return BAD_VALUE;
1270 }
1271 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001272 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001273 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1274 primaryMix->mDeviceAddress,
1275 AUDIO_FORMAT_DEFAULT);
1276 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001277 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001278 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1279 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001280 // if a direct output can be opened to deliver the track's multi-channel content to the
1281 // output rather than being downmixed by the primary output, then use this direct
1282 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1283 // mix.
1284 bool tryDirectForChannelMask = policyDesc != nullptr
1285 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1286 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001287 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001288 audio_io_handle_t newOutput;
1289 status = openDirectOutput(
1290 *stream, session, config,
1291 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001292 DeviceVector(policyMixDevice), &newOutput, *resultAttr);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001293 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001294 policyDesc = mOutputs.valueFor(newOutput);
1295 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001296 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001297 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001298 policyDesc = nullptr;
1299 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001300 }
1301 if (policyDesc != nullptr) {
1302 policyDesc->mPolicyMix = primaryMix;
1303 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001304 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1305 : AUDIO_PORT_HANDLE_NONE;
1306 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1307 // Remove direct flag as it is not on a direct output.
1308 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1309 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001310
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001311 ALOGV("getOutputForAttr() returns output %d", *output);
1312 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1313 *outputType = API_OUT_MIX_PLAYBACK;
1314 } else {
1315 *outputType = API_OUTPUT_LEGACY;
1316 }
1317 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001318 } else {
1319 if (policyMixDevice != nullptr) {
1320 ALOGE("%s, try to use primary mix but no output found", __func__);
1321 return INVALID_OPERATION;
1322 }
1323 // Fallback to default engine selection as the selected primary mix device is not
1324 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001325 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001326 }
François Gaffiec005e562018-11-06 15:04:49 +01001327 // Virtual sources must always be dynamicaly or explicitly routed
1328 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1329 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1330 return BAD_VALUE;
1331 }
1332 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1333 // in order to let the choice of the order to future vendor engine
1334 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001335
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001336 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001337 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001338 }
1339
Nadav Barb2f18162018-07-18 13:01:53 +03001340 // Set incall music only if device was explicitly set, and fallback to the device which is
1341 // chosen by the engine if not.
1342 // FIXME: provide a more generic approach which is not device specific and move this back
1343 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001344 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001345 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001346 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001347 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001348 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001349 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001350 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001351 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001352 }
1353 }
1354
François Gaffiec005e562018-11-06 15:04:49 +01001355 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1356 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1357 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001358
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001359 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001360 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001361 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001362 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001363 ALOGV("%s() Using MSD devices %s instead of devices %s",
1364 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001365 } else {
1366 *output = AUDIO_IO_HANDLE_NONE;
1367 }
1368 }
1369 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001370 sp<PreferredMixerAttributesInfo> info = nullptr;
1371 if (outputDevices.size() == 1) {
1372 info = getPreferredMixerAttributesInfo(
1373 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001374 mEngine->getProductStrategyForAttributes(*resultAttr),
1375 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001376 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1377 // and it is currently active.
1378 if (info != nullptr && info->getUid() != uid &&
jiabin220eea12024-05-17 17:55:20 +00001379 (!info->isBitPerfect() || info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001380 info = nullptr;
1381 }
jiabin220eea12024-05-17 17:55:20 +00001382 if (com::android::media::audioserver::
1383 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1384 if (info != nullptr && info->getUid() == uid &&
1385 info->configMatches(*config) &&
1386 (mEngine->getPhoneState() != AUDIO_MODE_NORMAL ||
1387 std::any_of(gHighPriorityUseCases.begin(), gHighPriorityUseCases.end(),
1388 [this, &outputDevices](audio_usage_t usage) {
1389 return mOutputs.isUsageActiveOnDevice(
1390 usage, outputDevices[0]); }))) {
1391 // Bit-perfect request is not allowed when the phone mode is not normal or
1392 // there is any higher priority user case active.
1393 return INVALID_OPERATION;
1394 }
1395 }
jiabina84c3d32022-12-02 18:59:55 +00001396 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001397 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001398 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001399 // The client will be active if the client is currently preferred mixer owner and the
1400 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001401 *isBitPerfect = (info != nullptr
jiabin220eea12024-05-17 17:55:20 +00001402 && info->isBitPerfect()
jiabin5eaf0962022-12-20 20:11:38 +00001403 && info->getUid() == uid
1404 && *output != AUDIO_IO_HANDLE_NONE
1405 // When bit-perfect output is selected for the preferred mixer attributes owner,
1406 // only need to consider the config matches.
1407 && mOutputs.valueFor(*output)->isConfigurationMatched(
1408 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
jiabin220eea12024-05-17 17:55:20 +00001409
1410 if (*isBitPerfect) {
1411 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_BIT_PERFECT);
1412 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001413 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001414 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001415 AudioProfileVector profiles;
1416 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1417 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001418 const auto channels = profiles[0]->getChannels();
1419 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1420 config->channel_mask = *channels.begin();
1421 }
1422 const auto sampleRates = profiles[0]->getSampleRates();
1423 if (!sampleRates.empty() &&
1424 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1425 config->sample_rate = *sampleRates.begin();
1426 }
jiabinf1c73972022-04-14 16:28:52 -07001427 config->format = profiles[0]->getFormat();
1428 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001429 return INVALID_OPERATION;
1430 }
Paul McLeanaa981192015-03-21 09:55:15 -07001431
François Gaffiec005e562018-11-06 15:04:49 +01001432 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001433 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001434 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001435 *selectedDeviceId = outputDevice->getId();
1436 break;
1437 }
1438 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001439
Eric Laurent8a1095a2019-11-08 14:44:16 -08001440 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1441 *outputType = API_OUTPUT_TELEPHONY_TX;
1442 } else {
1443 *outputType = API_OUTPUT_LEGACY;
1444 }
1445
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001446 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1447
1448 return NO_ERROR;
1449}
1450
1451status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1452 audio_io_handle_t *output,
1453 audio_session_t session,
1454 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001455 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001456 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001457 audio_output_flags_t *flags,
1458 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001459 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001460 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001461 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001462 bool *isSpatialized,
1463 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001464{
1465 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1466 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1467 return INVALID_OPERATION;
1468 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001469 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001470 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001471 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001472 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001473 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001474 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001475 const sp<DeviceDescriptor> requestedDevice =
1476 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1477
1478 // Prevent from storing invalid requested device id in clients
1479 const audio_port_handle_t sanitizedRequestedPortId =
1480 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1481 *selectedDeviceId = sanitizedRequestedPortId;
1482
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001483 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001484 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001485 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1486 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001487 if (status != NO_ERROR) {
1488 return status;
1489 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001490 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001491 if (secondaryOutputs != nullptr) {
1492 for (auto &secondaryMix : secondaryMixes) {
1493 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1494 if (outputDesc != nullptr &&
1495 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1496 secondaryOutputs->push_back(outputDesc->mIoHandle);
1497 weakSecondaryOutputDescs.push_back(outputDesc);
1498 }
1499 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001500 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001501
Eric Laurent8fc147b2018-07-22 19:13:55 -07001502 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001503 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001504 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001505 };
jiabin4ef93452019-09-10 14:29:54 -07001506 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001507
Eric Laurentc209fe42020-06-05 18:11:23 -07001508 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001509 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001510 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001511 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001512 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001513 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001514 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001515 std::move(weakSecondaryOutputDescs),
1516 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001517 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001518
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001519 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1520 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001521
Eric Laurente83b55d2014-11-14 10:06:21 -08001522 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001523}
1524
Eric Laurentc529cf62020-04-17 18:19:10 -07001525status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1526 audio_session_t session,
1527 const audio_config_t *config,
1528 audio_output_flags_t flags,
1529 const DeviceVector &devices,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001530 audio_io_handle_t *output,
1531 audio_attributes_t attributes) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001532
1533 *output = AUDIO_IO_HANDLE_NONE;
1534
1535 // skip direct output selection if the request can obviously be attached to a mixed output
1536 // and not explicitly requested
1537 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1538 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1539 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1540 return NAME_NOT_FOUND;
1541 }
1542
Mikhail Naganov285c1732024-09-05 17:26:50 -07001543 // Reject flag combinations that do not make sense. Note that the requested flags might not
1544 // have the 'DIRECT' flag set, however once a direct-capable profile is found, it will
1545 // combine the requested flags with its own flags, yielding an unsupported combination.
1546 if ((flags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
1547 return NAME_NOT_FOUND;
1548 }
1549
Eric Laurentc529cf62020-04-17 18:19:10 -07001550 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1551 // This prevents creating an offloaded track and tearing it down immediately after start
1552 // when audioflinger detects there is an active non offloadable effect.
1553 // FIXME: We should check the audio session here but we do not have it in this context.
1554 // This may prevent offloading in rare situations where effects are left active by apps
1555 // in the background.
1556 sp<IOProfile> profile;
1557 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1558 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1559 profile = getProfileForOutput(
1560 devices, config->sample_rate, config->format, config->channel_mask,
1561 flags, true /* directOnly */);
1562 }
1563
1564 if (profile == nullptr) {
1565 return NAME_NOT_FOUND;
1566 }
1567
1568 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1569 for (size_t i = 0; i < mOutputs.size(); i++) {
1570 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1571 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1572 // reuse direct output if currently open by the same client
1573 // and configured with same parameters
1574 if ((config->sample_rate == desc->getSamplingRate()) &&
1575 (config->format == desc->getFormat()) &&
1576 (config->channel_mask == desc->getChannelMask()) &&
1577 (session == desc->mDirectClientSession)) {
1578 desc->mDirectOpenCount++;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301579 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001580 mOutputs.keyAt(i), session);
1581 *output = mOutputs.keyAt(i);
1582 return NO_ERROR;
1583 }
1584 }
1585 }
1586
1587 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001588 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301589 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1590 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001591 return NAME_NOT_FOUND;
1592 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1593 // MMAP gracefully handles lack of an exclusive track resource by mixing
1594 // above the audio framework. For AAudio to know that the limit is reached,
1595 // return an error.
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301596 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1597 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001598 return NAME_NOT_FOUND;
1599 } else {
1600 // Close outputs on this profile, if available, to free resources for this request
1601 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1602 const auto desc = mOutputs.valueAt(i);
1603 if (desc->mProfile == profile) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301604 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1605 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001606 closeOutput(desc->mIoHandle);
1607 }
1608 }
1609 }
1610 }
1611
1612 // Unable to close streams to find free resources for this request
1613 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301614 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1615 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001616 return NAME_NOT_FOUND;
1617 }
1618
Atneya Nairb16666a2023-12-11 20:18:33 -08001619 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001620
Michael Chan6fb34492020-12-08 15:44:49 +11001621 // An MSD patch may be using the only output stream that can service this request. Release
1622 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001623 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001624
Eric Laurentf1f22e72021-07-13 14:04:14 +02001625 status_t status =
Dean Wheatleydfb67b82024-01-23 09:36:29 +11001626 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, &flags, output,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001627 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001628
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001629 // only accept an output with the requested parameters, unless the format can be IEC61937
1630 // encapsulated and opened by AudioFlinger as wrapped IEC61937.
1631 const bool ignoreRequestedParametersCheck = audio_is_iec61937_compatible(config->format)
1632 && (flags & AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO)
1633 && audio_has_proportional_frames(outputDesc->getFormat());
Eric Laurentc529cf62020-04-17 18:19:10 -07001634 if (status != NO_ERROR ||
Dean Wheatleyd27bbb92024-01-19 15:54:35 +11001635 (!ignoreRequestedParametersCheck &&
1636 ((config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1637 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1638 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())))) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001639 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1640 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1641 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1642 config->channel_mask, outputDesc->getChannelMask());
1643 if (*output != AUDIO_IO_HANDLE_NONE) {
1644 outputDesc->close();
1645 }
1646 // fall back to mixer output if possible when the direct output could not be open
1647 if (audio_is_linear_pcm(config->format) &&
1648 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1649 return NAME_NOT_FOUND;
1650 }
1651 *output = AUDIO_IO_HANDLE_NONE;
1652 return BAD_VALUE;
1653 }
1654 outputDesc->mDirectOpenCount = 1;
1655 outputDesc->mDirectClientSession = session;
1656
1657 addOutput(*output, outputDesc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07001658 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
1659 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
1660 hwModule->getHalVersionMajor() >= 3) {
1661 setOutputDevices(__func__, outputDesc, devices, true, 0, NULL);
1662 }
Eric Laurentc529cf62020-04-17 18:19:10 -07001663 mPreviousOutputs = mOutputs;
1664 ALOGV("%s returns new direct output %d", __func__, *output);
1665 mpClientInterface->onAudioPortListUpdate();
1666 return NO_ERROR;
1667}
1668
François Gaffie11d30102018-11-02 16:09:09 +01001669audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1670 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001671 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001672 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001673 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001674 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001675 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001676 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001677 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001678{
Andy Hungc88b0642018-04-27 15:42:35 -07001679 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001680
jiabine375d412019-02-26 12:54:53 -08001681 // Discard haptic channel mask when forcing muting haptic channels.
1682 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001683 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1684 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001685
Eric Laurente552edb2014-03-10 17:42:56 -07001686 // open a direct output if required by specified parameters
1687 //force direct flag if offload flag is set: offloading implies a direct output stream
1688 // and all common behaviors are driven by checking only the direct flag
1689 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001690 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1691 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001692 }
Nadav Bar766fb022018-01-07 12:18:03 +02001693 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1694 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001695 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001696
1697 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1698
Eric Laurente83b55d2014-11-14 10:06:21 -08001699 // only allow deep buffering for music stream type
1700 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001701 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001702 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov285c1732024-09-05 17:26:50 -07001703 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001704 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001705 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001706 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001707 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001708 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001709 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001710 audio_is_linear_pcm(config->format) &&
1711 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001712 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001713 AUDIO_OUTPUT_FLAG_DIRECT);
1714 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001715 }
Eric Laurente552edb2014-03-10 17:42:56 -07001716
Carter Hsua3abb402021-10-26 11:11:20 +08001717 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1718 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1719 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1720 }
1721
Eric Laurentf9230d52024-01-26 18:49:09 +01001722 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao57b93392024-04-26 04:12:21 +00001723 // was specified and offload or direct playback is not explicitly requested, and there is no
1724 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001725 *isSpatialized = false;
Shunkai Yao57b93392024-04-26 04:12:21 +00001726 if (mSpatializerOutput != nullptr &&
1727 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1728 prefMixerConfigInfo == nullptr &&
1729 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1730 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001731 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001732 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001733 }
1734
Eric Laurentc529cf62020-04-17 18:19:10 -07001735 audio_config_t directConfig = *config;
1736 directConfig.channel_mask = channelMask;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001737
1738 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1739 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001740 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001741 return output;
1742 }
1743
Eric Laurent14cbfca2016-03-17 09:42:16 -07001744 // A request for HW A/V sync cannot fallback to a mixed output because time
1745 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001746 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001747 return AUDIO_IO_HANDLE_NONE;
1748 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001749 // A request for Tuner cannot fallback to a mixed output
1750 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1751 return AUDIO_IO_HANDLE_NONE;
1752 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001753
Eric Laurente552edb2014-03-10 17:42:56 -07001754 // ignoring channel mask due to downmix capability in mixer
1755
1756 // open a non direct output
1757
1758 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001759 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001760 // get which output is suitable for the specified stream. The actual
1761 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001762 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001763 if (prefMixerConfigInfo != nullptr) {
1764 for (audio_io_handle_t outputHandle : outputs) {
1765 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1766 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1767 output = outputHandle;
1768 break;
1769 }
1770 }
1771 if (output == AUDIO_IO_HANDLE_NONE) {
1772 // No output open with the preferred profile. Open a new one.
1773 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1774 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1775 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1776 config.format = prefMixerConfigInfo->getConfigBase().format;
1777 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1778 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1779 &config, prefMixerConfigInfo->getFlags());
1780 if (preferredOutput == nullptr) {
1781 ALOGE("%s failed to open output with preferred mixer config", __func__);
1782 } else {
1783 output = preferredOutput->mIoHandle;
1784 }
1785 }
1786 } else {
1787 // at this stage we should ignore the DIRECT flag as no direct output could be
1788 // found earlier
1789 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001790 if (com::android::media::audioserver::
1791 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1792 // If the preferred mixer attributes is null, do not select the bit-perfect output
1793 // unless the bit-perfect output is the only output.
1794 // The bit-perfect output can exist while the passed in preferred mixer attributes
1795 // info is null when it is a high priority client. The high priority clients are
1796 // ringtone or alarm, which is not a bit-perfect use case.
1797 size_t i = 0;
1798 while (i < outputs.size() && outputs.size() > 1) {
1799 auto desc = mOutputs.valueFor(outputs[i]);
1800 // The output descriptor must not be null here.
1801 if (desc->isBitPerfect()) {
1802 outputs.removeItemsAt(i);
1803 } else {
1804 i += 1;
1805 }
1806 }
1807 }
jiabina84c3d32022-12-02 18:59:55 +00001808 output = selectOutput(
1809 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1810 }
Eric Laurente552edb2014-03-10 17:42:56 -07001811 }
François Gaffie11d30102018-11-02 16:09:09 +01001812 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001813 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001814 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001815
Eric Laurente552edb2014-03-10 17:42:56 -07001816 return output;
1817}
1818
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001819sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001820 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1821 mAvailableInputDevices);
1822 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1823}
1824
1825DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1826 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1827 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001828}
1829
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001830const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001831 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001832 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1833 if (msdModule != 0) {
1834 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1835 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1836 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1837 const struct audio_port_config *source = &patch->mPatch.sources[j];
1838 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1839 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001840 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001841 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 }
1843 }
1844 }
1845 return msdPatches;
1846}
1847
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001848bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1849 ssize_t index = mAudioPatches.indexOfKey(handle);
1850 if (index < 0) {
1851 return false;
1852 }
1853 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1854 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1855 if (msdModule == nullptr) {
1856 return false;
1857 }
1858 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1859 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1860 return true;
1861 }
1862 index = getMsdOutputPatches().indexOfKey(handle);
1863 if (index < 0) {
1864 return false;
1865 }
1866 return true;
1867}
1868
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001869status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1870 const InputProfileCollection &inputProfiles,
1871 const OutputProfileCollection &outputProfiles,
1872 const sp<DeviceDescriptor> &sourceDevice,
1873 const sp<DeviceDescriptor> &sinkDevice,
1874 AudioProfileVector& sourceProfiles,
1875 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001876 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001877 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001878 return NO_INIT;
1879 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001880 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001881 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001882 return NO_INIT;
1883 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001885 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1886 inProfile->supportsDevice(sourceDevice)) {
1887 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001888 }
1889 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001890 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001891 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001892 outProfile->supportsDevice(sinkDevice)) {
1893 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001894 }
1895 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001896 return NO_ERROR;
1897}
1898
1899status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1900 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1901 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1902{
Dean Wheatley16809da2022-12-09 14:55:46 +11001903 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1904 static const std::vector<audio_format_t> formatsOrder = {{
1905 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001906 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1907 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001908 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1909 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1910 // preferred).
1911 std::vector<audio_channel_mask_t> masks = {{
1912 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1913 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1914 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1915 // insert index masks (higher counts most preferred) as preferred over position masks
1916 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1917 masks.insert(
1918 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1919 }
1920 return masks;
1921 }();
1922
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001923 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001924 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1925 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001926 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001927 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1928 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001929 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001930 }
1931 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1932 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1933 sinkConfig->format = bestSinkConfig.format;
1934 // For encoded streams force direct flag to prevent downstream mixing.
1935 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1936 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001937 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1938 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001939 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001940 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1941 // raw and IEC61937 framed streams.
1942 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1943 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1944 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001945 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1946 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001947 sourceConfig->channel_mask =
1948 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1949 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1950 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001951 sourceConfig->format = bestSinkConfig.format;
1952 // Copy input stream directly without any processing (e.g. resampling).
1953 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1954 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1955 if (hwAvSync) {
1956 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1957 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1958 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1959 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1960 }
1961 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1962 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1963 sinkConfig->config_mask |= config_mask;
1964 sourceConfig->config_mask |= config_mask;
1965 return NO_ERROR;
1966}
1967
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001968PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1969 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001970{
1971 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001972 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1973 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1974 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1975 if (deviceModule == nullptr) {
1976 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1977 return patchBuilder;
1978 }
1979 const InputProfileCollection inputProfiles = msdIsSource ?
1980 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1981 const OutputProfileCollection outputProfiles = msdIsSource ?
1982 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1983
1984 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1985 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1986 device : getMsdAudioOutDevices().itemAt(0);
1987 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1988
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001989 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1990 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001991 AudioProfileVector sourceProfiles;
1992 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001993 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1994 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001995 for (auto hwAvSync : { true, false }) {
1996 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1997 sourceProfiles, sinkProfiles) != NO_ERROR) {
1998 continue;
1999 }
2000 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
2001 &sinkConfig) == NO_ERROR) {
2002 // Found a matching config. Re-create PatchBuilder with this config.
2003 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
2004 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002005 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002006 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002007 " supporting PCM format conversion.", __func__);
2008 return patchBuilder;
2009}
2010
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002011status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002012 DeviceVector devices;
2013 if (outputDevices != nullptr && outputDevices->size() > 0) {
2014 devices.add(*outputDevices);
2015 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002016 // Use media strategy for unspecified output device. This should only
2017 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2018 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002019 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002020 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002021 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002022 }
Michael Chan6fb34492020-12-08 15:44:49 +11002023 std::vector<PatchBuilder> patchesToCreate;
2024 for (auto i = 0u; i < devices.size(); ++i) {
2025 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002026 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002027 }
2028 // Retain only the MSD patches associated with outputDevices request.
2029 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002030 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002031 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2032 auto retainedPatch = false;
2033 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2034 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2035 patchesToRemove.removeItemsAt(i);
2036 retainedPatch = true;
2037 break;
2038 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002039 }
Michael Chan6fb34492020-12-08 15:44:49 +11002040 if (retainedPatch) {
2041 it = patchesToCreate.erase(it);
2042 continue;
2043 }
2044 ++it;
2045 }
2046 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2047 return NO_ERROR;
2048 }
2049 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2050 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002051 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002052 }
Michael Chan6fb34492020-12-08 15:44:49 +11002053 status_t status = NO_ERROR;
2054 for (const auto &p : patchesToCreate) {
2055 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2056 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2057 char message[256];
2058 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2059 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2060 currStatus == NO_ERROR ? "Success" : "Error",
2061 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2062 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2063 if (currStatus == NO_ERROR) {
2064 ALOGD("%s", message);
2065 } else {
2066 ALOGE("%s", message);
2067 if (status == NO_ERROR) {
2068 status = currStatus;
2069 }
2070 }
2071 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002072 return status;
2073}
2074
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002075void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2076 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002077 for (size_t i = 0; i < msdPatches.size(); i++) {
2078 const auto& patch = msdPatches[i];
2079 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2080 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2081 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2082 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2083 releaseAudioPatch(patch->getHandle(), mUidCached);
2084 break;
2085 }
2086 }
2087 }
2088}
2089
Dorin Drimus94d94412022-02-02 09:05:02 +01002090bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002091 DeviceVector devicesToCheck =
2092 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002093 AudioPatchCollection msdPatches = getMsdOutputPatches();
2094 for (size_t i = 0; i < msdPatches.size(); i++) {
2095 const auto& patch = msdPatches[i];
2096 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2097 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2098 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2099 const auto& foundDevice = devicesToCheck.getDevice(
2100 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2101 if (foundDevice != nullptr) {
2102 devicesToCheck.remove(foundDevice);
2103 if (devicesToCheck.isEmpty()) {
2104 return true;
2105 }
2106 }
2107 }
2108 }
2109 }
2110 return false;
2111}
2112
Eric Laurente0720872014-03-11 09:30:41 -07002113audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002114 audio_output_flags_t flags,
2115 audio_format_t format,
2116 audio_channel_mask_t channelMask,
2117 uint32_t samplingRate,
2118 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002119{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002120 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2121 "%s called with format %#x", __func__, format);
2122
jiabinebb6af42020-06-09 17:31:17 -07002123 // Return the output that haptic-generating attached to when 1) session id is specified,
2124 // 2) haptic-generating effect exists for given session id and 3) the output that
2125 // haptic-generating effect attached to is in given outputs.
2126 if (sessionId != AUDIO_SESSION_NONE) {
2127 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2128 sessionId, FX_IID_HAPTICGENERATOR);
2129 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2130 return hapticGeneratingOutput;
2131 }
2132 }
2133
Eric Laurent16c66dd2019-05-01 17:54:10 -07002134 // Flags disqualifying an output: the match must happen before calling selectOutput()
2135 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2136 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2137
2138 // Flags expressing a functional request: must be honored in priority over
2139 // other criteria
2140 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2141 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002142 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2143 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002144 // Flags expressing a performance request: have lower priority than serving
2145 // requested sampling rate or channel mask
2146 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2147 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2148 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2149
2150 const audio_output_flags_t functionalFlags =
2151 (audio_output_flags_t)(flags & kFunctionalFlags);
2152 const audio_output_flags_t performanceFlags =
2153 (audio_output_flags_t)(flags & kPerformanceFlags);
2154
2155 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2156
Eric Laurente552edb2014-03-10 17:42:56 -07002157 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002158 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002159 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002160 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002161 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002162 // with tiebreak preferring the minimum number of extra functional flags
2163 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002164 // 3: the output supporting the exact channel mask
2165 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002166 // 5: the output with the highest sampling rate if the requested sample rate is
2167 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002168 // 6: the output with the highest number of requested performance flags
2169 // 7: the output with the bit depth the closest to the requested one
2170 // 8: the primary output
2171 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002172
Eric Laurent16c66dd2019-05-01 17:54:10 -07002173 // matching criteria values in priority order for best matching output so far
2174 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002175
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002176 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002177 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2178 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2179 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002180
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002181 for (audio_io_handle_t output : outputs) {
2182 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002183 // matching criteria values in priority order for current output
2184 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002185
Eric Laurent16c66dd2019-05-01 17:54:10 -07002186 if (outputDesc->isDuplicated()) {
2187 continue;
2188 }
2189 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2190 continue;
2191 }
Eric Laurent8838a382014-09-08 16:44:28 -07002192
Eric Laurent16c66dd2019-05-01 17:54:10 -07002193 // If haptic channel is specified, use the haptic output if present.
2194 // When using haptic output, same audio format and sample rate are required.
2195 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002196 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao808da212024-04-05 22:50:56 +00002197 // skip if haptic channel specified but output does not support it, or output support haptic
2198 // but there is no haptic channel requested AND no orphan haptic effect exist
2199 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2200 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002201 continue;
2202 }
Shunkai Yao808da212024-04-05 22:50:56 +00002203 // In the case of audio-coupled-haptic playback, there is no format conversion and
2204 // resampling in the framework, same format/channel/sampleRate for client and the output
2205 // thread is required. In the case of HapticGenerator effect, do not require format
2206 // matching.
2207 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2208 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao57b93392024-04-26 04:12:21 +00002209 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao808da212024-04-05 22:50:56 +00002210 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002211 }
2212
2213 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002214 const int matchingFunctionalFlags =
2215 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2216 const int totalFunctionalFlags =
2217 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2218 // Prefer matching functional flags, but subtract unnecessary functional flags.
2219 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002220
2221 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002222 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2223 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002224 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2225 channelCount <= outputChannelCount) {
2226 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002227 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2228 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002229 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002230 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002231 currentMatchCriteria[3] = outputChannelCount;
2232 }
2233
2234 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002235 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002236 int diff; // avoid unsigned integer overflow.
2237 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2238
2239 // prefer the closest output sampling rate greater than or equal to target
2240 // if none exists, prefer the closest output sampling rate less than target.
2241 //
2242 // criteria is offset to make non-negative.
2243 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002244 }
2245
2246 // performance flags match
2247 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2248
2249 // format match
2250 if (format != AUDIO_FORMAT_INVALID) {
2251 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002252 PolicyAudioPort::kFormatDistanceMax -
2253 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002254 }
2255
2256 // primary output match
2257 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2258
2259 // compare match criteria by priority then value
2260 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2261 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2262 bestMatchCriteria = currentMatchCriteria;
2263 bestOutput = output;
2264
2265 std::stringstream result;
2266 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2267 std::ostream_iterator<int>(result, " "));
2268 ALOGV("%s new bestOutput %d criteria %s",
2269 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002270 }
2271 }
2272
Eric Laurent16c66dd2019-05-01 17:54:10 -07002273 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002274}
2275
Eric Laurent8fc147b2018-07-22 19:13:55 -07002276status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002277{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002278 ALOGV("%s portId %d", __FUNCTION__, portId);
2279
2280 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2281 if (outputDesc == 0) {
2282 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002283 return BAD_VALUE;
2284 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002285 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002286
Eric Laurent8fc147b2018-07-22 19:13:55 -07002287 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002288 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002289
jiabin220eea12024-05-17 17:55:20 +00002290 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2291 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2292 && outputDesc->isBitPerfect()) {
2293 // Usually, APM selects bit-perfect output for high priority use cases only when
2294 // bit-perfect output is the only output that can be routed to the selected device.
2295 // However, here is no need to play high priority use cases such as ringtone and alarm
2296 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2297 // can attach to new output.
2298 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2299 __func__, client->stream());
2300 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2301 return DEAD_OBJECT;
2302 }
2303
Eric Laurent733ce942017-12-07 12:18:25 -08002304 status_t status = outputDesc->start();
2305 if (status != NO_ERROR) {
2306 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002307 }
2308
Eric Laurent97ac8712018-07-27 18:59:02 -07002309 uint32_t delayMs;
2310 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002311
2312 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002313 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002314 if (status == DEAD_OBJECT) {
2315 sp<SwAudioOutputDescriptor> desc =
2316 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2317 if (desc == nullptr) {
2318 // This is not common, it may indicate something wrong with the HAL.
2319 ALOGE("%s unable to open output with default config", __func__);
2320 return status;
2321 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002322 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002323 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002324 }
jiabina84c3d32022-12-02 18:59:55 +00002325
2326 // If the client is the first one active on preferred mixer parameters, reopen the output
2327 // if the current mixer parameters doesn't match the preferred one.
2328 if (outputDesc->devices().size() == 1) {
2329 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2330 outputDesc->devices()[0]->getId(), client->strategy());
2331 if (info != nullptr && info->getUid() == client->uid()) {
2332 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2333 info->getConfigBase(), info->getFlags())) {
2334 stopSource(outputDesc, client);
2335 outputDesc->stop();
2336 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2337 config.channel_mask = info->getConfigBase().channel_mask;
2338 config.sample_rate = info->getConfigBase().sample_rate;
2339 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002340 sp<SwAudioOutputDescriptor> desc =
2341 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2342 if (desc == nullptr) {
2343 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002344 }
jiabin220eea12024-05-17 17:55:20 +00002345 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002346 // Intentionally return error to let the client side resending request for
2347 // creating and starting.
2348 return DEAD_OBJECT;
2349 }
2350 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002351 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002352 // If it is first bit-perfect client, reroute all clients that will be routed to
2353 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2354 PortHandleVector clientsToInvalidate;
2355 for (size_t i = 0; i < mOutputs.size(); i++) {
2356 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002357 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002358 continue;
2359 }
2360 for (const auto& c : mOutputs[i]->getClientIterable()) {
2361 clientsToInvalidate.push_back(c->portId());
2362 }
2363 }
2364 if (!clientsToInvalidate.empty()) {
2365 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2366 __func__);
2367 mpClientInterface->invalidateTracks(clientsToInvalidate);
2368 }
2369 }
jiabina84c3d32022-12-02 18:59:55 +00002370 }
2371 }
2372
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002373 if (client->hasPreferredDevice()) {
2374 // playback activity with preferred device impacts routing occurred, inform upper layers
2375 mpClientInterface->onRoutingUpdated();
2376 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002377 if (delayMs != 0) {
2378 usleep(delayMs * 1000);
2379 }
2380
jiabin220eea12024-05-17 17:55:20 +00002381 if (status == NO_ERROR &&
2382 outputDesc->mPreferredAttrInfo != nullptr &&
2383 outputDesc->isBitPerfect() &&
2384 com::android::media::audioserver::
2385 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2386 // A new client is started on bit-perfect output, update all clients internal mute.
2387 updateClientsInternalMute(outputDesc);
2388 }
2389
Eric Laurentc75307b2015-03-17 15:29:32 -07002390 return status;
2391}
2392
Eric Laurent96d1dda2022-03-14 17:14:19 +01002393bool AudioPolicyManager::isLeUnicastActive() const {
2394 if (isInCall()) {
2395 return true;
2396 }
2397 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2398}
2399
2400bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2401 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2402 return false;
2403 }
2404 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2405 ALOGV("%s active %d", __func__, active);
2406 return active;
2407}
2408
Eric Laurent97ac8712018-07-27 18:59:02 -07002409status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2410 const sp<TrackClientDescriptor>& client,
2411 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002412{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002413 // cannot start playback of STREAM_TTS if any other output is being used
2414 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002415
2416 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002417 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002418 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002419 auto clientStrategy = client->strategy();
2420 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002421 if (stream == AUDIO_STREAM_TTS) {
2422 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002423 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002424 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002425 return INVALID_OPERATION;
2426 } else {
2427 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2428 }
2429 } else {
2430 // some playback other than beacon starts
2431 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2432 }
2433
Eric Laurent77305a62016-07-25 16:39:22 -07002434 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002435 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002436 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002437
François Gaffie11d30102018-11-02 16:09:09 +01002438 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002439 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002440 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002441 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002442 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002443 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002444 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002445 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002446 } else {
2447 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002448 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002449 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2450 AUDIO_FORMAT_DEFAULT);
2451 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2452 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002453 }
2454
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002455 // requiresMuteCheck is false when we can bypass mute strategy.
2456 // It covers a common case when there is no materially active audio
2457 // and muting would result in unnecessary delay and dropped audio.
2458 const uint32_t outputLatencyMs = outputDesc->latency();
2459 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002460 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002461
Eric Laurente552edb2014-03-10 17:42:56 -07002462 // increment usage count for this stream on the requested output:
2463 // NOTE that the usage count is the same for duplicated output and hardware output which is
2464 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002465 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002466
2467 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002468 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002469 // Preferred device may be exclusive, use only if no other active clients on this output
2470 devices = DeviceVector(
2471 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2472 } else {
2473 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2474 }
François Gaffie11d30102018-11-02 16:09:09 +01002475 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002476 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002477 }
2478 }
Eric Laurente552edb2014-03-10 17:42:56 -07002479
François Gaffiec005e562018-11-06 15:04:49 +01002480 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002481 selectOutputForMusicEffects();
2482 }
2483
François Gaffie1c878552018-11-22 16:53:21 +01002484 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002485 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002486 if (devices.isEmpty()) {
2487 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002488 }
François Gaffiec005e562018-11-06 15:04:49 +01002489 bool shouldWait =
2490 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2491 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2492 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002493 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002494 const bool needToCloseBitPerfectOutput =
2495 (com::android::media::audioserver::
2496 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2497 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2498 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002499 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002500 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002501 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002502 // An output has a shared device if
2503 // - managed by the same hw module
2504 // - supports the currently selected device
2505 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002506 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002507
Eric Laurent77305a62016-07-25 16:39:22 -07002508 // force a device change if any other output is:
2509 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002510 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002511 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002512 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002513 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002514 // change the device currently selected by the other output.
2515 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002516 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002517 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002518 force = true;
2519 }
2520 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002521 // a notification so that audio focus effect can propagate, or that a mute/unmute
2522 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002523 const uint32_t latencyMs = desc->latency();
2524 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2525
2526 if (shouldWait && isActive && (waitMs < latencyMs)) {
2527 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002528 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002529
2530 // Require mute check if another output is on a shared device
2531 // and currently active to have proper drain and avoid pops.
2532 // Note restoring AudioTracks onto this output needs to invoke
2533 // a volume ramp if there is no mute.
2534 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002535
2536 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2537 outputsToReopen.push_back(desc);
2538 }
Eric Laurente552edb2014-03-10 17:42:56 -07002539 }
2540 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002541
jiabin220eea12024-05-17 17:55:20 +00002542 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002543 // If the output is open with preferred mixer attributes, but the routed device is
2544 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2545 // changed.
2546 return DEAD_OBJECT;
2547 }
jiabin220eea12024-05-17 17:55:20 +00002548 for (auto& outputToReopen : outputsToReopen) {
2549 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2550 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002551 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302552 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2553 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002554
Eric Laurente552edb2014-03-10 17:42:56 -07002555 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002556 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002557 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002558 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002559 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002560 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002561 outputDesc->useHwGain() /*force*/)) {
2562 // request AudioService to reinitialize the volume curves asynchronously
2563 ALOGE("checkAndSetVolume failed, requesting volume range init");
2564 mpClientInterface->onVolumeRangeInitRequest();
2565 };
Eric Laurente552edb2014-03-10 17:42:56 -07002566
2567 // update the outputs if starting an output with a stream that can affect notification
2568 // routing
2569 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002570
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002571 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002572 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002573 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002574 }
Eric Laurentdc462862016-07-19 12:29:53 -07002575
2576 if (waitMs > muteWaitMs) {
2577 *delayMs = waitMs - muteWaitMs;
2578 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002579
2580 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2581 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2582 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2583 // change occurs after the MixerThread starts and causes a stream volume
2584 // glitch.
2585 //
2586 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002587 }
Eric Laurentdc462862016-07-19 12:29:53 -07002588
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002589 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002590 mEngine->getForceUse(
2591 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002592 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002593 }
2594
Eric Laurent97ac8712018-07-27 18:59:02 -07002595 // Automatically enable the remote submix input when output is started on a re routing mix
2596 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002597 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2598 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002599 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2600 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2601 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002602 "remote-submix",
2603 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002604 }
2605
Eric Laurent96d1dda2022-03-14 17:14:19 +01002606 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2607
Eric Laurente552edb2014-03-10 17:42:56 -07002608 return NO_ERROR;
2609}
2610
Eric Laurent96d1dda2022-03-14 17:14:19 +01002611void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2612 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2613 bool isUnicastActive = isLeUnicastActive();
2614
2615 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002616 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002617 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2618 for (size_t i = 0; i < mOutputs.size(); i++) {
2619 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2620 if (desc != ignoredOutput && desc->isActive()
2621 && ((isUnicastActive &&
2622 !desc->devices().
2623 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2624 || (wasUnicastActive &&
2625 !desc->devices().getDevicesFromTypes(
2626 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2627 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2628 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002629 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002630 // If the device is using preferred mixer attributes, the output need to reopen
2631 // with default configuration when the new selected devices are different from
2632 // current routing devices.
2633 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2634 continue;
2635 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302636 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002637 // re-apply device specific volume if not done by setOutputDevice()
2638 if (!force) {
2639 applyStreamVolumes(desc, newDevices.types(), delayMs);
2640 }
2641 }
2642 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002643 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002644 }
2645}
2646
Eric Laurent8fc147b2018-07-22 19:13:55 -07002647status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002648{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002649 ALOGV("%s portId %d", __FUNCTION__, portId);
2650
2651 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2652 if (outputDesc == 0) {
2653 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002654 return BAD_VALUE;
2655 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002656 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002657
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002658 if (client->hasPreferredDevice(true)) {
2659 // playback activity with preferred device impacts routing occurred, inform upper layers
2660 mpClientInterface->onRoutingUpdated();
2661 }
2662
Eric Laurent97ac8712018-07-27 18:59:02 -07002663 ALOGV("stopOutput() output %d, stream %d, session %d",
2664 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002665
Eric Laurent97ac8712018-07-27 18:59:02 -07002666 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002667
Eric Laurent733ce942017-12-07 12:18:25 -08002668 if (status == NO_ERROR ) {
2669 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002670 } else {
2671 return status;
2672 }
2673
2674 if (outputDesc->devices().size() == 1) {
2675 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2676 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002677 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002678 if (info != nullptr && info->getUid() == client->uid()) {
2679 info->decreaseActiveClient();
2680 if (info->getActiveClientCount() == 0) {
2681 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002682 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002683 }
2684 }
jiabin220eea12024-05-17 17:55:20 +00002685 if (com::android::media::audioserver::
2686 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2687 !outputReopened && outputDesc->isBitPerfect()) {
2688 // Only need to update the clients' internal mute when the output is bit-perfect and it
2689 // is not reopened.
2690 updateClientsInternalMute(outputDesc);
2691 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002692 }
2693 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002694}
2695
Eric Laurent97ac8712018-07-27 18:59:02 -07002696status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2697 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002698{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002699 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002700 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002701 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002702 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002703
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002704 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2705
François Gaffie1c878552018-11-22 16:53:21 +01002706 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2707 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002708 // Automatically disable the remote submix input when output is stopped on a
2709 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002710 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002711 if (isSingleDeviceType(
2712 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002713 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002714 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002715 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2716 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002717 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002718 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002719 }
2720 }
2721 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002722 if (client->hasPreferredDevice(true) &&
2723 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002724 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002725 forceDeviceUpdate = true;
2726 }
2727
Eric Laurente552edb2014-03-10 17:42:56 -07002728 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002729 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002730
Eric Laurente552edb2014-03-10 17:42:56 -07002731 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002732 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002733 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002734 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002735
2736 // If the routing does not change, if an output is routed on a device using HwGain
2737 // (aka setAudioPortConfig) and there are still active clients following different
2738 // volume group(s), force reapply volume
2739 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2740 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2741
Eric Laurente552edb2014-03-10 17:42:56 -07002742 // delay the device switch by twice the latency because stopOutput() is executed when
2743 // the track stop() command is received and at that time the audio track buffer can
2744 // still contain data that needs to be drained. The latency only covers the audio HAL
2745 // and kernel buffers. Also the latency does not always include additional delay in the
2746 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302747 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002748 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002749
2750 // force restoring the device selection on other active outputs if it differs from the
2751 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002752 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002753 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002754 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002755 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002756 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002757 desc->isActive() &&
2758 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002759 (newDevices != desc->devices())) {
2760 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2761 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002762
jiabin220eea12024-05-17 17:55:20 +00002763 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002764 // If the device is using preferred mixer attributes, the output need to
2765 // reopen with default configuration when the new selected devices are
2766 // different from current routing devices.
2767 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2768 continue;
2769 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302770 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002771
Eric Laurent57de36c2016-09-28 16:59:11 -07002772 // re-apply device specific volume if not done by setOutputDevice()
2773 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002774 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002775 }
Eric Laurente552edb2014-03-10 17:42:56 -07002776 }
2777 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002778 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002779 // update the outputs if stopping one with a stream that can affect notification routing
2780 handleNotificationRoutingForStream(stream);
2781 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002782
2783 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2784 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002785 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002786 }
2787
François Gaffiec005e562018-11-06 15:04:49 +01002788 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002789 selectOutputForMusicEffects();
2790 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002791
2792 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2793
Eric Laurente552edb2014-03-10 17:42:56 -07002794 return NO_ERROR;
2795 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002796 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002797 return INVALID_OPERATION;
2798 }
2799}
2800
jiabinbce0c1d2020-10-05 11:20:18 -07002801bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002802{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002803 ALOGV("%s portId %d", __FUNCTION__, portId);
2804
2805 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2806 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002807 // If an output descriptor is closed due to a device routing change,
2808 // then there are race conditions with releaseOutput from tracks
2809 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2810 // destroyed shortly thereafter.
2811 //
2812 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002813 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002814 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002815 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002816
2817 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002818
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302819 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2820 if (outputDesc->isClientActive(client)) {
2821 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2822 stopOutput(portId);
2823 }
2824
Eric Laurent8fc147b2018-07-22 19:13:55 -07002825 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2826 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002827 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002828 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002829 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002830 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002831 if (--outputDesc->mDirectOpenCount == 0) {
2832 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002833 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002834 }
2835 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302836
Andy Hung39efb7a2018-09-26 15:39:28 -07002837 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002838 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2839 // The output is pending reopened to query dynamic profiles and
2840 // there is no active clients
2841 closeOutput(outputDesc->mIoHandle);
2842 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2843 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2844 if (newOutputDesc == nullptr) {
2845 ALOGE("%s failed to open output", __func__);
2846 }
2847 return true;
2848 }
2849 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002850}
2851
Eric Laurentcaf7f482014-11-25 17:50:47 -08002852status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2853 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002854 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002855 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002856 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002857 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002858 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002859 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002860 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002861 audio_port_handle_t *portId,
2862 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002863{
François Gaffiec005e562018-11-06 15:04:49 +01002864 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002865 "flags %#x attributes=%s requested device ID %d",
2866 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2867 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002868
Eric Laurentad2e7b92017-09-14 20:06:42 -07002869 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002870 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002871 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002872 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002873 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002874 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002875 sp<RecordClientDescriptor> clientDesc;
2876 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002877 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002878 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002879
2880 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2881 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2882 return INVALID_OPERATION;
2883 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002884
Francois Gaffie716e1432019-01-14 16:58:59 +01002885 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2886 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002887 }
2888
Paul McLean466dc8e2015-04-17 13:15:36 -06002889 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002890 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002891 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002892
Eric Laurentad2e7b92017-09-14 20:06:42 -07002893 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2894 // possible
2895 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2896 *input != AUDIO_IO_HANDLE_NONE) {
2897 ssize_t index = mInputs.indexOfKey(*input);
2898 if (index < 0) {
2899 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2900 status = BAD_VALUE;
2901 goto error;
2902 }
2903 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002904 RecordClientVector clients = inputDesc->getClientsForSession(session);
2905 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002906 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2907 status = BAD_VALUE;
2908 goto error;
2909 }
2910 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2911 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002912 // corresponds to a new client and is only permitted from the same UID.
2913 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002914 if (clients.size() > 1) {
2915 for (const auto& client : clients) {
2916 // The client map is ordered by key values (portId) and portIds are allocated
2917 // incrementaly. So the first client in this list is the one opened by audio flinger
2918 // when the mmap stream is created and should be ignored as it does not correspond
2919 // to an actual client
2920 if (client == *clients.cbegin()) {
2921 continue;
2922 }
2923 if (uid != client->uid() && !client->isSilenced()) {
2924 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2925 uid, client->portId(), client->uid());
2926 status = INVALID_OPERATION;
2927 goto error;
2928 }
Eric Laurent331679c2018-04-16 17:03:16 -07002929 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002930 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002931 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002932 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002933
Eric Laurentfecbceb2021-02-09 14:46:43 +01002934 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002935 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002936 }
2937
2938 *input = AUDIO_IO_HANDLE_NONE;
2939 *inputType = API_INPUT_INVALID;
2940
Francois Gaffie716e1432019-01-14 16:58:59 +01002941 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002942 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002943 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002944 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002945 ALOGW("%s could not find input mix for attr %s",
2946 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002947 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002948 }
jiabinc1de2df2019-05-07 14:26:40 -07002949 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2950 String8(attr->tags + strlen("addr=")),
2951 AUDIO_FORMAT_DEFAULT);
2952 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002953 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002954 __func__, attributes.source, attributes.tags);
2955 status = BAD_VALUE;
2956 goto error;
2957 }
2958
Kevin Rocard25f9b052019-02-27 15:08:54 -08002959 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2960 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2961 } else {
2962 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2963 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002964 if (virtualDeviceId) {
2965 *virtualDeviceId = policyMix->mVirtualDeviceId;
2966 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002967 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002968 if (explicitRoutingDevice != nullptr) {
2969 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002970 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002971 // Prevent from storing invalid requested device id in clients
2972 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002973 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002974 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2975 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002976 }
François Gaffie11d30102018-11-02 16:09:09 +01002977 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002978 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002979 status = BAD_VALUE;
2980 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002981 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002982 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2983 *inputType = API_INPUT_MIX_CAPTURE;
2984 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002985 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2986 // there is an external policy, but this input is attached to a mix of recorders,
2987 // meaning it receives audio injected into the framework, so the recorder doesn't
2988 // know about it and is therefore considered "legacy"
2989 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002990
2991 if (virtualDeviceId) {
2992 *virtualDeviceId = policyMix->mVirtualDeviceId;
2993 }
François Gaffie11d30102018-11-02 16:09:09 +01002994 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002995 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002996 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002997 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002998 } else {
2999 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08003000 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07003001
Eric Laurent599c7582015-12-07 18:05:55 -08003002 }
3003
François Gaffiec005e562018-11-06 15:04:49 +01003004 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003005 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003006 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003007 AudioProfileVector profiles;
3008 status_t ret = getProfilesForDevices(
3009 DeviceVector(device), profiles, flags, true /*isInput*/);
3010 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003011 const auto channels = profiles[0]->getChannels();
3012 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3013 config->channel_mask = *channels.begin();
3014 }
3015 const auto sampleRates = profiles[0]->getSampleRates();
3016 if (!sampleRates.empty() &&
3017 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3018 config->sample_rate = *sampleRates.begin();
3019 }
jiabinf1c73972022-04-14 16:28:52 -07003020 config->format = profiles[0]->getFormat();
3021 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003022 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003023 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003024
Marvin Ramine5a122d2023-12-07 13:57:59 +01003025
3026 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3027 *virtualDeviceId = policyMix->mVirtualDeviceId;
3028 }
3029
Eric Laurent8f42ea12018-08-08 09:08:25 -07003030exit:
3031
François Gaffiec005e562018-11-06 15:04:49 +01003032 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3033 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003034
Francois Gaffie716e1432019-01-14 16:58:59 +01003035 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003036 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003037 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003038
Mikhail Naganov2996f672019-04-18 12:29:59 -07003039 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003040 requestedDeviceId, attributes.source, flags,
3041 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003042 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003043 // Move (if found) effect for the client session to its input
3044 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003045 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003046
3047 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3048 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003049
Eric Laurent599c7582015-12-07 18:05:55 -08003050 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003051
3052error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003053 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003054}
3055
3056
François Gaffie11d30102018-11-02 16:09:09 +01003057audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003058 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003059 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003060 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003061 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003062 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003063{
3064 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003065 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003066 bool isSoundTrigger = false;
3067
François Gaffiec005e562018-11-06 15:04:49 +01003068 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003069 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3070 if (index >= 0) {
3071 input = mSoundTriggerSessions.valueFor(session);
3072 isSoundTrigger = true;
3073 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3074 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3075 } else {
3076 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003077 }
François Gaffiec005e562018-11-06 15:04:49 +01003078 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003079 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003080 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003081 }
3082
Carter Hsua3abb402021-10-26 11:11:20 +08003083 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3084 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3085 }
3086
Eric Laurentfe231122017-11-17 17:48:06 -08003087 // sampling rate and flags may be updated by getInputProfile
3088 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3089 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003090 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003091 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003092 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003093 // find a compatible input profile (not necessarily identical in parameters)
3094 sp<IOProfile> profile = getInputProfile(
3095 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3096 if (profile == nullptr) {
3097 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003098 }
jiabin2fd710d2022-05-02 23:20:22 +00003099
Glenn Kasten05ddca52016-02-11 08:17:12 -08003100 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003101 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003102 if (samplingRate == 0) {
3103 samplingRate = profileSamplingRate;
3104 }
Eric Laurente552edb2014-03-10 17:42:56 -07003105
Eric Laurent322b4d22015-04-03 15:57:54 -07003106 if (profile->getModuleHandle() == 0) {
3107 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003108 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003109 }
3110
Eric Laurentec376dc2021-04-08 20:41:22 +02003111 // Reuse an already opened input if a client with the same session ID already exists
3112 // on that input
3113 for (size_t i = 0; i < mInputs.size(); i++) {
3114 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3115 if (desc->mProfile != profile) {
3116 continue;
3117 }
3118 RecordClientVector clients = desc->clientsList();
3119 for (const auto &client : clients) {
3120 if (session == client->session()) {
3121 return desc->mIoHandle;
3122 }
3123 }
3124 }
3125
Eric Laurent3974e3b2017-12-07 17:58:43 -08003126 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003127 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003128 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003129 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003130 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003131 continue;
3132 }
3133 // if sound trigger, reuse input if used by other sound trigger on same session
3134 // else
3135 // reuse input if active client app is not in IDLE state
3136 //
3137 RecordClientVector clients = desc->clientsList();
3138 bool doClose = false;
3139 for (const auto& client : clients) {
3140 if (isSoundTrigger != client->isSoundTrigger()) {
3141 continue;
3142 }
3143 if (client->isSoundTrigger()) {
3144 if (session == client->session()) {
3145 return desc->mIoHandle;
3146 }
3147 continue;
3148 }
3149 if (client->active() && client->appState() != APP_STATE_IDLE) {
3150 return desc->mIoHandle;
3151 }
3152 doClose = true;
3153 }
3154 if (doClose) {
3155 closeInput(desc->mIoHandle);
3156 } else {
3157 i++;
3158 }
3159 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003160 }
3161
Eric Laurentfe231122017-11-17 17:48:06 -08003162 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003163
Eric Laurentfe231122017-11-17 17:48:06 -08003164 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3165 lConfig.sample_rate = profileSamplingRate;
3166 lConfig.channel_mask = profileChannelMask;
3167 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003168
François Gaffie11d30102018-11-02 16:09:09 +01003169 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003170
3171 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003172 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003173 (profileSamplingRate != lConfig.sample_rate) ||
3174 !audio_formats_match(profileFormat, lConfig.format) ||
3175 (profileChannelMask != lConfig.channel_mask)) {
3176 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003177 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003178 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003179 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003180 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003181 }
Eric Laurent599c7582015-12-07 18:05:55 -08003182 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003183 }
3184
Eric Laurentc722f302014-12-10 11:21:49 -08003185 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003186
Eric Laurent599c7582015-12-07 18:05:55 -08003187 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003188 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003189
Eric Laurent599c7582015-12-07 18:05:55 -08003190 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003191}
3192
Eric Laurent4eb58f12018-12-07 16:41:02 -08003193status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003194{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003195 ALOGV("%s portId %d", __FUNCTION__, portId);
3196
3197 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3198 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003199 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003200 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003201 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003202 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003203 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003204 if (client->active()) {
3205 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3206 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003207 }
3208
Eric Laurent8f42ea12018-08-08 09:08:25 -07003209 audio_session_t session = client->session();
3210
Eric Laurent4eb58f12018-12-07 16:41:02 -08003211 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003212
Eric Laurent4eb58f12018-12-07 16:41:02 -08003213 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003214
Eric Laurent4eb58f12018-12-07 16:41:02 -08003215 status_t status = inputDesc->start();
3216 if (status != NO_ERROR) {
3217 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003218 }
Eric Laurente552edb2014-03-10 17:42:56 -07003219
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003220 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003221 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003222 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003223
Eric Laurent8f42ea12018-08-08 09:08:25 -07003224 // indicate active capture to sound trigger service if starting capture from a mic on
3225 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003226 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003227 if (device != nullptr) {
3228 status = setInputDevice(input, device, true /* force */);
3229 } else {
3230 ALOGW("%s no new input device can be found for descriptor %d",
3231 __FUNCTION__, inputDesc->getId());
3232 status = BAD_VALUE;
3233 }
Eric Laurente552edb2014-03-10 17:42:56 -07003234
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003235 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003236 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003237 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003238 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003239 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3240 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003241 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003242 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003243
François Gaffie11d30102018-11-02 16:09:09 +01003244 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3245 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003246 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003247 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003248 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003249
Eric Laurent8f42ea12018-08-08 09:08:25 -07003250 // automatically enable the remote submix output when input is started if not
3251 // used by a policy mix of type MIX_TYPE_RECORDERS
3252 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003253 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003254 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003255 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003256 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003257 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3258 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003259 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003260 if (address != "") {
3261 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3262 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003263 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003264 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003265 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003266 } else if (status != NO_ERROR) {
3267 // Restore client activity state.
3268 inputDesc->setClientActive(client, false);
3269 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003270 }
3271
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003272 ALOGV("%s input %d source = %d status = %d exit",
3273 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003274
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003275 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003276}
3277
Eric Laurent8fc147b2018-07-22 19:13:55 -07003278status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003279{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003280 ALOGV("%s portId %d", __FUNCTION__, portId);
3281
3282 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3283 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003284 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003285 return BAD_VALUE;
3286 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003287 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003288 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003289 if (!client->active()) {
3290 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003291 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003292 }
Carter Hsue6139d52021-07-08 10:30:20 +08003293 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003294 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003295
Eric Laurent8f42ea12018-08-08 09:08:25 -07003296 inputDesc->stop();
3297 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003298 auto current_source = inputDesc->source();
3299 setInputDevice(input, getNewInputDevice(inputDesc),
3300 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003301 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003302 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003303 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003304 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003305 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3306 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003307 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003308 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003309
3310 // automatically disable the remote submix output when input is stopped if not
3311 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003312 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003313 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003314 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003315 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003316 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3317 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003318 }
3319 if (address != "") {
3320 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3321 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003322 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003323 }
3324 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003325 resetInputDevice(input);
3326
3327 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3328 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003329 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3330 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003331 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003332 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003333 }
3334 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003335 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003336 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003337}
3338
Eric Laurent8fc147b2018-07-22 19:13:55 -07003339void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003340{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003341 ALOGV("%s portId %d", __FUNCTION__, portId);
3342
3343 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3344 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003345 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003346 return;
3347 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003348 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003349 audio_io_handle_t input = inputDesc->mIoHandle;
3350
Eric Laurent8f42ea12018-08-08 09:08:25 -07003351 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003352
Andy Hung39efb7a2018-09-26 15:39:28 -07003353 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003354
3355 // If no more clients are present in this session, park effects to an orphan chain
3356 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3357 if (clientsOnSession.size() == 0) {
3358 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3359 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003360 if (inputDesc->getClientCount() > 0) {
3361 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003362 return;
3363 }
3364
Eric Laurent05b90f82014-08-27 15:32:29 -07003365 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003366 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003367 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003368}
3369
Eric Laurent8f42ea12018-08-08 09:08:25 -07003370void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003371{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003372 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003373
3374 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003375 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003376 }
3377}
3378
Eric Laurent8f42ea12018-08-08 09:08:25 -07003379void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3380{
3381 stopInput(portId);
3382 releaseInput(portId);
3383}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003384
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003385bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3386 if (input->clientsList().size() == 0
3387 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3388 return true;
3389 }
3390 for (const auto& client : input->clientsList()) {
3391 sp<DeviceDescriptor> device =
3392 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3393 client->session());
3394 if (!input->supportedDevices().contains(device)) {
3395 return true;
3396 }
3397 }
3398 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3399 return false;
3400}
3401
Eric Laurent0dd51852019-04-19 18:18:58 -07003402void AudioPolicyManager::checkCloseInputs() {
3403 // After connecting or disconnecting an input device, close input if:
3404 // - it has no client (was just opened to check profile) OR
3405 // - none of its supported devices are connected anymore OR
3406 // - one of its clients cannot be routed to one of its supported
3407 // devices anymore. Otherwise update device selection
3408 std::vector<audio_io_handle_t> inputsToClose;
3409 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003410 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003411 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003412 }
3413 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003414 for (const audio_io_handle_t handle : inputsToClose) {
3415 ALOGV("%s closing input %d", __func__, handle);
3416 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003417 }
Eric Laurentd4692962014-05-05 18:13:44 -07003418}
3419
Vlad Popa87e0e582024-05-20 18:49:20 -07003420status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3421 const char *address __unused,
3422 bool enabled,
3423 audio_stream_type_t streamToDriveAbs)
3424{
3425 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3426 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3427 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3428 toString(streamToDriveAbs).c_str());
3429 return BAD_VALUE;
3430 }
3431
3432 if (enabled) {
3433 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3434 } else {
3435 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3436 }
3437
3438 return NO_ERROR;
3439}
3440
François Gaffie251c7f02018-11-07 10:41:08 +01003441void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003442{
3443 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003444 if (indexMin < 0 || indexMax < 0) {
3445 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3446 return;
3447 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003448 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003449
3450 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003451 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3452 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003453 continue;
3454 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003455 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003456 }
Eric Laurente552edb2014-03-10 17:42:56 -07003457}
3458
Eric Laurente0720872014-03-11 09:30:41 -07003459status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003460 int index,
3461 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003462{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003463 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003464 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3465 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3466 return NO_ERROR;
3467 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303468 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3469 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003470 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003471}
3472
Eric Laurente0720872014-03-11 09:30:41 -07003473status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003474 int *index,
3475 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003476{
François Gaffiec005e562018-11-06 15:04:49 +01003477 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3478 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003479 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003480 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003481 deviceTypes = mEngine->getOutputDevicesForStream(
3482 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003483 }
jiabin9a3361e2019-10-01 09:38:30 -07003484 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003485}
3486
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003487status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003488 int index,
3489 audio_devices_t device)
3490{
3491 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003492 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3493 if (group == VOLUME_GROUP_NONE) {
3494 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003495 return BAD_VALUE;
3496 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003497 ALOGV("%s: group %d matching with %s index %d",
3498 __FUNCTION__, group, toString(attributes).c_str(), index);
Eric Laurentc86a3e12024-10-10 14:26:43 +00003499 if (mEngine->getStreamTypeForAttributes(attributes) == AUDIO_STREAM_PATCH) {
3500 ALOGV("%s: cannot change volume for PATCH stream, attrs: %s",
3501 __FUNCTION__, toString(attributes).c_str());
3502 return NO_ERROR;
3503 }
François Gaffiecfe17322018-11-07 13:41:29 +01003504 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003505 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003506 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003507 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3508 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3509 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3510 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003511 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3512
3513 status = setVolumeCurveIndex(index, device, curves);
3514 if (status != NO_ERROR) {
3515 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3516 return status;
3517 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003518
jiabin9a3361e2019-10-01 09:38:30 -07003519 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003520 auto curCurvAttrs = curves.getAttributes();
3521 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3522 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003523 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003524 } else if (!curves.getStreamTypes().empty()) {
3525 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003526 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003527 } else {
3528 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3529 return BAD_VALUE;
3530 }
jiabin9a3361e2019-10-01 09:38:30 -07003531 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3532 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003533
François Gaffiecfe17322018-11-07 13:41:29 +01003534 // update volume on all outputs and streams matching the following:
3535 // - The requested stream (or a stream matching for volume control) is active on the output
3536 // - The device (or devices) selected by the engine for this stream includes
3537 // the requested device
3538 // - For non default requested device, currently selected device on the output is either the
3539 // requested device or one of the devices selected by the engine for this stream
3540 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3541 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003542 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003543 for (size_t i = 0; i < mOutputs.size(); i++) {
3544 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003545 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003546
jiabin9a3361e2019-10-01 09:38:30 -07003547 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3548 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003549 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003550
3551 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003552 continue;
3553 }
3554 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3555 curDevices.find(device) == curDevices.end()) {
3556 continue;
3557 }
3558 bool applyVolume = false;
3559 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3560 curSrcDevices.insert(device);
3561 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003562 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3563 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003564 } else {
3565 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3566 }
3567 if (!applyVolume) {
3568 continue; // next output
3569 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003570 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3571 // If a higher priority strategy is active, and the output is routed to a device with a
3572 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003573 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003574 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003575 // If the volume source is active with higher priority source, ensure at least Sw Muted
3576 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003577 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3578 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3579 false /*preferredDevice*/);
3580 if (activeClients.empty()) {
3581 continue;
3582 }
3583 bool isPreempted = false;
3584 bool isHigherPriority = productStrategy < strategy;
3585 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003586 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003587 ALOGV("%s: Strategy=%d (\nrequester:\n"
3588 " group %d, volumeGroup=%d attributes=%s)\n"
3589 " higher priority source active:\n"
3590 " volumeGroup=%d attributes=%s) \n"
3591 " on output %zu, bailing out", __func__, productStrategy,
3592 group, group, toString(attributes).c_str(),
3593 client->volumeSource(), toString(client->attributes()).c_str(), i);
3594 applyVolume = false;
3595 isPreempted = true;
3596 break;
3597 }
3598 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003599 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003600 applyVolume = true;
3601 }
3602 }
3603 if (isPreempted || applyVolume) {
3604 break;
3605 }
3606 }
3607 if (!applyVolume) {
3608 continue; // next output
3609 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003610 }
François Gaffieed91f582020-01-31 10:35:37 +01003611 //FIXME: workaround for truncated touch sounds
3612 // delayed volume change for system stream to be removed when the problem is
3613 // handled by system UI
3614 status_t volStatus = checkAndSetVolume(
3615 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003616 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003617 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3618 if (volStatus != NO_ERROR) {
3619 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003620 }
3621 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003622
3623 // update voice volume if the an active call route exists
3624 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3625 && (curSrcDevices.find(
3626 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3627 != curSrcDevices.end())) {
3628 bool isVoiceVolSrc;
3629 bool isBtScoVolSrc;
3630 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3631 isVoiceVolSrc, isBtScoVolSrc, __func__)
3632 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003633 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3634 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3635 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003636 }
3637 }
3638
François Gaffiecfe17322018-11-07 13:41:29 +01003639 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3640 return status;
3641}
3642
François Gaffieaaac0fd2018-11-22 17:56:39 +01003643status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003644 audio_devices_t device,
3645 IVolumeCurves &volumeCurves)
3646{
3647 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3648 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003649 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3650 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003651 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303652 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3653 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003654 return BAD_VALUE;
3655 }
3656 if (!audio_is_output_device(device)) {
3657 return BAD_VALUE;
3658 }
3659
3660 // Force max volume if stream cannot be muted
3661 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3662
François Gaffieaaac0fd2018-11-22 17:56:39 +01003663 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003664 volumeCurves.addCurrentVolumeIndex(device, index);
3665 return NO_ERROR;
3666}
3667
3668status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3669 int &index,
3670 audio_devices_t device)
3671{
3672 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3673 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003674 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003675 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003676 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003677 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003678 }
jiabin9a3361e2019-10-01 09:38:30 -07003679 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003680}
3681
3682status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3683 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003684 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003685{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003686 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003687 return BAD_VALUE;
3688 }
jiabin9a3361e2019-10-01 09:38:30 -07003689 index = curves.getVolumeIndex(deviceTypes);
3690 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003691 return NO_ERROR;
3692}
3693
3694status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3695 int &index)
3696{
3697 index = getVolumeCurves(attr).getVolumeIndexMin();
3698 return NO_ERROR;
3699}
3700
3701status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3702 int &index)
3703{
3704 index = getVolumeCurves(attr).getVolumeIndexMax();
3705 return NO_ERROR;
3706}
3707
Eric Laurent36829f92017-04-07 19:04:42 -07003708audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003709{
3710 // select one output among several suitable for global effects.
3711 // The priority is as follows:
3712 // 1: An offloaded output. If the effect ends up not being offloadable,
3713 // AudioFlinger will invalidate the track and the offloaded output
3714 // will be closed causing the effect to be moved to a PCM output.
3715 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003716 // 3: The primary output
3717 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003718
François Gaffiec005e562018-11-06 15:04:49 +01003719 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3720 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003721 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003722
Eric Laurent36829f92017-04-07 19:04:42 -07003723 if (outputs.size() == 0) {
3724 return AUDIO_IO_HANDLE_NONE;
3725 }
Eric Laurente552edb2014-03-10 17:42:56 -07003726
Eric Laurent36829f92017-04-07 19:04:42 -07003727 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3728 bool activeOnly = true;
3729
3730 while (output == AUDIO_IO_HANDLE_NONE) {
3731 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3732 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3733 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3734
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003735 for (audio_io_handle_t output : outputs) {
3736 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003737 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003738 continue;
3739 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003740 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3741 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003742 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003743 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003744 }
3745 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003746 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003747 }
3748 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003749 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003750 }
3751 }
3752 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3753 output = outputOffloaded;
3754 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3755 output = outputDeepBuffer;
3756 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3757 output = outputPrimary;
3758 } else {
3759 output = outputs[0];
3760 }
3761 activeOnly = false;
3762 }
3763
3764 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003765 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3766 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003767 mMusicEffectOutput = output;
3768 }
3769
3770 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003771 return output;
3772}
3773
Eric Laurent36829f92017-04-07 19:04:42 -07003774audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3775{
3776 return selectOutputForMusicEffects();
3777}
3778
Eric Laurente0720872014-03-11 09:30:41 -07003779status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003780 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003781 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003782 int session,
3783 int id)
3784{
Shunkai Yao2fa06c12024-03-19 04:31:47 +00003785 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003786 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003787 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003788 index = mInputs.indexOfKey(io);
3789 if (index < 0) {
3790 ALOGW("registerEffect() unknown io %d", io);
3791 return INVALID_OPERATION;
3792 }
Eric Laurente552edb2014-03-10 17:42:56 -07003793 }
3794 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003795 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3796 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3797 || strategy == PRODUCT_STRATEGY_NONE));
3798 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003799}
3800
Eric Laurentc241b0d2018-11-28 09:08:49 -08003801status_t AudioPolicyManager::unregisterEffect(int id)
3802{
3803 if (mEffects.getEffect(id) == nullptr) {
3804 return INVALID_OPERATION;
3805 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003806 if (mEffects.isEffectEnabled(id)) {
3807 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3808 setEffectEnabled(id, false);
3809 }
3810 return mEffects.unregisterEffect(id);
3811}
3812
3813status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3814{
3815 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3816 if (effect == nullptr) {
3817 return INVALID_OPERATION;
3818 }
3819
3820 status_t status = mEffects.setEffectEnabled(id, enabled);
3821 if (status == NO_ERROR) {
3822 mInputs.trackEffectEnabled(effect, enabled);
3823 }
3824 return status;
3825}
3826
Eric Laurent6c796322019-04-09 14:13:17 -07003827
3828status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3829{
3830 mEffects.moveEffects(ids, io);
3831 return NO_ERROR;
3832}
3833
Eric Laurentc75307b2015-03-17 15:29:32 -07003834bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3835{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003836 auto vs = toVolumeSource(stream, false);
3837 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003838}
3839
3840bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3841{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003842 auto vs = toVolumeSource(stream, false);
3843 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003844}
3845
Eric Laurente0720872014-03-11 09:30:41 -07003846bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003847{
3848 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003849 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003850 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003851 return true;
3852 }
3853 }
3854 return false;
3855}
3856
Eric Laurent275e8e92014-11-30 15:14:47 -08003857// Register a list of custom mixes with their attributes and format.
3858// When a mix is registered, corresponding input and output profiles are
3859// added to the remote submix hw module. The profile contains only the
3860// parameters (sampling rate, format...) specified by the mix.
3861// The corresponding input remote submix device is also connected.
3862//
3863// When a remote submix device is connected, the address is checked to select the
3864// appropriate profile and the corresponding input or output stream is opened.
3865//
3866// When capture starts, getInputForAttr() will:
3867// - 1 look for a mix matching the address passed in attribtutes tags if any
3868// - 2 if none found, getDeviceForInputSource() will:
3869// - 2.1 look for a mix matching the attributes source
3870// - 2.2 if none found, default to device selection by policy rules
3871// At this time, the corresponding output remote submix device is also connected
3872// and active playback use cases can be transferred to this mix if needed when reconnecting
3873// after AudioTracks are invalidated
3874//
3875// When playback starts, getOutputForAttr() will:
3876// - 1 look for a mix matching the address passed in attribtutes tags if any
3877// - 2 if none found, look for a mix matching the attributes usage
3878// - 3 if none found, default to device and output selection by policy rules.
3879
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003880status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003881{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003882 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3883 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003884 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003885 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003886 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003887 // examine each mix's route type
3888 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003889 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003890 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3891 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3892 ALOGE("Unsupported Policy Mix %zu of %zu: "
3893 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3894 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003895 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003896 break;
3897 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003898 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3899 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003900 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003901 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3902 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003903 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003904 rSubmixModule = mHwModules.getModuleFromName(
3905 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3906 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003907 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003908 i);
3909 res = INVALID_OPERATION;
3910 break;
3911 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003912 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003913
Eric Laurent97ac8712018-07-27 18:59:02 -07003914 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003915 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003916 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003917 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003918 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3919 } else {
3920 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3921 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003922 }
François Gaffie036e1e92015-03-19 10:16:24 +01003923
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003924 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003925 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003926 res = INVALID_OPERATION;
3927 break;
3928 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003929 audio_config_t outputConfig = mix.mFormat;
3930 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003931 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3932 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003933 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3934 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003935 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003936 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3937 audio_is_linear_pcm(outputConfig.format)
3938 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003939 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003940 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3941 audio_is_linear_pcm(inputConfig.format)
3942 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003943
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003944 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003945 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003946 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003947 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003948 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003949 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003950 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003951 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3952 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003953 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003954 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003955 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003956
3957 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3958 mix.mDeviceType, mix.mDeviceAddress,
3959 String8(), AUDIO_FORMAT_DEFAULT);
3960 if (device == nullptr) {
3961 res = INVALID_OPERATION;
3962 break;
3963 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003964
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003965 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003966 // First try to find an already opened output supporting the device
3967 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003968 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003969
Eric Laurentc529cf62020-04-17 18:19:10 -07003970 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003971 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003972 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003973 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003974 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003975 } else {
3976 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003977 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003978 }
3979 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003980 // If no output found, try to find a direct output profile supporting the device
3981 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3982 sp<HwModule> module = mHwModules[i];
3983 for (size_t j = 0;
3984 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3985 j++) {
3986 sp<IOProfile> profile = module->getOutputProfiles()[j];
3987 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3988 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3989 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003990 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003991 res = INVALID_OPERATION;
3992 } else {
3993 foundOutput = true;
3994 }
3995 }
3996 }
3997 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003998 if (res != NO_ERROR) {
3999 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004000 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07004001 res = INVALID_OPERATION;
4002 break;
4003 } else if (!foundOutput) {
4004 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004005 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004006 res = INVALID_OPERATION;
4007 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07004008 } else {
4009 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004010 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004011 }
Eric Laurentc722f302014-12-10 11:21:49 -08004012 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004013 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004014 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004015 if (audio_flags::audio_mix_ownership()) {
4016 // Only unregister mixes that were actually registered to not accidentally unregister
4017 // mixes that already existed previously.
4018 unregisterPolicyMixes(registeredMixes);
4019 registeredMixes.clear();
4020 } else {
4021 unregisterPolicyMixes(mixes);
4022 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004023 } else if (checkOutputs) {
4024 checkForDeviceAndOutputChanges();
4025 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004026 }
4027 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004028}
4029
4030status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4031{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004032 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004033 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004034 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004035 sp<HwModule> rSubmixModule;
4036 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004037 for (const auto& mix : mixes) {
4038 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004039
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004040 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004041 rSubmixModule = mHwModules.getModuleFromName(
4042 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4043 if (rSubmixModule == 0) {
4044 res = INVALID_OPERATION;
4045 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004046 }
4047 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004048
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004049 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004050
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004051 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004052 res = INVALID_OPERATION;
4053 continue;
4054 }
4055
Marvin Ramin0783e202024-03-05 12:45:50 +01004056 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004057 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004058 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4059 status_t currentRes =
4060 setDeviceConnectionStateInt(device,
4061 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4062 address.c_str(),
4063 "remote-submix",
4064 AUDIO_FORMAT_DEFAULT);
4065 if (!audio_flags::audio_mix_ownership()) {
4066 res = currentRes;
4067 }
4068 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004069 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004070 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004071 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004072 }
4073 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004074 }
jiabin5740f082019-08-19 15:08:30 -07004075 rSubmixModule->removeOutputProfile(address.c_str());
4076 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004077
Kevin Rocard153f92d2018-12-18 18:33:28 -08004078 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004079 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004080 res = INVALID_OPERATION;
4081 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004082 } else {
4083 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004084 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004085 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004086 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004087
4088 if (res == NO_ERROR && checkOutputs) {
4089 checkForDeviceAndOutputChanges();
4090 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004091 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004092 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004093}
4094
Marvin Raminbdefaf02023-11-01 09:10:32 +01004095status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4096 if (!audio_flags::audio_mix_test_api()) {
4097 return INVALID_OPERATION;
4098 }
4099
4100 _aidl_return.clear();
4101 _aidl_return.reserve(mPolicyMixes.size());
4102 for (const auto &policyMix: mPolicyMixes) {
4103 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4104 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4105 policyMix->mCbFlags);
4106 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004107 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004108 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004109 }
4110
Vlad Popaa5d73f32024-03-08 16:05:38 -08004111 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004112 return OK;
4113}
4114
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004115status_t AudioPolicyManager::updatePolicyMix(
4116 const AudioMix& mix,
4117 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4118 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4119 if (res == NO_ERROR) {
4120 checkForDeviceAndOutputChanges();
4121 updateCallAndOutputRouting();
4122 }
4123 return res;
4124}
4125
Mikhail Naganov100f0122018-11-29 11:22:16 -08004126void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4127{
4128 size_t i = 0;
4129 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4130 for (const auto& fmt : mManualSurroundFormats) {
4131 if (i++ != 0) dst->append(", ");
4132 std::string sfmt;
4133 FormatConverter::toString(fmt, sfmt);
4134 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4135 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4136 }
4137}
4138
Eric Laurentc529cf62020-04-17 18:19:10 -07004139// Returns true if all devices types match the predicate and are supported by one HW module
4140bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004141 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004142 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004143 const char *context,
4144 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004145 for (size_t i = 0; i < devices.size(); i++) {
4146 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004147 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004148 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004149 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004150 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004151 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004152 return false;
4153 }
4154 }
4155 return true;
4156}
4157
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004158void AudioPolicyManager::changeOutputDevicesMuteState(
4159 const AudioDeviceTypeAddrVector& devices) {
4160 ALOGVV("%s() num devices %zu", __func__, devices.size());
4161
4162 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4163 getSoftwareOutputsForDevices(devices);
4164
4165 for (size_t i = 0; i < outputs.size(); i++) {
4166 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4167 DeviceVector prevDevices = outputDesc->devices();
4168 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4169 }
4170}
4171
4172std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4173 const AudioDeviceTypeAddrVector& devices) const
4174{
4175 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4176 DeviceVector deviceDescriptors;
4177 for (size_t j = 0; j < devices.size(); j++) {
4178 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4179 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4180 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4181 ALOGE("%s: device type %#x address %s not supported or not an output device",
4182 __func__, devices[j].mType, devices[j].getAddress());
4183 continue;
4184 }
4185 deviceDescriptors.add(desc);
4186 }
4187 for (size_t i = 0; i < mOutputs.size(); i++) {
4188 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4189 continue;
4190 }
4191 outputs.push_back(mOutputs.valueAt(i));
4192 }
4193 return outputs;
4194}
4195
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004196status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004197 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004198 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004199 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4200 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004201 }
4202 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004203 if (res != NO_ERROR) {
4204 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4205 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004206 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004207
4208 checkForDeviceAndOutputChanges();
4209 updateCallAndOutputRouting();
4210
4211 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004212}
4213
4214status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4215 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004216 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4217 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004218 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004219 __FUNCTION__, uid);
4220 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004221 }
4222
Eric Laurentc529cf62020-04-17 18:19:10 -07004223 checkForDeviceAndOutputChanges();
4224 updateCallAndOutputRouting();
4225
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004226 return res;
4227}
4228
Eric Laurent2517af32020-11-25 15:31:27 +01004229
jiabin0a488932020-08-07 17:32:40 -07004230status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4231 device_role_t role,
4232 const AudioDeviceTypeAddrVector &devices) {
4233 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4234 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004235
Eric Laurentc529cf62020-04-17 18:19:10 -07004236 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004237 return BAD_VALUE;
4238 }
jiabin0a488932020-08-07 17:32:40 -07004239 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004240 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004241 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4242 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004243 return status;
4244 }
4245
4246 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004247
4248 bool forceVolumeReeval = false;
4249 // FIXME: workaround for truncated touch sounds
4250 // to be removed when the problem is handled by system UI
4251 uint32_t delayMs = 0;
4252 if (strategy == mCommunnicationStrategy) {
4253 forceVolumeReeval = true;
4254 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4255 updateInputRouting();
4256 }
4257 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004258
4259 return NO_ERROR;
4260}
4261
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004262void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4263 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004264{
4265 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004266 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004267 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004268 // Only apply special touch sound delay once
4269 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004270 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004271 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004272 for (size_t i = 0; i < mOutputs.size(); i++) {
4273 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4274 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004275 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4276 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004277 // As done in setDeviceConnectionState, we could also fix default device issue by
4278 // preventing the force re-routing in case of default dev that distinguishes on address.
4279 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004280 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004281 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004282 // If the device is using preferred mixer attributes, the output need to reopen
4283 // with default configuration when the new selected devices are different from
4284 // current routing devices.
4285 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4286 continue;
4287 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304288
4289 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4290 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004291 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004292 // Only apply special touch sound delay once
4293 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004294 }
4295 if (forceVolumeReeval && !newDevices.isEmpty()) {
4296 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4297 }
4298 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004299 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004300 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004301}
4302
Eric Laurent2517af32020-11-25 15:31:27 +01004303void AudioPolicyManager::updateInputRouting() {
4304 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304305 // Skip for hotword recording as the input device switch
4306 // is handled within sound trigger HAL
4307 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4308 continue;
4309 }
Eric Laurent2517af32020-11-25 15:31:27 +01004310 auto newDevice = getNewInputDevice(activeDesc);
4311 // Force new input selection if the new device can not be reached via current input
4312 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4313 setInputDevice(activeDesc->mIoHandle, newDevice);
4314 } else {
4315 closeInput(activeDesc->mIoHandle);
4316 }
4317 }
4318}
4319
Paul Wang5d7cdb52022-11-22 09:45:06 +00004320status_t
4321AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4322 device_role_t role,
4323 const AudioDeviceTypeAddrVector &devices) {
4324 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4325 dumpAudioDeviceTypeAddrVector(devices).c_str());
4326
Eric Laurent78fedbf2023-03-09 14:40:44 +01004327 if (!areAllDevicesSupported(
4328 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004329 return BAD_VALUE;
4330 }
4331 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4332 if (status != NO_ERROR) {
4333 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4334 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4335 return status;
4336 }
4337
4338 checkForDeviceAndOutputChanges();
4339
4340 bool forceVolumeReeval = false;
4341 // TODO(b/263479999): workaround for truncated touch sounds
4342 // to be removed when the problem is handled by system UI
4343 uint32_t delayMs = 0;
4344 if (strategy == mCommunnicationStrategy) {
4345 forceVolumeReeval = true;
4346 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4347 updateInputRouting();
4348 }
4349 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4350
4351 return NO_ERROR;
4352}
4353
4354status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4355 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004356{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004357 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004358
Paul Wang5d7cdb52022-11-22 09:45:06 +00004359 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004360 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004361 ALOGW_IF(status != NAME_NOT_FOUND,
4362 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004363 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004364 return status;
4365 }
4366
4367 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004368
4369 bool forceVolumeReeval = false;
4370 // FIXME: workaround for truncated touch sounds
4371 // to be removed when the problem is handled by system UI
4372 uint32_t delayMs = 0;
4373 if (strategy == mCommunnicationStrategy) {
4374 forceVolumeReeval = true;
4375 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4376 updateInputRouting();
4377 }
4378 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004379
4380 return NO_ERROR;
4381}
4382
jiabin0a488932020-08-07 17:32:40 -07004383status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4384 device_role_t role,
4385 AudioDeviceTypeAddrVector &devices) {
4386 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004387}
4388
Jiabin Huang3b98d322020-09-03 17:54:16 +00004389status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4390 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4391 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4392 dumpAudioDeviceTypeAddrVector(devices).c_str());
4393
Mikhail Naganov55773032020-10-01 15:08:13 -07004394 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004395 return BAD_VALUE;
4396 }
4397 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4398 ALOGW_IF(status != NO_ERROR,
4399 "Engine could not set preferred devices %s for audio source %d role %d",
4400 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4401
4402 return status;
4403}
4404
4405status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4406 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4407 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4408 dumpAudioDeviceTypeAddrVector(devices).c_str());
4409
Mikhail Naganov55773032020-10-01 15:08:13 -07004410 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004411 return BAD_VALUE;
4412 }
4413 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4414 ALOGW_IF(status != NO_ERROR,
4415 "Engine could not add preferred devices %s for audio source %d role %d",
4416 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4417
Eric Laurent2517af32020-11-25 15:31:27 +01004418 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004419 return status;
4420}
4421
4422status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4423 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4424{
4425 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4426 dumpAudioDeviceTypeAddrVector(devices).c_str());
4427
Eric Laurent78fedbf2023-03-09 14:40:44 +01004428 if (!areAllDevicesSupported(
4429 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004430 return BAD_VALUE;
4431 }
4432
4433 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4434 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004435 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004436 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004437 if (status == NO_ERROR) {
4438 updateInputRouting();
4439 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004440 return status;
4441}
4442
4443status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4444 device_role_t role) {
4445 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4446
4447 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004448 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004449 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004450 if (status == NO_ERROR) {
4451 updateInputRouting();
4452 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004453 return status;
4454}
4455
4456status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4457 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4458 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4459}
4460
Oscar Azucena90e77632019-11-27 17:12:28 -08004461status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004462 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004463 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004464 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4465 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004466 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004467 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4468 if (status != NO_ERROR) {
4469 ALOGE("%s() could not set device affinity for userId %d",
4470 __FUNCTION__, userId);
4471 return status;
4472 }
4473
4474 // reevaluate outputs for all devices
4475 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004476 changeOutputDevicesMuteState(devices);
4477 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4478 true /* skipDelays */);
4479 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004480
4481 return NO_ERROR;
4482}
4483
4484status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004485 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004486 AudioDeviceTypeAddrVector devices;
4487 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004488 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4489 if (status != NO_ERROR) {
4490 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4491 __FUNCTION__, userId);
4492 return status;
4493 }
4494
4495 // reevaluate outputs for all devices
4496 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004497 changeOutputDevicesMuteState(devices);
4498 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4499 true /* skipDelays */);
4500 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004501
4502 return NO_ERROR;
4503}
4504
Andy Hungc29d82b2018-10-05 12:23:17 -07004505void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004506{
Andy Hungc29d82b2018-10-05 12:23:17 -07004507 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004508 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004509 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004510 std::string stateLiteral;
4511 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004512 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004513 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4514 "communications", "media", "record", "dock", "system",
4515 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4516 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4517 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004518 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4519 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4520 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4521 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4522 dst->append(" (MANUAL: ");
4523 dumpManualSurroundFormats(dst);
4524 dst->append(")");
4525 }
4526 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004527 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004528 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4529 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004530 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004531 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004532
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004533 dst->append("\n");
4534 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4535 dst->append("\n");
4536 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004537 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004538 mOutputs.dump(dst);
4539 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004540 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004541 mAudioPatches.dump(dst);
4542 mPolicyMixes.dump(dst);
4543 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004544
Kevin Rocardb99cc752019-03-21 20:52:24 -07004545 dst->appendFormat(" AllowedCapturePolicies:\n");
4546 for (auto& policy : mAllowedCapturePolicies) {
4547 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4548 }
4549
jiabina84c3d32022-12-02 18:59:55 +00004550 dst->appendFormat(" Preferred mixer audio configuration:\n");
4551 for (const auto it : mPreferredMixerAttrInfos) {
4552 dst->appendFormat(" - device port id: %d\n", it.first);
4553 for (const auto preferredMixerInfoIt : it.second) {
4554 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4555 preferredMixerInfoIt.second->dump(dst);
4556 }
4557 }
4558
François Gaffiec005e562018-11-06 15:04:49 +01004559 dst->appendFormat("\nPolicy Engine dump:\n");
4560 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004561
4562 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4563 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4564 dst->appendFormat(" - device type: %s, driving stream %d\n",
4565 dumpDeviceTypes({it.first}).c_str(),
4566 mEngine->getVolumeGroupForAttributes(it.second));
4567 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004568}
4569
4570status_t AudioPolicyManager::dump(int fd)
4571{
4572 String8 result;
4573 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004574 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004575 return NO_ERROR;
4576}
4577
Kevin Rocardb99cc752019-03-21 20:52:24 -07004578status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4579{
4580 mAllowedCapturePolicies[uid] = capturePolicy;
4581 return NO_ERROR;
4582}
4583
Eric Laurente552edb2014-03-10 17:42:56 -07004584// This function checks for the parameters which can be offloaded.
4585// This can be enhanced depending on the capability of the DSP and policy
4586// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004587audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004588{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004589 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004590 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004591 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004592 offloadInfo.format,
4593 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4594 offloadInfo.has_video);
4595
jiabin2b9d5a12021-12-10 01:06:29 +00004596 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004597 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004598 }
4599
4600 // See if there is a profile to support this.
4601 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004602 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004603 offloadInfo.sample_rate,
4604 offloadInfo.format,
4605 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004606 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4607 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004608 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4609 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4610 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004611 if (profile == nullptr) {
4612 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4613 }
4614 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4615 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4616 }
4617 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004618}
4619
Michael Chana94fbb22018-04-24 14:31:19 +10004620bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4621 const audio_attributes_t& attributes) {
4622 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004623 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004624 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4625 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004626 config.sample_rate,
4627 config.format,
4628 config.channel_mask,
4629 output_flags,
4630 true /* directOnly */);
4631 ALOGV("%s() profile %sfound with name: %s, "
4632 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4633 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004634 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004635 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004636
4637 // also try the MSD module if compatible profile not found
4638 if (profile == nullptr) {
4639 profile = getMsdProfileForOutput(outputDevices,
4640 config.sample_rate,
4641 config.format,
4642 config.channel_mask,
4643 output_flags,
4644 true /* directOnly */);
4645 ALOGV("%s() MSD profile %sfound with name: %s, "
4646 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4647 __FUNCTION__, profile != 0 ? "" : "NOT ",
4648 (profile != 0 ? profile->getTagName().c_str() : "null"),
4649 config.sample_rate, config.format, config.channel_mask, output_flags);
4650 }
4651 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004652}
4653
jiabin2b9d5a12021-12-10 01:06:29 +00004654bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4655 bool durationIgnored) {
4656 if (mMasterMono) {
4657 return false; // no offloading if mono is set.
4658 }
4659
4660 // Check if offload has been disabled
4661 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4662 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4663 return false;
4664 }
4665
4666 // Check if stream type is music, then only allow offload as of now.
4667 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4668 {
4669 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4670 return false;
4671 }
4672
4673 //TODO: enable audio offloading with video when ready
4674 const bool allowOffloadWithVideo =
4675 property_get_bool("audio.offload.video", false /* default_value */);
4676 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4677 ALOGV("%s: has_video == true, returning false", __func__);
4678 return false;
4679 }
4680
4681 //If duration is less than minimum value defined in property, return false
4682 const int min_duration_secs = property_get_int32(
4683 "audio.offload.min.duration.secs", -1 /* default_value */);
4684 if (!durationIgnored) {
4685 if (min_duration_secs >= 0) {
4686 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4687 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4688 __func__, min_duration_secs);
4689 return false;
4690 }
4691 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4692 ALOGV("%s: Offload denied by duration < default min(=%u)",
4693 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4694 return false;
4695 }
4696 }
4697
4698 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4699 // creating an offloaded track and tearing it down immediately after start when audioflinger
4700 // detects there is an active non offloadable effect.
4701 // FIXME: We should check the audio session here but we do not have it in this context.
4702 // This may prevent offloading in rare situations where effects are left active by apps
4703 // in the background.
4704 if (mEffects.isNonOffloadableEffectEnabled()) {
4705 return false;
4706 }
4707
4708 return true;
4709}
4710
4711audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4712 const audio_config_t *config) {
4713 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4714 offloadInfo.format = config->format;
4715 offloadInfo.sample_rate = config->sample_rate;
4716 offloadInfo.channel_mask = config->channel_mask;
4717 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4718 offloadInfo.has_video = false;
4719 offloadInfo.is_streaming = false;
4720 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4721
4722 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4723 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4724 audio_flags_to_audio_output_flags(attr->flags, &flags);
4725 // only retain flags that will drive compressed offload or passthrough
4726 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4727 if (offloadPossible) {
4728 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4729 }
4730 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4731
Dorin Drimusfae3c642022-03-17 18:36:30 +01004732 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004733 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004734 DeviceVector outputDevices = engineOutputDevices;
4735 // the MSD module checks for different conditions and output devices
4736 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4737 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4738 continue;
4739 }
4740 outputDevices = getMsdAudioOutDevices();
4741 }
jiabin2b9d5a12021-12-10 01:06:29 +00004742 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004743 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004744 config->sample_rate, nullptr /*updatedSamplingRate*/,
4745 config->format, nullptr /*updatedFormat*/,
4746 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004747 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004748 continue;
4749 }
4750 // reject profiles not corresponding to a device currently available
4751 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4752 continue;
4753 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004754 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4755 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004756 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004757 != AUDIO_DIRECT_NOT_SUPPORTED) {
4758 // Already reports offload gapless supported. No need to report offload support.
4759 continue;
4760 }
4761 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4762 != AUDIO_OUTPUT_FLAG_NONE) {
4763 // If offload gapless is reported, no need to report offload support.
4764 directMode = (audio_direct_mode_t) ((directMode &
4765 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4766 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4767 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004768 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004769 }
4770 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004771 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004772 }
4773 }
4774 }
4775 return directMode;
4776}
4777
Dorin Drimusf2196d82022-01-03 12:11:18 +01004778status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4779 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004780 if (mEffects.isNonOffloadableEffectEnabled()) {
4781 return OK;
4782 }
jiabinf1c73972022-04-14 16:28:52 -07004783 DeviceVector devices;
4784 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004785 if (status != OK) {
4786 return status;
4787 }
4788 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4789 if (devices.empty()) {
4790 return OK; // no output devices for the attributes
4791 }
jiabinf1c73972022-04-14 16:28:52 -07004792 return getProfilesForDevices(devices, audioProfilesVector,
4793 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004794}
4795
jiabina84c3d32022-12-02 18:59:55 +00004796status_t AudioPolicyManager::getSupportedMixerAttributes(
4797 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4798 ALOGV("%s, portId=%d", __func__, portId);
4799 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4800 if (deviceDescriptor == nullptr) {
4801 ALOGE("%s the requested device is currently unavailable", __func__);
4802 return BAD_VALUE;
4803 }
jiabin96daffc2023-05-11 17:51:55 +00004804 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4805 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4806 deviceDescriptor->type());
4807 return BAD_VALUE;
4808 }
jiabina84c3d32022-12-02 18:59:55 +00004809 for (const auto& hwModule : mHwModules) {
4810 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4811 if (curProfile->supportsDevice(deviceDescriptor)) {
4812 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4813 }
4814 }
4815 }
4816 return NO_ERROR;
4817}
4818
4819status_t AudioPolicyManager::setPreferredMixerAttributes(
4820 const audio_attributes_t *attr,
4821 audio_port_handle_t portId,
4822 uid_t uid,
4823 const audio_mixer_attributes_t *mixerAttributes) {
4824 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4825 "mixerBehavior=%d}, uid=%d, portId=%u",
4826 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4827 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4828 mixerAttributes->mixer_behavior, uid, portId);
4829 if (attr->usage != AUDIO_USAGE_MEDIA) {
4830 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4831 return BAD_VALUE;
4832 }
4833 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4834 if (deviceDescriptor == nullptr) {
4835 ALOGE("%s the requested device is currently unavailable", __func__);
4836 return BAD_VALUE;
4837 }
4838 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4839 ALOGE("%s(%d), type=%d, is not a usb output device",
4840 __func__, portId, deviceDescriptor->type());
4841 return BAD_VALUE;
4842 }
4843
4844 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4845 audio_flags_to_audio_output_flags(attr->flags, &flags);
4846 flags = (audio_output_flags_t) (flags |
4847 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4848 sp<IOProfile> profile = nullptr;
4849 DeviceVector devices(deviceDescriptor);
4850 for (const auto& hwModule : mHwModules) {
4851 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4852 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004853 && curProfile->getCompatibilityScore(
4854 devices,
4855 mixerAttributes->config.sample_rate,
4856 nullptr /*updatedSamplingRate*/,
4857 mixerAttributes->config.format,
4858 nullptr /*updatedFormat*/,
4859 mixerAttributes->config.channel_mask,
4860 nullptr /*updatedChannelMask*/,
4861 flags,
4862 false /*exactMatchRequiredForInputFlags*/)
4863 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004864 profile = curProfile;
4865 break;
4866 }
4867 }
4868 }
4869 if (profile == nullptr) {
4870 ALOGE("%s, there is no compatible profile found", __func__);
4871 return BAD_VALUE;
4872 }
4873
4874 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4875 sp<PreferredMixerAttributesInfo>::make(
4876 uid, portId, profile, flags, *mixerAttributes);
4877 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4878 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4879
4880 // If 1) there is any client from the preferred mixer configuration owner that is currently
4881 // active and matches the strategy and 2) current output is on the preferred device and the
4882 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4883 // configuration.
4884 std::vector<audio_io_handle_t> outputsToReopen;
4885 for (size_t i = 0; i < mOutputs.size(); i++) {
4886 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004887 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4888 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004889 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004890 } else {
4891 for (const auto &client: output->getActiveClients()) {
4892 if (client->uid() == uid && client->strategy() == strategy) {
4893 client->setIsInvalid();
4894 outputsToReopen.push_back(output->mIoHandle);
4895 }
jiabina84c3d32022-12-02 18:59:55 +00004896 }
4897 }
4898 }
4899 }
4900 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4901 config.sample_rate = mixerAttributes->config.sample_rate;
4902 config.channel_mask = mixerAttributes->config.channel_mask;
4903 config.format = mixerAttributes->config.format;
4904 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004905 sp<SwAudioOutputDescriptor> desc =
4906 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4907 if (desc == nullptr) {
4908 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4909 continue;
4910 }
jiabin220eea12024-05-17 17:55:20 +00004911 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004912 }
4913
4914 return NO_ERROR;
4915}
4916
4917sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004918 audio_port_handle_t devicePortId,
4919 product_strategy_t strategy,
4920 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004921 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4922 if (it == mPreferredMixerAttrInfos.end()) {
4923 return nullptr;
4924 }
jiabind9a58d32023-06-01 17:57:30 +00004925 if (activeBitPerfectPreferred) {
4926 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004927 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004928 return info;
4929 }
4930 }
jiabina84c3d32022-12-02 18:59:55 +00004931 }
jiabind9a58d32023-06-01 17:57:30 +00004932 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4933 return strategyMatchedMixerAttrInfoIt == it->second.end()
4934 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004935}
4936
4937status_t AudioPolicyManager::getPreferredMixerAttributes(
4938 const audio_attributes_t *attr,
4939 audio_port_handle_t portId,
4940 audio_mixer_attributes_t* mixerAttributes) {
4941 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4942 portId, mEngine->getProductStrategyForAttributes(*attr));
4943 if (info == nullptr) {
4944 return NAME_NOT_FOUND;
4945 }
4946 *mixerAttributes = info->getMixerAttributes();
4947 return NO_ERROR;
4948}
4949
4950status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4951 audio_port_handle_t portId,
4952 uid_t uid) {
4953 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4954 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4955 if (preferredMixerAttrInfo == nullptr) {
4956 return NAME_NOT_FOUND;
4957 }
4958 if (preferredMixerAttrInfo->getUid() != uid) {
4959 ALOGE("%s, requested uid=%d, owned uid=%d",
4960 __func__, uid, preferredMixerAttrInfo->getUid());
4961 return PERMISSION_DENIED;
4962 }
4963 mPreferredMixerAttrInfos[portId].erase(strategy);
4964 if (mPreferredMixerAttrInfos[portId].empty()) {
4965 mPreferredMixerAttrInfos.erase(portId);
4966 }
4967
4968 // Reconfig existing output
4969 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4970 for (size_t i = 0; i < mOutputs.size(); i++) {
4971 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4972 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4973 }
4974 }
4975 for (const auto output : potentialOutputsToReopen) {
4976 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4977 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4978 preferredMixerAttrInfo->getFlags())) {
4979 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4980 }
4981 }
4982 return NO_ERROR;
4983}
4984
Eric Laurent6a94d692014-05-20 11:18:06 -07004985status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4986 audio_port_type_t type,
4987 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004988 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004989 unsigned int *generation)
4990{
jiabin19cdba52020-11-24 11:28:58 -08004991 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4992 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004993 return BAD_VALUE;
4994 }
4995 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004996 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004997 *num_ports = 0;
4998 }
4999
5000 size_t portsWritten = 0;
5001 size_t portsMax = *num_ports;
5002 *num_ports = 0;
5003 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005004 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
5005 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07005006 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005007 for (const auto& dev : mAvailableOutputDevices) {
5008 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005009 continue;
5010 }
5011 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005012 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005013 }
5014 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005015 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 }
5017 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005018 for (const auto& dev : mAvailableInputDevices) {
5019 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005020 continue;
5021 }
5022 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005023 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005024 }
5025 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005026 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 }
5028 }
5029 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5030 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5031 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5032 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5033 }
5034 *num_ports += mInputs.size();
5035 }
5036 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005037 size_t numOutputs = 0;
5038 for (size_t i = 0; i < mOutputs.size(); i++) {
5039 if (!mOutputs[i]->isDuplicated()) {
5040 numOutputs++;
5041 if (portsWritten < portsMax) {
5042 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5043 }
5044 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005045 }
Eric Laurent84c70242014-06-23 08:46:27 -07005046 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005047 }
5048 }
jiabina84c3d32022-12-02 18:59:55 +00005049
Eric Laurent6a94d692014-05-20 11:18:06 -07005050 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005051 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005052 return NO_ERROR;
5053}
5054
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005055status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5056 std::vector<media::AudioPortFw>* _aidl_return) {
5057 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5058 audio_port_v7 port;
5059 dev->toAudioPort(&port);
5060 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5061 _aidl_return->push_back(std::move(aidlPort));
5062 return OK;
5063 };
5064
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005065 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005066 for (const auto& dev : module->getDeclaredDevices()) {
5067 if (role == media::AudioPortRole::NONE ||
5068 ((role == media::AudioPortRole::SOURCE)
5069 == audio_is_input_device(dev->type()))) {
5070 RETURN_STATUS_IF_ERROR(pushPort(dev));
5071 }
5072 }
5073 }
5074 return OK;
5075}
5076
jiabin19cdba52020-11-24 11:28:58 -08005077status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005078{
Eric Laurent99fcae42018-05-17 16:59:18 -07005079 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5080 return BAD_VALUE;
5081 }
5082 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5083 if (dev != 0) {
5084 dev->toAudioPort(port);
5085 return NO_ERROR;
5086 }
5087 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5088 if (dev != 0) {
5089 dev->toAudioPort(port);
5090 return NO_ERROR;
5091 }
5092 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5093 if (out != 0) {
5094 out->toAudioPort(port);
5095 return NO_ERROR;
5096 }
5097 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5098 if (in != 0) {
5099 in->toAudioPort(port);
5100 return NO_ERROR;
5101 }
5102 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005103}
5104
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005105status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5106 audio_patch_handle_t *handle,
5107 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005108{
François Gaffieafd4cea2019-11-18 15:50:22 +01005109 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005110 if (handle == NULL || patch == NULL) {
5111 return BAD_VALUE;
5112 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005113 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005114 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005115 return BAD_VALUE;
5116 }
5117 // only one source per audio patch supported for now
5118 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005119 return INVALID_OPERATION;
5120 }
Eric Laurent874c42872014-08-08 15:13:39 -07005121 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005122 return INVALID_OPERATION;
5123 }
Eric Laurent874c42872014-08-08 15:13:39 -07005124 for (size_t i = 0; i < patch->num_sinks; i++) {
5125 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5126 return INVALID_OPERATION;
5127 }
5128 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005129
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005130 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5131 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5132 if (srcDevice == nullptr || sinkDevice == nullptr) {
5133 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5134 return BAD_VALUE;
5135 }
5136 ALOGV("%s between source %s and sink %s", __func__,
5137 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5138 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5139 // Default attributes, default volume priority, not to infer with non raw audio patches.
5140 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5141 const struct audio_port_config *source = &patch->sources[0];
5142 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005143 new SourceClientDescriptor(
5144 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5145 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005146 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005147 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005148
5149 status_t status =
5150 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5151
5152 if (status != NO_ERROR) {
5153 return INVALID_OPERATION;
5154 }
5155 mAudioSources.add(portId, sourceDesc);
5156 return NO_ERROR;
5157}
5158
5159status_t AudioPolicyManager::connectAudioSourceToSink(
5160 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5161 const struct audio_patch *patch,
5162 audio_patch_handle_t &handle,
5163 uid_t uid, uint32_t delayMs)
5164{
5165 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5166 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5167 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5168 return INVALID_OPERATION;
5169 }
5170 sourceDesc->connect(handle, sinkDevice);
5171 if (isMsdPatch(handle)) {
5172 return NO_ERROR;
5173 }
5174 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5175 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5176 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5177 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5178 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5179 goto FailurePatchAdded;
5180 }
5181 status = swOutput->start();
5182 if (status != NO_ERROR) {
5183 goto FailureSourceAdded;
5184 }
5185 swOutput->addClient(sourceDesc);
5186 status = startSource(swOutput, sourceDesc, &delayMs);
5187 if (status != NO_ERROR) {
5188 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5189 goto FailureSourceActive;
5190 }
5191 if (delayMs != 0) {
5192 usleep(delayMs * 1000);
5193 }
5194 return NO_ERROR;
5195
5196FailureSourceActive:
5197 swOutput->stop();
5198 releaseOutput(sourceDesc->portId());
5199FailureSourceAdded:
5200 sourceDesc->setSwOutput(nullptr);
5201FailurePatchAdded:
5202 releaseAudioPatchInternal(handle);
5203 return INVALID_OPERATION;
5204}
5205
5206status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5207 audio_patch_handle_t *handle,
5208 uid_t uid, uint32_t delayMs,
5209 const sp<SourceClientDescriptor>& sourceDesc)
5210{
5211 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005212 sp<AudioPatch> patchDesc;
5213 ssize_t index = mAudioPatches.indexOfKey(*handle);
5214
François Gaffieafd4cea2019-11-18 15:50:22 +01005215 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5216 patch->sources[0].role,
5217 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005218#if LOG_NDEBUG == 0
5219 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005220 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5221 patch->sinks[i].role,
5222 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005223 }
5224#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005225
5226 if (index >= 0) {
5227 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005228 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5229 __func__, mUidCached, patchDesc->getUid(), uid);
5230 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 return INVALID_OPERATION;
5232 }
5233 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005234 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005235 }
5236
5237 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005238 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005239 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005240 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005241 return BAD_VALUE;
5242 }
Eric Laurent84c70242014-06-23 08:46:27 -07005243 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5244 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005245 if (patchDesc != 0) {
5246 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005247 ALOGV("%s source id differs for patch current id %d new id %d",
5248 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005249 return BAD_VALUE;
5250 }
5251 }
Eric Laurent874c42872014-08-08 15:13:39 -07005252 DeviceVector devices;
5253 for (size_t i = 0; i < patch->num_sinks; i++) {
5254 // Only support mix to devices connection
5255 // TODO add support for mix to mix connection
5256 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005257 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005258 return INVALID_OPERATION;
5259 }
5260 sp<DeviceDescriptor> devDesc =
5261 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5262 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005263 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005264 return BAD_VALUE;
5265 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005266
jiabin66acc432024-02-06 00:57:36 +00005267 if (outputDesc->mProfile->getCompatibilityScore(
5268 DeviceVector(devDesc),
5269 patch->sources[0].sample_rate,
5270 nullptr, // updatedSamplingRate
5271 patch->sources[0].format,
5272 nullptr, // updatedFormat
5273 patch->sources[0].channel_mask,
5274 nullptr, // updatedChannelMask
5275 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005276 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005277 return INVALID_OPERATION;
5278 }
5279 devices.add(devDesc);
5280 }
5281 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005282 return INVALID_OPERATION;
5283 }
Eric Laurent874c42872014-08-08 15:13:39 -07005284
Eric Laurent6a94d692014-05-20 11:18:06 -07005285 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005286 ALOGV("%s setting device %s on output %d",
5287 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305288 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005289 index = mAudioPatches.indexOfKey(*handle);
5290 if (index >= 0) {
5291 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005292 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005293 }
5294 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005295 patchDesc->setUid(uid);
5296 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005297 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005298 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005299 return INVALID_OPERATION;
5300 }
5301 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5302 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5303 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005304 // only one sink supported when connecting an input device to a mix
5305 if (patch->num_sinks > 1) {
5306 return INVALID_OPERATION;
5307 }
François Gaffie53615e22015-03-19 09:24:12 +01005308 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005309 if (inputDesc == NULL) {
5310 return BAD_VALUE;
5311 }
5312 if (patchDesc != 0) {
5313 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5314 return BAD_VALUE;
5315 }
5316 }
François Gaffie11d30102018-11-02 16:09:09 +01005317 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005318 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005319 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005320 return BAD_VALUE;
5321 }
5322
jiabin66acc432024-02-06 00:57:36 +00005323 if (inputDesc->mProfile->getCompatibilityScore(
5324 DeviceVector(device),
5325 patch->sinks[0].sample_rate,
5326 nullptr, /*updatedSampleRate*/
5327 patch->sinks[0].format,
5328 nullptr, /*updatedFormat*/
5329 patch->sinks[0].channel_mask,
5330 nullptr, /*updatedChannelMask*/
5331 // FIXME for the parameter type,
5332 // and the NONE
5333 (audio_output_flags_t)
5334 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005335 return INVALID_OPERATION;
5336 }
5337 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005338 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005339 device->toString().c_str(), inputDesc->mIoHandle);
5340 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005341 index = mAudioPatches.indexOfKey(*handle);
5342 if (index >= 0) {
5343 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005344 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005345 }
5346 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005347 patchDesc->setUid(uid);
5348 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005349 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005350 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005351 return INVALID_OPERATION;
5352 }
5353 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5354 // device to device connection
5355 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005356 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005357 return BAD_VALUE;
5358 }
5359 }
François Gaffie11d30102018-11-02 16:09:09 +01005360 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005361 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005362 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005363 return BAD_VALUE;
5364 }
Eric Laurent874c42872014-08-08 15:13:39 -07005365
Eric Laurent6a94d692014-05-20 11:18:06 -07005366 //update source and sink with our own data as the data passed in the patch may
5367 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005368 PatchBuilder patchBuilder;
5369 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005370
5371 // if first sink is to MSD, establish single MSD patch
5372 if (getMsdAudioOutDevices().contains(
5373 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5374 ALOGV("%s patching to MSD", __FUNCTION__);
5375 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5376 goto installPatch;
5377 }
5378
François Gaffieafd4cea2019-11-18 15:50:22 +01005379 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5380 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005381
Eric Laurent874c42872014-08-08 15:13:39 -07005382 for (size_t i = 0; i < patch->num_sinks; i++) {
5383 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005384 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005385 return INVALID_OPERATION;
5386 }
François Gaffie11d30102018-11-02 16:09:09 +01005387 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005388 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005389 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005390 return BAD_VALUE;
5391 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005392 audio_port_config sinkPortConfig = {};
5393 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5394 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005395
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005396 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5397 // volume management purpose (tracking activity)
5398 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5399 // in config XML to reach the sink so that is can be declared as available.
5400 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005401 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005402 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005403 // take care of dynamic routing for SwOutput selection,
5404 audio_attributes_t attributes = sourceDesc->attributes();
5405 audio_stream_type_t stream = sourceDesc->stream();
5406 audio_attributes_t resultAttr;
5407 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5408 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005409 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5410 config.channel_mask =
5411 (audio_channel_mask_get_representation(sourceMask)
5412 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5413 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005414 config.format = sourceDesc->config().format;
5415 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5416 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5417 bool isRequestedDeviceForExclusiveUse = false;
5418 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005419 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005420 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005421 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5422 &stream, sourceDesc->uid(), &config, &flags,
5423 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005424 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005425 if (output == AUDIO_IO_HANDLE_NONE) {
5426 ALOGV("%s no output for device %s",
5427 __FUNCTION__, sinkDevice->toString().c_str());
5428 return INVALID_OPERATION;
5429 }
5430 outputDesc = mOutputs.valueFor(output);
5431 if (outputDesc->isDuplicated()) {
5432 ALOGE("%s output is duplicated", __func__);
5433 return INVALID_OPERATION;
5434 }
François Gaffie7e39df22022-04-26 12:48:49 +02005435 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5436 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005437 } else {
5438 // Same for "raw patches" aka created from createAudioPatch API
5439 SortedVector<audio_io_handle_t> outputs =
5440 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5441 // if the sink device is reachable via an opened output stream, request to
5442 // go via this output stream by adding a second source to the patch
5443 // description
5444 output = selectOutput(outputs);
5445 if (output == AUDIO_IO_HANDLE_NONE) {
5446 ALOGE("%s no output available for internal patch sink", __func__);
5447 return INVALID_OPERATION;
5448 }
5449 outputDesc = mOutputs.valueFor(output);
5450 if (outputDesc->isDuplicated()) {
5451 ALOGV("%s output for device %s is duplicated",
5452 __func__, sinkDevice->toString().c_str());
5453 return INVALID_OPERATION;
5454 }
François Gaffie7e39df22022-04-26 12:48:49 +02005455 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005456 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005457 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005458 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005459 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005460 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005461 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5462 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005463 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5464 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005465 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005466 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005467 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005468 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005469 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005470 return INVALID_OPERATION;
5471 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005472 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005473 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005474 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005475 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005476 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005477 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurent963dbcc2024-06-20 12:34:15 +00005478 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005479 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5480 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005481 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005482 }
Eric Laurent83b88082014-06-20 18:31:16 -07005483 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005484 }
5485 // TODO: check from routing capabilities in config file and other conflicting patches
5486
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005487installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005488 status_t status = installPatch(
5489 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005490 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005491 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005492 return INVALID_OPERATION;
5493 }
5494 } else {
5495 return BAD_VALUE;
5496 }
5497 } else {
5498 return BAD_VALUE;
5499 }
5500 return NO_ERROR;
5501}
5502
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005503status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005504{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005505 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005506 ssize_t index = mAudioPatches.indexOfKey(handle);
5507
5508 if (index < 0) {
5509 return BAD_VALUE;
5510 }
5511 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005512 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5513 __func__, mUidCached, patchDesc->getUid(), uid);
5514 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005515 return INVALID_OPERATION;
5516 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005517 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5518 for (size_t i = 0; i < mAudioSources.size(); i++) {
5519 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5520 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5521 portId = sourceDesc->portId();
5522 break;
5523 }
5524 }
5525 return portId != AUDIO_PORT_HANDLE_NONE ?
5526 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005527}
Eric Laurent6a94d692014-05-20 11:18:06 -07005528
François Gaffieafd4cea2019-11-18 15:50:22 +01005529status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005530 uint32_t delayMs,
5531 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005532{
5533 ALOGV("%s patch %d", __func__, handle);
5534 if (mAudioPatches.indexOfKey(handle) < 0) {
5535 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5536 return BAD_VALUE;
5537 }
5538 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005539 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005540 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005541 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005542 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005543 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005544 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005545 return BAD_VALUE;
5546 }
5547
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305548 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005549 getNewOutputDevices(outputDesc, true /*fromCache*/),
5550 true,
5551 0,
5552 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005553 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5554 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005555 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005556 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005557 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005558 return BAD_VALUE;
5559 }
5560 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005561 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005562 true,
5563 NULL);
5564 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005565 status_t status =
5566 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5567 ALOGV("%s patch panel returned %d patchHandle %d",
5568 __func__, status, patchDesc->getAfHandle());
5569 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005570 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005571 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005572 // SW or HW Bridge
5573 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5574 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005575 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005576 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5577 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5578 outputDesc = sourceDesc->swOutput().promote();
5579 }
5580 if (outputDesc == nullptr) {
5581 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5582 // releaseOutput has already called closeOutput in case of direct output
5583 return NO_ERROR;
5584 }
François Gaffie7e39df22022-04-26 12:48:49 +02005585 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005586 // While using a HwBridge, force reconsidering device only if not reusing an existing
5587 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005588 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005589 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5590 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5591 // Reconsider device only for cases:
5592 // 1 / Active Output
5593 // 2 / Inactive Output previously hosting HwBridge
5594 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5595 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5596 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305597 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005598 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5599 outputDesc->devices(),
5600 force,
5601 0,
5602 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005603 } else {
5604 return BAD_VALUE;
5605 }
5606 } else {
5607 return BAD_VALUE;
5608 }
5609 return NO_ERROR;
5610}
5611
5612status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5613 struct audio_patch *patches,
5614 unsigned int *generation)
5615{
François Gaffie53615e22015-03-19 09:24:12 +01005616 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005617 return BAD_VALUE;
5618 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005619 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005620 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005621}
5622
Eric Laurente1715a42014-05-20 11:30:42 -07005623status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005624{
Eric Laurente1715a42014-05-20 11:30:42 -07005625 ALOGV("setAudioPortConfig()");
5626
5627 if (config == NULL) {
5628 return BAD_VALUE;
5629 }
5630 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5631 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005632 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5633 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005634 }
5635
Eric Laurenta121f902014-06-03 13:32:54 -07005636 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005637 if (config->type == AUDIO_PORT_TYPE_MIX) {
5638 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005639 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005640 if (outputDesc == NULL) {
5641 return BAD_VALUE;
5642 }
Eric Laurent84c70242014-06-23 08:46:27 -07005643 ALOG_ASSERT(!outputDesc->isDuplicated(),
5644 "setAudioPortConfig() called on duplicated output %d",
5645 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005646 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005647 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005648 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005649 if (inputDesc == NULL) {
5650 return BAD_VALUE;
5651 }
Eric Laurenta121f902014-06-03 13:32:54 -07005652 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005653 } else {
5654 return BAD_VALUE;
5655 }
5656 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5657 sp<DeviceDescriptor> deviceDesc;
5658 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5659 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5660 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5661 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5662 } else {
5663 return BAD_VALUE;
5664 }
5665 if (deviceDesc == NULL) {
5666 return BAD_VALUE;
5667 }
Eric Laurenta121f902014-06-03 13:32:54 -07005668 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005669 } else {
5670 return BAD_VALUE;
5671 }
5672
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005673 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005674 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5675 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005676 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005677 audioPortConfig->toAudioPortConfig(&newConfig, config);
5678 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005679 }
Eric Laurenta121f902014-06-03 13:32:54 -07005680 if (status != NO_ERROR) {
5681 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005682 }
Eric Laurente1715a42014-05-20 11:30:42 -07005683
5684 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005685}
5686
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005687void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5688{
Eric Laurentd60560a2015-04-10 11:31:20 -07005689 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005690 clearAudioPatches(uid);
5691 clearSessionRoutes(uid);
5692}
5693
Eric Laurent6a94d692014-05-20 11:18:06 -07005694void AudioPolicyManager::clearAudioPatches(uid_t uid)
5695{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005696 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005697 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005698 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005699 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005700 }
5701 }
5702}
5703
François Gaffiec005e562018-11-06 15:04:49 +01005704void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005705{
François Gaffiec005e562018-11-06 15:04:49 +01005706 // Take the first attributes following the product strategy as it is used to retrieve the routed
5707 // device. All attributes wihin a strategy follows the same "routing strategy"
5708 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5709 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005710 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005711 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005712 for (size_t j = 0; j < mOutputs.size(); j++) {
5713 if (mOutputs.keyAt(j) == ouptutToSkip) {
5714 continue;
5715 }
5716 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005717 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005718 continue;
5719 }
5720 // If the default device for this strategy is on another output mix,
5721 // invalidate all tracks in this strategy to force re connection.
5722 // Otherwise select new device on the output mix.
5723 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005724 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005725 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005726 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005727 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005728 // If the device is using preferred mixer attributes, the output need to reopen
5729 // with default configuration when the new selected devices are different from
5730 // current routing devices.
5731 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5732 continue;
5733 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305734 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005735 }
5736 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005737 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005738}
5739
5740void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5741{
5742 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005743 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005744 for (size_t i = 0; i < mOutputs.size(); i++) {
5745 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005746 for (const auto& client : outputDesc->getClientIterable()) {
5747 if (client->hasPreferredDevice() && client->uid() == uid) {
5748 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005749 auto clientStrategy = client->strategy();
5750 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5751 end(affectedStrategies)) {
5752 continue;
5753 }
5754 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005755 }
5756 }
5757 }
5758 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005759 for (const auto& strategy : affectedStrategies) {
5760 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005761 }
5762
5763 // remove input routes associated with this uid
5764 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005765 for (size_t i = 0; i < mInputs.size(); i++) {
5766 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005767 for (const auto& client : inputDesc->getClientIterable()) {
5768 if (client->hasPreferredDevice() && client->uid() == uid) {
5769 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5770 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005771 }
5772 }
5773 }
5774 // reroute inputs if necessary
5775 SortedVector<audio_io_handle_t> inputsToClose;
5776 for (size_t i = 0; i < mInputs.size(); i++) {
5777 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005778 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005779 inputsToClose.add(inputDesc->mIoHandle);
5780 }
5781 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005782 for (const auto& input : inputsToClose) {
5783 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005784 }
5785}
5786
Eric Laurentd60560a2015-04-10 11:31:20 -07005787void AudioPolicyManager::clearAudioSources(uid_t uid)
5788{
5789 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005790 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5791 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005792 stopAudioSource(mAudioSources.keyAt(i));
5793 }
5794 }
5795}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005796
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005797status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5798 audio_io_handle_t *ioHandle,
5799 audio_devices_t *device)
5800{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005801 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5802 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005803 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005804 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5805 if (deviceDesc == nullptr) {
5806 return INVALID_OPERATION;
5807 }
5808 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005809
François Gaffiedf372692015-03-19 10:43:27 +01005810 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005811}
5812
Eric Laurentd60560a2015-04-10 11:31:20 -07005813status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005814 const audio_attributes_t *attributes,
5815 audio_port_handle_t *portId,
Eric Laurent963dbcc2024-06-20 12:34:15 +00005816 uid_t uid) {
5817 return startAudioSourceInternal(source, attributes, portId, uid,
David Li48b6a832024-07-01 13:14:10 +00005818 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurent963dbcc2024-06-20 12:34:15 +00005819}
5820
5821status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5822 const audio_attributes_t *attributes,
5823 audio_port_handle_t *portId,
David Li48b6a832024-07-01 13:14:10 +00005824 uid_t uid, bool internal, bool isCallRx,
5825 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005826{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005827 ALOGV("%s", __FUNCTION__);
5828 *portId = AUDIO_PORT_HANDLE_NONE;
5829
5830 if (source == NULL || attributes == NULL || portId == NULL) {
5831 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5832 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005833 return BAD_VALUE;
5834 }
5835
Eric Laurentd60560a2015-04-10 11:31:20 -07005836 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5837 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005838 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5839 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005840 return INVALID_OPERATION;
5841 }
5842
François Gaffie11d30102018-11-02 16:09:09 +01005843 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005844 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005845 String8(source->ext.device.address),
5846 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005847 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005848 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005849 return BAD_VALUE;
5850 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005851
jiabin4ef93452019-09-10 14:29:54 -07005852 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005853
François Gaffieaaac0fd2018-11-22 17:56:39 +01005854 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005855 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005856 mEngine->getStreamTypeForAttributes(*attributes),
5857 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005858 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005859
David Li48b6a832024-07-01 13:14:10 +00005860 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005861 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005862 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005863 }
5864 return status;
5865}
5866
David Li48b6a832024-07-01 13:14:10 +00005867status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5868 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005869{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005870 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005871
5872 // make sure we only have one patch per source.
5873 disconnectAudioSource(sourceDesc);
5874
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005875 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005876 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5877 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5878 sourceDesc->srcDevice()->type(),
5879 String8(sourceDesc->srcDevice()->address().c_str()),
5880 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005881 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005882 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005883 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005884 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005885 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5886 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5887 return INVALID_OPERATION;
5888 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005889 PatchBuilder patchBuilder;
5890 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5891 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005892
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005893 return connectAudioSourceToSink(
David Li48b6a832024-07-01 13:14:10 +00005894 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005895}
5896
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005897status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005898{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005899 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5900 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005901 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005902 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005903 return BAD_VALUE;
5904 }
5905 status_t status = disconnectAudioSource(sourceDesc);
5906
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005907 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005908 return status;
5909}
5910
Andy Hung2ddee192015-12-18 17:34:44 -08005911status_t AudioPolicyManager::setMasterMono(bool mono)
5912{
5913 if (mMasterMono == mono) {
5914 return NO_ERROR;
5915 }
5916 mMasterMono = mono;
5917 // if enabling mono we close all offloaded devices, which will invalidate the
5918 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5919 // for recreating the new AudioTrack as non-offloaded PCM.
5920 //
5921 // If disabling mono, we leave all tracks as is: we don't know which clients
5922 // and tracks are able to be recreated as offloaded. The next "song" should
5923 // play back offloaded.
5924 if (mMasterMono) {
5925 Vector<audio_io_handle_t> offloaded;
5926 for (size_t i = 0; i < mOutputs.size(); ++i) {
5927 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5928 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5929 offloaded.push(desc->mIoHandle);
5930 }
5931 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005932 for (const auto& handle : offloaded) {
5933 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005934 }
5935 }
5936 // update master mono for all remaining outputs
5937 for (size_t i = 0; i < mOutputs.size(); ++i) {
5938 updateMono(mOutputs.keyAt(i));
5939 }
5940 return NO_ERROR;
5941}
5942
5943status_t AudioPolicyManager::getMasterMono(bool *mono)
5944{
5945 *mono = mMasterMono;
5946 return NO_ERROR;
5947}
5948
Eric Laurentac9cef52017-06-09 15:46:26 -07005949float AudioPolicyManager::getStreamVolumeDB(
5950 audio_stream_type_t stream, int index, audio_devices_t device)
5951{
jiabin9a3361e2019-10-01 09:38:30 -07005952 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005953}
5954
jiabin81772902018-04-02 17:52:27 -07005955status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5956 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005957 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005958{
Kriti Dang6537def2021-03-02 13:46:59 +01005959 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5960 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005961 return BAD_VALUE;
5962 }
Kriti Dang6537def2021-03-02 13:46:59 +01005963 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5964 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005965
5966 size_t formatsWritten = 0;
5967 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005968
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005969 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005970 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5971 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005972 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005973 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005974 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005975 bool formatEnabled = true;
5976 switch (forceUse) {
5977 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005978 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005979 break;
5980 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5981 formatEnabled = false;
5982 break;
5983 default: // AUTO or ALWAYS => true
5984 break;
jiabin81772902018-04-02 17:52:27 -07005985 }
5986 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5987 }
jiabin81772902018-04-02 17:52:27 -07005988 }
5989 return NO_ERROR;
5990}
5991
Kriti Dang6537def2021-03-02 13:46:59 +01005992status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5993 audio_format_t *surroundFormats) {
5994 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5995 return BAD_VALUE;
5996 }
5997 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5998 __func__, *numSurroundFormats, surroundFormats);
5999
6000 size_t formatsWritten = 0;
6001 size_t formatsMax = *numSurroundFormats;
6002 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
6003
6004 // Return formats from all device profiles that have already been resolved by
6005 // checkOutputsForDevice().
6006 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
6007 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
6008 audio_devices_t deviceType = device->type();
6009 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6010 // returns formats reported by HDMI devices.
hongchao.yinf0c82082024-07-24 19:41:02 +08006011 if (deviceType != AUDIO_DEVICE_OUT_HDMI &&
6012 deviceType != AUDIO_DEVICE_OUT_HDMI_ARC && deviceType != AUDIO_DEVICE_OUT_HDMI_EARC) {
Kriti Dang6537def2021-03-02 13:46:59 +01006013 continue;
6014 }
6015 // Formats reported by sink devices
6016 std::unordered_set<audio_format_t> formatset;
6017 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6018 formatset.insert(it->second.begin(), it->second.end());
6019 }
6020
6021 // Formats hard-coded in the in policy configuration file (if any).
6022 FormatVector encodedFormats = device->encodedFormats();
6023 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6024 // Filter the formats which are supported by the vendor hardware.
6025 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006026 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006027 formats.insert(*it);
6028 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006029 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006030 if (pair.second.count(*it) != 0) {
6031 formats.insert(pair.first);
6032 break;
6033 }
6034 }
6035 }
6036 }
6037 }
6038 *numSurroundFormats = formats.size();
6039 for (const auto& format: formats) {
6040 if (formatsWritten < formatsMax) {
6041 surroundFormats[formatsWritten++] = format;
6042 }
6043 }
6044 return NO_ERROR;
6045}
6046
jiabin81772902018-04-02 17:52:27 -07006047status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6048{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006049 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006050 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6051 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006052 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006053 return BAD_VALUE;
6054 }
6055
Mikhail Naganov100f0122018-11-29 11:22:16 -08006056 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6057 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006058 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006059 return INVALID_OPERATION;
6060 }
6061
Mikhail Naganov100f0122018-11-29 11:22:16 -08006062 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006063 return NO_ERROR;
6064 }
6065
Mikhail Naganov100f0122018-11-29 11:22:16 -08006066 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006067 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006068 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006069 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006070 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006071 }
6072 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006073 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006074 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006075 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006076 }
6077 }
6078
6079 sp<SwAudioOutputDescriptor> outputDesc;
6080 bool profileUpdated = false;
hongchao.yinf0c82082024-07-24 19:41:02 +08006081 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromTypes(
6082 {AUDIO_DEVICE_OUT_HDMI, AUDIO_DEVICE_OUT_HDMI_ARC, AUDIO_DEVICE_OUT_HDMI_EARC});
jiabin81772902018-04-02 17:52:27 -07006083 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6084 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006085 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006086 std::string name = hdmiOutputDevices[i]->getName();
hongchao.yinf0c82082024-07-24 19:41:02 +08006087 status_t status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006088 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6089 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006090 name.c_str(),
6091 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006092 if (status != NO_ERROR) {
6093 continue;
6094 }
hongchao.yinf0c82082024-07-24 19:41:02 +08006095 status = setDeviceConnectionStateInt(hdmiOutputDevices[i]->type(),
jiabin81772902018-04-02 17:52:27 -07006096 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6097 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006098 name.c_str(),
6099 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006100 profileUpdated |= (status == NO_ERROR);
6101 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006102 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006103 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006104 AUDIO_DEVICE_IN_HDMI);
6105 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6106 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006107 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006108 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006109 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6110 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6111 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006112 name.c_str(),
6113 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006114 if (status != NO_ERROR) {
6115 continue;
6116 }
6117 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6118 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6119 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006120 name.c_str(),
6121 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006122 profileUpdated |= (status == NO_ERROR);
6123 }
6124
jiabin81772902018-04-02 17:52:27 -07006125 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006126 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006127 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006128 }
6129
6130 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6131}
6132
Eric Laurent5ada82e2019-08-29 17:53:54 -07006133void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006134{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006135 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006136 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006137 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006138 }
6139}
6140
jiabin6012f912018-11-02 17:06:30 -07006141bool AudioPolicyManager::isHapticPlaybackSupported()
6142{
6143 for (const auto& hwModule : mHwModules) {
6144 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6145 for (const auto &outProfile : outputProfiles) {
6146 struct audio_port audioPort;
6147 outProfile->toAudioPort(&audioPort);
6148 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6149 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6150 return true;
6151 }
6152 }
6153 }
6154 }
6155 return false;
6156}
6157
Carter Hsu325a8eb2022-01-19 19:56:51 +08006158bool AudioPolicyManager::isUltrasoundSupported()
6159{
6160 bool hasUltrasoundOutput = false;
6161 bool hasUltrasoundInput = false;
6162 for (const auto& hwModule : mHwModules) {
6163 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6164 if (!hasUltrasoundOutput) {
6165 for (const auto &outProfile : outputProfiles) {
6166 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6167 hasUltrasoundOutput = true;
6168 break;
6169 }
6170 }
6171 }
6172
6173 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6174 if (!hasUltrasoundInput) {
6175 for (const auto &inputProfile : inputProfiles) {
6176 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6177 hasUltrasoundInput = true;
6178 break;
6179 }
6180 }
6181 }
6182
6183 if (hasUltrasoundOutput && hasUltrasoundInput)
6184 return true;
6185 }
6186 return false;
6187}
6188
Atneya Nair698f5ef2022-12-15 16:15:09 -08006189bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6190{
6191 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6192 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6193 for (const auto& hwModule : mHwModules) {
6194 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6195 for (const auto &inputProfile : inputProfiles) {
6196 if ((inputProfile->getFlags() & mask) == mask) {
6197 return true;
6198 }
6199 }
6200 }
6201 return false;
6202}
6203
Eric Laurent8340e672019-11-06 11:01:08 -08006204bool AudioPolicyManager::isCallScreenModeSupported()
6205{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006206 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006207}
6208
6209
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006210status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006211{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006212 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006213 if (!sourceDesc->isConnected()) {
6214 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6215 return NO_ERROR;
6216 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006217 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6218 if (swOutput != 0) {
6219 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006220 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006221 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006222 }
jiabinbce0c1d2020-10-05 11:20:18 -07006223 if (releaseOutput(sourceDesc->portId())) {
6224 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6225 // no need to release audio patch here but just return NO_ERROR.
6226 return NO_ERROR;
6227 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006228 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006229 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006230 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006231 // close Hwoutput and remove from mHwOutputs
6232 } else {
6233 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6234 }
6235 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006236 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006237 sourceDesc->disconnect();
6238 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006239}
6240
François Gaffiec005e562018-11-06 15:04:49 +01006241sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6242 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006243{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006244 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006245 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006246 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006247 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006248 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6249 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006250 source = sourceDesc;
6251 break;
6252 }
6253 }
6254 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006255}
6256
Eric Laurentb4f42a92022-01-17 17:37:31 +01006257bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006258 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006259 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006260{
6261 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6262 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006263 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006264 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006265 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6266 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6267 return false;
6268 }
6269 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6270 return false;
6271 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006272 }
6273
Eric Laurentd332bc82023-08-04 11:45:23 +02006274 // The caller can have the audio config criteria ignored by either passing a null ptr or
6275 // the AUDIO_CONFIG_INITIALIZER value.
6276 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006277 // some positional channel masks and PCM format and for stereo if low latency performance
6278 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006279
6280 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006281 static const bool stereo_spatialization_enabled =
6282 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006283 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006284 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006285 ? audio_channel_mask_contains_stereo(config->channel_mask)
6286 : audio_is_channel_mask_spatialized(config->channel_mask);
6287 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006288 return false;
6289 }
6290 if (!audio_is_linear_pcm(config->format)) {
6291 return false;
6292 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006293 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6294 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6295 return false;
6296 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006297 }
6298
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006299 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006300 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006301 if (profile == nullptr) {
6302 return false;
6303 }
6304
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006305 return true;
6306}
6307
Shunkai Yao57b93392024-04-26 04:12:21 +00006308// The Spatializer output is compatible with Haptic use cases if:
6309// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6310// with client if client haptic channel bits were set, or
6311// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6312// including the haptic bits or creating the HapticGenerator effect for same session.
6313bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6314 const audio_config_t* config, audio_session_t sessionId) const {
6315 const auto clientHapticChannel =
6316 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6317 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6318 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6319
6320 if (threadOutputHapticChannel) {
6321 // check format and sampleRate match if client haptic channel mask exist
6322 if (clientHapticChannel) {
6323 return mSpatializerOutput->getFormat() == config->format &&
6324 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6325 }
6326 return true;
6327 } else {
6328 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6329 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6330 // HapticGenerator effect for this session) are not supported.
6331 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006332 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao57b93392024-04-26 04:12:21 +00006333 }
6334}
6335
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006336void AudioPolicyManager::checkVirtualizerClientRoutes() {
6337 std::set<audio_stream_type_t> streamsToInvalidate;
6338 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006339 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6340 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006341 audio_attributes_t attr = client->attributes();
6342 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6343 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6344 audio_config_base_t clientConfig = client->config();
6345 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006346 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006347 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006348 streamsToInvalidate.insert(client->stream());
6349 }
6350 }
6351 }
6352
jiabinc44b3462022-12-08 12:52:31 -08006353 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006354}
6355
Eric Laurente191d1b2022-04-15 11:59:25 +02006356
6357bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6358 const sp<SwAudioOutputDescriptor>& outputDesc) {
6359 if (outputDesc->isDuplicated()) {
6360 return false;
6361 }
6362 DeviceVector devices = outputDesc->supportedDevices();
6363 for (size_t i = 0; i < mOutputs.size(); i++) {
6364 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6365 if (desc == outputDesc || desc->isDuplicated()) {
6366 continue;
6367 }
6368 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6369 if (!sharedDevices.isEmpty()
6370 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6371 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6372 return false;
6373 }
6374 }
6375 return true;
6376}
6377
6378
Eric Laurentfa0f6742021-08-17 18:39:44 +02006379status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006380 const audio_attributes_t *attr,
6381 audio_io_handle_t *output) {
6382 *output = AUDIO_IO_HANDLE_NONE;
6383
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006384 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6385 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6386 audio_config_t *configPtr = nullptr;
6387 audio_config_t config;
6388 if (mixerConfig != nullptr) {
6389 config = audio_config_initializer(mixerConfig);
6390 configPtr = &config;
6391 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006392 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006393 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006394 return BAD_VALUE;
6395 }
6396
6397 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006398 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006399 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006400 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006401 return BAD_VALUE;
6402 }
6403
Eric Laurente191d1b2022-04-15 11:59:25 +02006404 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006405 for (size_t i = 0; i < mOutputs.size(); i++) {
6406 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006407 if (!desc->isDuplicated()
6408 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6409 spatializerOutputs.push_back(desc);
6410 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006411 }
6412 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006413 mSpatializerOutput.clear();
6414 bool outputsChanged = false;
6415 for (const auto& desc : spatializerOutputs) {
6416 if (desc->mProfile == profile
6417 && (configPtr == nullptr
6418 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6419 mSpatializerOutput = desc;
6420 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6421 } else {
6422 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6423 " and devices %s", __func__, desc->mIoHandle,
6424 configPtr != nullptr ? configPtr->channel_mask : 0,
6425 devices.toString().c_str());
6426 closeOutput(desc->mIoHandle);
6427 outputsChanged = true;
6428 }
Eric Laurent39095982021-08-24 18:29:27 +02006429 }
6430
Eric Laurente191d1b2022-04-15 11:59:25 +02006431 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006432 sp<SwAudioOutputDescriptor> desc =
6433 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006434 if (desc != nullptr) {
6435 mSpatializerOutput = desc;
6436 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006437 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006438 }
6439
6440 checkVirtualizerClientRoutes();
6441
Eric Laurente191d1b2022-04-15 11:59:25 +02006442 if (outputsChanged) {
6443 mPreviousOutputs = mOutputs;
6444 mpClientInterface->onAudioPortListUpdate();
6445 }
6446
6447 if (mSpatializerOutput == nullptr) {
6448 ALOGV("%s could not open spatializer output with requested config", __func__);
6449 return BAD_VALUE;
6450 }
Eric Laurent39095982021-08-24 18:29:27 +02006451 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006452 ALOGV("%s returning new spatializer output %d", __func__, *output);
6453 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006454}
6455
Eric Laurentfa0f6742021-08-17 18:39:44 +02006456status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6457 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006458 return INVALID_OPERATION;
6459 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006460 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006461 return BAD_VALUE;
6462 }
Eric Laurent39095982021-08-24 18:29:27 +02006463
Eric Laurente191d1b2022-04-15 11:59:25 +02006464 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6465 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6466 closeOutput(mSpatializerOutput->mIoHandle);
6467 //from now on mSpatializerOutput is null
6468 checkVirtualizerClientRoutes();
6469 }
Eric Laurent39095982021-08-24 18:29:27 +02006470
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006471 return NO_ERROR;
6472}
6473
Eric Laurente552edb2014-03-10 17:42:56 -07006474// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006475// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006476// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006477uint32_t AudioPolicyManager::nextAudioPortGeneration()
6478{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006479 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006480}
6481
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006482AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006483 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006484 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006485 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006486 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006487 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006488 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006489 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006490 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006491 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006492 mAudioPortGeneration(1),
6493 mBeaconMuteRefCount(0),
6494 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006495 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006496 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006497 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006498 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006499{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006500}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006501
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006502status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006503 if (mEngine == nullptr) {
6504 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006505 }
6506 mEngine->setObserver(this);
6507 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006508 if (status != NO_ERROR) {
6509 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6510 return status;
6511 }
François Gaffie2110e042015-03-24 08:41:51 +01006512
jiabin29230182023-04-04 21:02:36 +00006513 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6514 // at the end of this function.
6515 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006516 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6517 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6518
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006519 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006520 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006521 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006522
Eric Laurent3a4311c2014-03-17 12:00:47 -07006523 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006524 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6525 defaultOutputDevice == nullptr ||
6526 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6527 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6528 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006529 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006530 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006531 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006532
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006533 // Silence ALOGV statements
6534 property_set("log.tag." LOG_TAG, "D");
6535
Eric Laurente552edb2014-03-10 17:42:56 -07006536 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006537 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006538}
6539
Eric Laurente0720872014-03-11 09:30:41 -07006540AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006541{
Eric Laurente552edb2014-03-10 17:42:56 -07006542 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006543 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006544 }
6545 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006546 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006547 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006548 mAvailableOutputDevices.clear();
6549 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006550 mOutputs.clear();
6551 mInputs.clear();
6552 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006553 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006554 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006555}
6556
Eric Laurente0720872014-03-11 09:30:41 -07006557status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006558{
Eric Laurent87ffa392015-05-22 10:32:38 -07006559 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006560}
6561
Eric Laurente552edb2014-03-10 17:42:56 -07006562// ---
6563
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006564void AudioPolicyManager::onNewAudioModulesAvailable()
6565{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006566 DeviceVector newDevices;
6567 onNewAudioModulesAvailableInt(&newDevices);
6568 if (!newDevices.empty()) {
6569 nextAudioPortGeneration();
6570 mpClientInterface->onAudioPortListUpdate();
6571 }
6572}
6573
6574void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6575{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006576 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006577 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6578 continue;
6579 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006580 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006581 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6582 handle != AUDIO_MODULE_HANDLE_NONE) {
6583 hwModule->setHandle(handle);
6584 } else {
6585 ALOGW("could not load HW module %s", hwModule->getName());
6586 continue;
6587 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006588 }
6589 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006590 // open all output streams needed to access attached devices.
6591 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006592 // This also validates mAvailableOutputDevices list
6593 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6594 if (!outProfile->canOpenNewIo()) {
6595 ALOGE("Invalid Output profile max open count %u for profile %s",
6596 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6597 continue;
6598 }
6599 if (!outProfile->hasSupportedDevices()) {
6600 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6601 continue;
6602 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006603 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6604 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006605 mTtsOutputAvailable = true;
6606 }
6607
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006608 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006609 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006610 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006611 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6612 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006613 } else {
6614 // choose first device present in profile's SupportedDevices also part of
6615 // mAvailableOutputDevices.
6616 if (availProfileDevices.isEmpty()) {
6617 continue;
6618 }
6619 supportedDevice = availProfileDevices.itemAt(0);
6620 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006621 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006622 continue;
6623 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306624
6625 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6626 && availProfileDevices.areAllDevicesAttached()) {
6627 ALOGV("%s skip opening output for mmap profile %s", __func__,
6628 outProfile->getTagName().c_str());
6629 continue;
6630 }
6631
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006632 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6633 mpClientInterface);
6634 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006635 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006636 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006637 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6638 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006639 AUDIO_STREAM_DEFAULT,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11006640 &flags, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006641 if (status != NO_ERROR) {
6642 ALOGW("Cannot open output stream for devices %s on hw module %s",
6643 supportedDevice->toString().c_str(), hwModule->getName());
6644 continue;
6645 }
6646 for (const auto &device : availProfileDevices) {
6647 // give a valid ID to an attached device once confirmed it is reachable
6648 if (!device->isAttached()) {
6649 device->attach(hwModule);
6650 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006651 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006652 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006653 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6654 }
6655 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006656 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006657 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6658 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006659 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006660 }
Eric Laurent39095982021-08-24 18:29:27 +02006661 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006662 outputDesc->close();
6663 } else {
6664 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306665 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006666 DeviceVector(supportedDevice),
6667 true,
6668 0,
6669 NULL);
6670 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006671 }
6672 // open input streams needed to access attached devices to validate
6673 // mAvailableInputDevices list
6674 for (const auto& inProfile : hwModule->getInputProfiles()) {
6675 if (!inProfile->canOpenNewIo()) {
6676 ALOGE("Invalid Input profile max open count %u for profile %s",
6677 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6678 continue;
6679 }
6680 if (!inProfile->hasSupportedDevices()) {
6681 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6682 continue;
6683 }
6684 // chose first device present in profile's SupportedDevices also part of
6685 // available input devices
6686 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006687 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006688 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006689 ALOGV("%s: Input device list is empty! for profile %s",
6690 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006691 continue;
6692 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306693
6694 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6695 && availProfileDevices.areAllDevicesAttached()) {
6696 ALOGV("%s skip opening input for mmap profile %s", __func__,
6697 inProfile->getTagName().c_str());
6698 continue;
6699 }
6700
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006701 sp<AudioInputDescriptor> inputDesc =
6702 new AudioInputDescriptor(inProfile, mpClientInterface);
6703
6704 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6705 status_t status = inputDesc->open(nullptr,
6706 availProfileDevices.itemAt(0),
6707 AUDIO_SOURCE_MIC,
Mikhail Naganov08816472024-07-18 16:01:54 +00006708 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006709 &input);
6710 if (status != NO_ERROR) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306711 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6712 __func__, availProfileDevices.toString().c_str(),
6713 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006714 continue;
6715 }
6716 for (const auto &device : availProfileDevices) {
6717 // give a valid ID to an attached device once confirmed it is reachable
6718 if (!device->isAttached()) {
6719 device->attach(hwModule);
6720 device->importAudioPortAndPickAudioProfile(inProfile, true);
6721 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006722 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006723 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6724 }
6725 }
6726 inputDesc->close();
6727 }
6728 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006729
6730 // Check if spatializer outputs can be closed until used.
6731 // mOutputs vector never contains duplicated outputs at this point.
6732 std::vector<audio_io_handle_t> outputsClosed;
6733 for (size_t i = 0; i < mOutputs.size(); i++) {
6734 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6735 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6736 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6737 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006738 nextAudioPortGeneration();
6739 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6740 if (index >= 0) {
6741 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6742 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6743 patchDesc->getAfHandle(), 0);
6744 mAudioPatches.removeItemsAt(index);
6745 mpClientInterface->onAudioPatchListUpdate();
6746 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006747 desc->close();
6748 }
6749 }
6750 for (auto output : outputsClosed) {
6751 removeOutput(output);
6752 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006753}
6754
Eric Laurent98e38192018-02-15 18:31:53 -08006755void AudioPolicyManager::addOutput(audio_io_handle_t output,
6756 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006757{
Eric Laurent1c333e22014-05-20 10:48:17 -07006758 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006759 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006760 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006761 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006762 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006763}
6764
François Gaffie53615e22015-03-19 09:24:12 +01006765void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6766{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006767 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6768 ALOGV("%s: removing primary output", __func__);
6769 mPrimaryOutput = nullptr;
6770 }
François Gaffie53615e22015-03-19 09:24:12 +01006771 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006772 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006773}
6774
Eric Laurent98e38192018-02-15 18:31:53 -08006775void AudioPolicyManager::addInput(audio_io_handle_t input,
6776 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006777{
Eric Laurent1c333e22014-05-20 10:48:17 -07006778 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006779 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006780}
Eric Laurente552edb2014-03-10 17:42:56 -07006781
François Gaffie11d30102018-11-02 16:09:09 +01006782status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006783 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006784 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006785{
François Gaffie11d30102018-11-02 16:09:09 +01006786 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006787 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006788 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006789
François Gaffie11d30102018-11-02 16:09:09 +01006790 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006791 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006792 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006793 }
Eric Laurente552edb2014-03-10 17:42:56 -07006794
Eric Laurent3b73df72014-03-11 09:06:29 -07006795 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006796 // first call getAudioPort to get the supported attributes from the HAL
6797 struct audio_port_v7 port = {};
6798 device->toAudioPort(&port);
6799 status_t status = mpClientInterface->getAudioPort(&port);
6800 if (status == NO_ERROR) {
6801 device->importAudioPort(port);
6802 }
6803
6804 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006805 for (size_t i = 0; i < mOutputs.size(); i++) {
6806 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006807 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006808 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006809 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6810 mOutputs.keyAt(i), device->toString().c_str());
6811 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006812 }
6813 }
6814 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006815 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006816 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006817 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6818 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006819 if (profile->supportsDevice(device)) {
6820 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306821 ALOGV("%s(): adding profile %s from module %s",
6822 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006823 }
6824 }
6825 }
6826
Eric Laurent7b279bb2015-12-14 10:18:23 -08006827 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006828
Eric Laurente552edb2014-03-10 17:42:56 -07006829 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006830 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006831 return BAD_VALUE;
6832 }
6833
6834 // open outputs for matching profiles if needed. Direct outputs are also opened to
6835 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6836 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006837 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006838
6839 // nothing to do if one output is already opened for this profile
6840 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006841 for (j = 0; j < outputs.size(); j++) {
6842 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006843 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006844 // matching profile: save the sample rates, format and channel masks supported
6845 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006846 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006847 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006848 }
Eric Laurente552edb2014-03-10 17:42:56 -07006849 break;
6850 }
6851 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006852 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006853 continue;
6854 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306855 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6856 ALOGV("%s skip opening output for mmap profile %s",
6857 __func__, profile->getTagName().c_str());
6858 continue;
6859 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006860 if (!profile->canOpenNewIo()) {
6861 ALOGW("Max Output number %u already opened for this profile %s",
6862 profile->maxOpenCount, profile->getTagName().c_str());
6863 continue;
6864 }
6865
Eric Laurent83efe1c2017-07-09 16:51:08 -07006866 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006867 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006868 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6869 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006870 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006871 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006872 profiles.removeAt(profile_index);
6873 profile_index--;
6874 } else {
6875 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006876 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006877 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006878 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6879 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006880 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006881 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006882
François Gaffie11d30102018-11-02 16:09:09 +01006883 if (device_distinguishes_on_address(deviceType)) {
6884 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6885 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306886 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6887 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006888 }
Eric Laurente552edb2014-03-10 17:42:56 -07006889 ALOGV("checkOutputsForDevice(): adding output %d", output);
6890 }
6891 }
6892
6893 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006894 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006895 return BAD_VALUE;
6896 }
Eric Laurentd4692962014-05-05 18:13:44 -07006897 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006898 // check if one opened output is not needed any more after disconnecting one device
6899 for (size_t i = 0; i < mOutputs.size(); i++) {
6900 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006901 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006902 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006903 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006904 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006905 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006906 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006907 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6908 mOutputs.keyAt(i));
6909 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006910 }
Eric Laurente552edb2014-03-10 17:42:56 -07006911 }
6912 }
Eric Laurentd4692962014-05-05 18:13:44 -07006913 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006914 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006915 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6916 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006917 if (!profile->supportsDevice(device)) {
6918 continue;
6919 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306920 ALOGV("%s(): clearing direct output profile %s on module %s",
6921 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07006922 profile->clearAudioProfiles();
6923 if (!profile->hasDynamicAudioProfile()) {
6924 continue;
6925 }
6926 // When a device is disconnected, if there is an IOProfile that contains dynamic
6927 // profiles and supports the disconnected device, call getAudioPort to repopulate
6928 // the capabilities of the devices that is supported by the IOProfile.
6929 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6930 if (supportedDevice == device ||
6931 !mAvailableOutputDevices.contains(supportedDevice)) {
6932 continue;
6933 }
6934 struct audio_port_v7 port;
6935 supportedDevice->toAudioPort(&port);
6936 status_t status = mpClientInterface->getAudioPort(&port);
6937 if (status == NO_ERROR) {
6938 supportedDevice->importAudioPort(port);
6939 }
Eric Laurente552edb2014-03-10 17:42:56 -07006940 }
6941 }
6942 }
6943 }
6944 return NO_ERROR;
6945}
6946
François Gaffie11d30102018-11-02 16:09:09 +01006947status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006948 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006949{
François Gaffie11d30102018-11-02 16:09:09 +01006950 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006951 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006952 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006953 }
6954
Eric Laurentd4692962014-05-05 18:13:44 -07006955 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006956 sp<AudioInputDescriptor> desc;
6957
jiabinbf5f4262023-04-12 21:48:34 +00006958 // first call getAudioPort to get the supported attributes from the HAL
6959 struct audio_port_v7 port = {};
6960 device->toAudioPort(&port);
6961 status_t status = mpClientInterface->getAudioPort(&port);
6962 if (status == NO_ERROR) {
6963 device->importAudioPort(port);
6964 }
6965
Eric Laurent0dd51852019-04-19 18:18:58 -07006966 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006967 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006968 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006969 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006970 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006971 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006972 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006973
François Gaffie11d30102018-11-02 16:09:09 +01006974 if (profile->supportsDevice(device)) {
6975 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306976 ALOGV("%s : adding profile %s from module %s", __func__,
6977 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006978 }
6979 }
6980 }
6981
Eric Laurent0dd51852019-04-19 18:18:58 -07006982 if (profiles.isEmpty()) {
6983 ALOGW("%s: No input profile available for device %s",
6984 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006985 return BAD_VALUE;
6986 }
6987
6988 // open inputs for matching profiles if needed. Direct inputs are also opened to
6989 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6990 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6991
Eric Laurent1c333e22014-05-20 10:48:17 -07006992 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006993
Eric Laurentd4692962014-05-05 18:13:44 -07006994 // nothing to do if one input is already opened for this profile
6995 size_t input_index;
6996 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6997 desc = mInputs.valueAt(input_index);
6998 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006999 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007000 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007001 }
Eric Laurentd4692962014-05-05 18:13:44 -07007002 break;
7003 }
7004 }
7005 if (input_index != mInputs.size()) {
7006 continue;
7007 }
7008
Jaideep Sharma44824a22024-06-18 16:32:34 +05307009 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
7010 ALOGV("%s skip opening input for mmap profile %s",
7011 __func__, profile->getTagName().c_str());
7012 continue;
7013 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007014 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307015 ALOGW("%s Max Input number %u already opened for this profile %s",
7016 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007017 continue;
7018 }
7019
Eric Laurentfe231122017-11-17 17:48:06 -08007020 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007021 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307022 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Mikhail Naganov08816472024-07-18 16:01:54 +00007023 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7024 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007025
Eric Laurentcf2c0212014-07-25 16:20:43 -07007026 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007027 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007028 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007029 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007030 mpClientInterface->setParameters(input, String8(param));
7031 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007032 }
jiabin12537fc2023-10-12 17:56:08 +00007033 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007034 if (!profile->hasValidAudioProfile()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307035 ALOGW("%s direct input missing param for profile %s", __func__,
7036 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007037 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007038 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007039 }
7040
Eric Laurent0dd51852019-04-19 18:18:58 -07007041 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007042 addInput(input, desc);
7043 }
7044 } // endif input != 0
7045
Eric Laurentcf2c0212014-07-25 16:20:43 -07007046 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307047 ALOGW("%s could not open input for device %s on profile %s", __func__,
7048 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007049 profiles.removeAt(profile_index);
7050 profile_index--;
7051 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007052 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007053 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007054 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307055 ALOGV("%s: adding input %d for profile %s", __func__,
7056 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007057
7058 if (checkCloseInput(desc)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307059 ALOGV("%s: closing input %d for profile %s", __func__,
7060 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007061 closeInput(input);
7062 }
Eric Laurentd4692962014-05-05 18:13:44 -07007063 }
7064 } // end scan profiles
7065
7066 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007067 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007068 return BAD_VALUE;
7069 }
7070 } else {
7071 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007072 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007073 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007074 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007075 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007076 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007077 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007078 if (profile->supportsDevice(device)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307079 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7080 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007081 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007082 }
7083 }
7084 }
7085 } // end disconnect
7086
7087 return NO_ERROR;
7088}
7089
7090
Eric Laurente0720872014-03-11 09:30:41 -07007091void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007092{
7093 ALOGV("closeOutput(%d)", output);
7094
François Gaffie1c878552018-11-22 16:53:21 +01007095 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7096 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007097 ALOGW("closeOutput() unknown output %d", output);
7098 return;
7099 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007100 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007101 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007102
Eric Laurente552edb2014-03-10 17:42:56 -07007103 // look for duplicated outputs connected to the output being removed.
7104 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007105 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7106 if (dupOutput->isDuplicated() &&
7107 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7108 sp<SwAudioOutputDescriptor> remainingOutput =
7109 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007110 // As all active tracks on duplicated output will be deleted,
7111 // and as they were also referenced on the other output, the reference
7112 // count for their stream type must be adjusted accordingly on
7113 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007114 const bool wasActive = remainingOutput->isActive();
7115 // Note: no-op on the closing output where all clients has already been set inactive
7116 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007117 // stop() will be a no op if the output is still active but is needed in case all
7118 // active streams refcounts where cleared above
7119 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007120 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007121 }
Eric Laurente552edb2014-03-10 17:42:56 -07007122 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7123 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7124
7125 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007126 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007127 }
7128 }
7129
Eric Laurent05b90f82014-08-27 15:32:29 -07007130 nextAudioPortGeneration();
7131
François Gaffie1c878552018-11-22 16:53:21 +01007132 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007133 if (index >= 0) {
7134 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007135 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7136 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007137 mAudioPatches.removeItemsAt(index);
7138 mpClientInterface->onAudioPatchListUpdate();
7139 }
7140
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007141 if (closingOutputWasActive) {
7142 closingOutput->stop();
7143 }
François Gaffie1c878552018-11-22 16:53:21 +01007144 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007145 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007146 for (const auto device : closingOutput->devices()) {
7147 device->setPreferredConfig(nullptr);
7148 }
7149 }
Eric Laurente552edb2014-03-10 17:42:56 -07007150
François Gaffie53615e22015-03-19 09:24:12 +01007151 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007152 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007153 if (closingOutput == mSpatializerOutput) {
7154 mSpatializerOutput.clear();
7155 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007156
7157 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7158 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007159 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007160 bool directOutputOpen = false;
7161 for (size_t i = 0; i < mOutputs.size(); i++) {
7162 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7163 directOutputOpen = true;
7164 break;
7165 }
7166 }
7167 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007168 ALOGV("no direct outputs open, reset MSD patches");
7169 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7170 // how output devices for patching are resolved. Avoid by caching and reusing the
7171 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7172 // devices to patch to. This may be complicated by the fact that devices may become
7173 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007174 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007175 }
7176 }
jiabin220eea12024-05-17 17:55:20 +00007177
7178 if (closingOutput->mPreferredAttrInfo != nullptr) {
7179 closingOutput->mPreferredAttrInfo->resetActiveClient();
7180 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007181}
7182
7183void AudioPolicyManager::closeInput(audio_io_handle_t input)
7184{
7185 ALOGV("closeInput(%d)", input);
7186
7187 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7188 if (inputDesc == NULL) {
7189 ALOGW("closeInput() unknown input %d", input);
7190 return;
7191 }
7192
Eric Laurent6a94d692014-05-20 11:18:06 -07007193 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007194
François Gaffie11d30102018-11-02 16:09:09 +01007195 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007196 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007197 if (index >= 0) {
7198 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007199 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7200 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007201 mAudioPatches.removeItemsAt(index);
7202 mpClientInterface->onAudioPatchListUpdate();
7203 }
7204
François Gaffie6ebbce02023-07-19 13:27:53 +02007205 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007206 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007207 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007208
François Gaffie11d30102018-11-02 16:09:09 +01007209 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7210 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007211 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007212 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007213 }
Eric Laurente552edb2014-03-10 17:42:56 -07007214}
7215
François Gaffie11d30102018-11-02 16:09:09 +01007216SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7217 const DeviceVector &devices,
7218 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007219{
7220 SortedVector<audio_io_handle_t> outputs;
7221
François Gaffie11d30102018-11-02 16:09:09 +01007222 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007223 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007224 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007225 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007226 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007227 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007228 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007229 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007230 outputs.add(openOutputs.keyAt(i));
7231 }
7232 }
7233 return outputs;
7234}
7235
Mikhail Naganov37977152018-07-11 15:54:44 -07007236void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7237{
7238 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7239 // output is suspended before any tracks are moved to it
7240 checkA2dpSuspend();
7241 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007242 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007243 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007244 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007245 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007246 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7247 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7248 // configuration changes will ultimately be rerouted correctly. We can still avoid
7249 // unnecessary rerouting by caching and reusing the arguments to
7250 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7251 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007252 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007253 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007254 // an event that changed routing likely occurred, inform upper layers
7255 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007256}
7257
François Gaffiec005e562018-11-06 15:04:49 +01007258bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7259 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007260{
François Gaffiec005e562018-11-06 15:04:49 +01007261 return mEngine->getProductStrategyForAttributes(lAttr) ==
7262 mEngine->getProductStrategyForAttributes(rAttr);
7263}
7264
Francois Gaffieff1eb522020-05-06 18:37:04 +02007265void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7266{
7267 for (size_t i = 0; i < mAudioSources.size(); i++) {
7268 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7269 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007270 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurent963dbcc2024-06-20 12:34:15 +00007271 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007272 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007273 }
7274 }
7275}
7276
7277void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7278{
7279 for (size_t i = 0; i < mAudioSources.size(); i++) {
7280 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7281 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7282 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7283 disconnectAudioSource(sourceDesc);
7284 }
7285 }
7286}
7287
François Gaffiec005e562018-11-06 15:04:49 +01007288void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7289{
7290 auto psId = mEngine->getProductStrategyForAttributes(attr);
7291
7292 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7293 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007294
François Gaffie11d30102018-11-02 16:09:09 +01007295 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7296 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007297
Eric Laurentc209fe42020-06-05 18:11:23 -07007298 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007299 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007300 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007301 // take into account dynamic audio policies related changes: if a client is now associated
7302 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007303 // invalidate clients on outputs that do not support all the newly selected devices for the
7304 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007305 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007306 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007307 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007308 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007309 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007310
Eric Laurentc209fe42020-06-05 18:11:23 -07007311 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7312 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7313 continue;
7314 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007315 if (!desc->supportsAllDevices(newDevices)) {
7316 invalidatedOutputs.push_back(desc);
7317 break;
7318 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007319 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007320 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007321 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7322 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7323 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007324 if (status == OK) {
7325 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7326 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7327 maxLatency = desc->latency();
7328 }
7329 invalidatedOutputs.push_back(desc);
7330 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007331 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007332 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007333 }
7334 }
7335
Eric Laurent56ed8842022-11-15 16:04:41 +01007336 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007337 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7338 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007339 for (audio_io_handle_t srcOut : srcOutputs) {
7340 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007341 if (desc == nullptr) continue;
7342
7343 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007344 maxLatency = desc->latency();
7345 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007346
Eric Laurent56ed8842022-11-15 16:04:41 +01007347 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007348 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007349 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007350 // a client on a non direct outputs has necessarily a linear PCM format
7351 // so we can call selectOutput() safely
7352 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7353 client->flags(),
7354 client->config().format,
7355 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007356 client->config().sample_rate,
7357 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007358 if (newOutput != srcOut) {
7359 invalidate = true;
7360 break;
7361 }
7362 } else {
7363 sp<IOProfile> profile = getProfileForOutput(newDevices,
7364 client->config().sample_rate,
7365 client->config().format,
7366 client->config().channel_mask,
7367 client->flags(),
7368 true /* directOnly */);
7369 if (profile != desc->mProfile) {
7370 invalidate = true;
7371 break;
7372 }
7373 }
7374 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007375 // mute strategy while moving tracks from one output to another
7376 if (invalidate) {
7377 invalidatedOutputs.push_back(desc);
7378 if (desc->isStrategyActive(psId)) {
7379 setStrategyMute(psId, true, desc);
7380 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7381 newDevices.types());
7382 }
Eric Laurente552edb2014-03-10 17:42:56 -07007383 }
François Gaffiec005e562018-11-06 15:04:49 +01007384 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurent963dbcc2024-06-20 12:34:15 +00007385 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007386 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007387 }
Eric Laurente552edb2014-03-10 17:42:56 -07007388 }
7389
Eric Laurent56ed8842022-11-15 16:04:41 +01007390 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7391 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7392 std::to_string(srcOutputs[0]).c_str(),
7393 std::to_string(dstOutputs[0]).c_str());
7394
François Gaffiec005e562018-11-06 15:04:49 +01007395 // Move effects associated to this stream from previous output to new output
7396 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007397 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007398 }
François Gaffiec005e562018-11-06 15:04:49 +01007399 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007400 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007401 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007402 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007403 desc->setTracksInvalidatedStatusByStrategy(psId);
7404 }
Eric Laurente552edb2014-03-10 17:42:56 -07007405 }
7406 }
7407}
7408
Eric Laurente0720872014-03-11 09:30:41 -07007409void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007410{
François Gaffiec005e562018-11-06 15:04:49 +01007411 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7412 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7413 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007414 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007415 }
Eric Laurente552edb2014-03-10 17:42:56 -07007416}
7417
Kevin Rocard153f92d2018-12-18 18:33:28 -08007418void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007419 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007420 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007421 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007422 for (size_t i = 0; i < mOutputs.size(); i++) {
7423 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7424 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007425 sp<AudioPolicyMix> primaryMix;
7426 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007427 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007428 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7429 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7430 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007431 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7432 for (auto &secondaryMix : secondaryMixes) {
7433 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7434 if (outputDesc != nullptr &&
7435 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7436 secondaryDescs.push_back(outputDesc);
7437 }
7438 }
7439
jiabinc44b3462022-12-08 12:52:31 -08007440 if (status != OK &&
7441 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7442 // When it failed to query secondary output, only invalidate the client that is not
7443 // MMAP. The reason is that MMAP stream will not support secondary output.
7444 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007445 } else if (!std::equal(
7446 client->getSecondaryOutputs().begin(),
7447 client->getSecondaryOutputs().end(),
7448 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungced57302024-08-14 11:37:57 -07007449 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7450 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007451 // If the format is not PCM, the tracks should be invalidated to get correct
7452 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007453 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007454 } else {
7455 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7456 std::vector<audio_io_handle_t> secondaryOutputIds;
7457 for (const auto &secondaryDesc: secondaryDescs) {
7458 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7459 weakSecondaryDescs.push_back(secondaryDesc);
7460 }
7461 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7462 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007463 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007464 }
7465 }
7466 }
jiabin10a03f12021-05-07 23:46:28 +00007467 if (!trackSecondaryOutputs.empty()) {
7468 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7469 }
jiabinc44b3462022-12-08 12:52:31 -08007470 if (!clientsToInvalidate.empty()) {
7471 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7472 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007473 }
7474}
7475
Eric Laurent2517af32020-11-25 15:31:27 +01007476bool AudioPolicyManager::isScoRequestedForComm() const {
7477 AudioDeviceTypeAddrVector devices;
7478 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7479 for (const auto &device : devices) {
7480 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7481 return true;
7482 }
7483 }
7484 return false;
7485}
7486
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007487bool AudioPolicyManager::isHearingAidUsedForComm() const {
7488 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7489 true /*fromCache*/);
7490 for (const auto &device : devices) {
7491 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7492 return true;
7493 }
7494 }
7495 return false;
7496}
7497
7498
Eric Laurente0720872014-03-11 09:30:41 -07007499void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007500{
François Gaffie53615e22015-03-19 09:24:12 +01007501 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007502 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007503 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007504 return;
7505 }
7506
Eric Laurent3a4311c2014-03-17 12:00:47 -07007507 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007508 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7509 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007510 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007511
7512 // if suspended, restore A2DP output if:
7513 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007514 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007515 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007516 //
Eric Laurentf732e072016-08-03 19:30:28 -07007517 // if not suspended, suspend A2DP output if:
7518 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007519 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007520 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007521 //
7522 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007523 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007524 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007525 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007526 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007527
7528 mpClientInterface->restoreOutput(a2dpOutput);
7529 mA2dpSuspended = false;
7530 }
7531 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007532 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007533 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007534 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007535 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007536
7537 mpClientInterface->suspendOutput(a2dpOutput);
7538 mA2dpSuspended = true;
7539 }
7540 }
7541}
7542
François Gaffie11d30102018-11-02 16:09:09 +01007543DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7544 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007545{
François Gaffiedb1755b2023-09-01 11:50:35 +02007546 if (outputDesc == nullptr) {
7547 return DeviceVector{};
7548 }
François Gaffie11d30102018-11-02 16:09:09 +01007549
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007550 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007551 if (index >= 0) {
7552 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007553 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007554 ALOGV("%s device %s forced by patch %d", __func__,
7555 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7556 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007557 }
7558 }
7559
Dean Wheatley514b4312020-06-17 21:45:00 +10007560 // Do not retrieve engine device for outputs through MSD
7561 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7562 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7563 return outputDesc->devices();
7564 }
7565
Eric Laurent97ac8712018-07-27 18:59:02 -07007566 // Honor explicit routing requests only if no client using default routing is active on this
7567 // input: a specific app can not force routing for other apps by setting a preferred device.
7568 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007569 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007570 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007571 if (device != nullptr) {
7572 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007573 }
7574
François Gaffiea807ef92018-11-05 10:44:33 +01007575 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7576 // of setForceUse / Default Bus device here
7577 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7578 if (device != nullptr) {
7579 return DeviceVector(device);
7580 }
7581
François Gaffiedb1755b2023-09-01 11:50:35 +02007582 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007583 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7584 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307585 auto hasStreamActive = [&](auto stream) {
7586 return hasStream(streams, stream) && isStreamActive(stream, 0);
7587 };
Eric Laurent484e9272018-06-07 17:29:23 -07007588
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307589 auto doGetOutputDevicesForVoice = [&]() {
7590 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007591 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307592 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007593 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7594 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307595 };
7596
7597 // With low-latency playing on speaker, music on WFD, when the first low-latency
7598 // output is stopped, getNewOutputDevices checks for a product strategy
7599 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007600 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307601 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7602 // stream is associated to the output descriptor.
7603 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7604 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7605 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7606 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007607 // Retrieval of devices for voice DL is done on primary output profile, cannot
7608 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007609 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007610 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7611 break;
7612 }
Eric Laurente552edb2014-03-10 17:42:56 -07007613 }
François Gaffiec005e562018-11-06 15:04:49 +01007614 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007615 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007616}
7617
François Gaffie11d30102018-11-02 16:09:09 +01007618sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7619 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007620{
François Gaffie11d30102018-11-02 16:09:09 +01007621 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007622
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007623 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007624 if (index >= 0) {
7625 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007626 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007627 ALOGV("getNewInputDevice() device %s forced by patch %d",
7628 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7629 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007630 }
7631 }
7632
Eric Laurent97ac8712018-07-27 18:59:02 -07007633 // Honor explicit routing requests only if no client using default routing is active on this
7634 // input: a specific app can not force routing for other apps by setting a preferred device.
7635 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007636 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7637 if (device != nullptr) {
7638 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007639 }
7640
Eric Laurentdc95a252018-04-12 12:46:56 -07007641 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007642 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007643 audio_attributes_t attributes;
7644 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007645 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007646 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7647 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007648 attributes = topClient->attributes();
7649 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007650 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007651 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007652 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7653 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007654 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007655 }
7656
Francois Gaffie716e1432019-01-14 16:58:59 +01007657 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7658 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007659 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007660 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007661 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007662 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007663
Eric Laurente552edb2014-03-10 17:42:56 -07007664 return device;
7665}
7666
Eric Laurent794fde22016-03-11 09:50:45 -08007667bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7668 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007669 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007670}
7671
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007672status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007673 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007674 if (devices == nullptr) {
7675 return BAD_VALUE;
7676 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007677
Andy Hung6d23c0f2022-02-16 09:37:15 -08007678 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007679 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7680 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007681 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007682 for (const auto& device : curDevices) {
7683 devices->push_back(device->getDeviceTypeAddr());
7684 }
7685 return NO_ERROR;
7686}
7687
Eric Laurente0720872014-03-11 09:30:41 -07007688void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007689 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007690 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007691 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007692 updateDevicesAndOutputs();
7693 break;
7694 default:
7695 break;
7696 }
7697}
7698
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007699uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007700
7701 // skip beacon mute management if a dedicated TTS output is available
7702 if (mTtsOutputAvailable) {
7703 return 0;
7704 }
7705
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007706 switch(event) {
7707 case STARTING_OUTPUT:
7708 mBeaconMuteRefCount++;
7709 break;
7710 case STOPPING_OUTPUT:
7711 if (mBeaconMuteRefCount > 0) {
7712 mBeaconMuteRefCount--;
7713 }
7714 break;
7715 case STARTING_BEACON:
7716 mBeaconPlayingRefCount++;
7717 break;
7718 case STOPPING_BEACON:
7719 if (mBeaconPlayingRefCount > 0) {
7720 mBeaconPlayingRefCount--;
7721 }
7722 break;
7723 }
7724
7725 if (mBeaconMuteRefCount > 0) {
7726 // any playback causes beacon to be muted
7727 return setBeaconMute(true);
7728 } else {
7729 // no other playback: unmute when beacon starts playing, mute when it stops
7730 return setBeaconMute(mBeaconPlayingRefCount == 0);
7731 }
7732}
7733
7734uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7735 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7736 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7737 // keep track of muted state to avoid repeating mute/unmute operations
7738 if (mBeaconMuted != mute) {
7739 // mute/unmute AUDIO_STREAM_TTS on all outputs
7740 ALOGV("\t muting %d", mute);
7741 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007742 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7743 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7744 ALOGV("\t no tts volume source available");
7745 return 0;
7746 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007747 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007748 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007749 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007750 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007751 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007752 maxLatency = latency;
7753 }
7754 }
7755 mBeaconMuted = mute;
7756 return maxLatency;
7757 }
7758 return 0;
7759}
7760
Eric Laurente0720872014-03-11 09:30:41 -07007761void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007762{
François Gaffiec005e562018-11-06 15:04:49 +01007763 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007764 mPreviousOutputs = mOutputs;
7765}
7766
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007767uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007768 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007769 uint32_t delayMs)
7770{
7771 // mute/unmute strategies using an incompatible device combination
7772 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7773 // if unmuting, unmute only after the specified delay
7774 if (outputDesc->isDuplicated()) {
7775 return 0;
7776 }
7777
7778 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007779 DeviceVector devices = outputDesc->devices();
7780 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007781
François Gaffiec005e562018-11-06 15:04:49 +01007782 auto productStrategies = mEngine->getOrderedProductStrategies();
7783 for (const auto &productStrategy : productStrategies) {
7784 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7785 DeviceVector curDevices =
7786 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7787 curDevices = curDevices.filter(outputDesc->supportedDevices());
7788 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007789 bool doMute = false;
7790
François Gaffiec005e562018-11-06 15:04:49 +01007791 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007792 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007793 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7794 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007795 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007796 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007797 }
Eric Laurent99401132014-05-07 19:48:15 -07007798 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007799 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007800 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007801 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007802 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007803 continue;
7804 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307805 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007806 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7807 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7808 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007809 if (mute) {
7810 // FIXME: should not need to double latency if volume could be applied
7811 // immediately by the audioflinger mixer. We must account for the delay
7812 // between now and the next time the audioflinger thread for this output
7813 // will process a buffer (which corresponds to one buffer size,
7814 // usually 1/2 or 1/4 of the latency).
7815 if (muteWaitMs < desc->latency() * 2) {
7816 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007817 }
7818 }
7819 }
7820 }
7821 }
7822 }
7823
Eric Laurent99401132014-05-07 19:48:15 -07007824 // temporary mute output if device selection changes to avoid volume bursts due to
7825 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007826 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007827 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007828
Eric Laurentdc462862016-07-19 12:29:53 -07007829 if (muteWaitMs < tempMuteWaitMs) {
7830 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007831 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007832
7833 // If recommended duration is defined, replace temporary mute duration to avoid
7834 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7835 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7836 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7837 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7838 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7839
François Gaffieaaac0fd2018-11-22 17:56:39 +01007840 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7841 // make sure that we do not start the temporary mute period too early in case of
7842 // delayed device change
7843 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7844 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007845 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007846 }
7847 }
7848
Eric Laurente552edb2014-03-10 17:42:56 -07007849 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7850 if (muteWaitMs > delayMs) {
7851 muteWaitMs -= delayMs;
7852 usleep(muteWaitMs * 1000);
7853 return muteWaitMs;
7854 }
7855 return 0;
7856}
7857
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307858uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7859 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007860 const DeviceVector &devices,
7861 bool force,
7862 int delayMs,
7863 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007864 bool requiresMuteCheck, bool requiresVolumeCheck,
7865 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007866{
jiabin3ff8d7d2022-12-13 06:27:44 +00007867 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307868 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7869 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7870 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007871 uint32_t muteWaitMs;
7872
7873 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307874 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007875 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307876 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007877 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007878 return muteWaitMs;
7879 }
Eric Laurente552edb2014-03-10 17:42:56 -07007880
7881 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007882 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007883 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007884 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007885
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307886 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7887 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007888
7889 if (!filteredDevices.isEmpty()) {
7890 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007891 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007892
7893 // if the outputs are not materially active, there is no need to mute.
7894 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007895 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007896 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307897 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7898 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007899 muteWaitMs = 0;
7900 }
Eric Laurente552edb2014-03-10 17:42:56 -07007901
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007902 bool outputRouted = outputDesc->isRouted();
7903
Eric Laurent79ea9582020-06-11 18:49:24 -07007904 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7905 // output profile or if new device is not supported AND previous device(s) is(are) still
7906 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007907 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307908 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7909 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007910 // restore previous device after evaluating strategy mute state
7911 outputDesc->setDevices(prevDevices);
7912 return muteWaitMs;
7913 }
7914
Eric Laurente552edb2014-03-10 17:42:56 -07007915 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007916 // the requested device is AUDIO_DEVICE_NONE
7917 // OR the requested device is the same as current device
7918 // AND force is not specified
7919 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007920 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007921 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307922 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7923 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7924 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007925 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307926 ALOGV("%s %s setting same device on routed output, force apply volumes",
7927 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007928 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7929 }
Eric Laurente552edb2014-03-10 17:42:56 -07007930 return muteWaitMs;
7931 }
7932
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307933 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7934 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007935
Eric Laurente552edb2014-03-10 17:42:56 -07007936 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007937 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007938 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007939 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007940 PatchBuilder patchBuilder;
7941 patchBuilder.addSource(outputDesc);
7942 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7943 for (const auto &filteredDevice : filteredDevices) {
7944 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007945 }
7946
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007947 // Add half reported latency to delayMs when muteWaitMs is null in order
7948 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007949 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7950 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7951 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007952 }
Eric Laurente552edb2014-03-10 17:42:56 -07007953
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007954 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7955 if (!skipMuteDelay) {
7956 // update stream volumes according to new device
7957 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7958 }
Eric Laurente552edb2014-03-10 17:42:56 -07007959
7960 return muteWaitMs;
7961}
7962
Eric Laurentc75307b2015-03-17 15:29:32 -07007963status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007964 int delayMs,
7965 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007966{
Eric Laurent6a94d692014-05-20 11:18:06 -07007967 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007968 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7969 return INVALID_OPERATION;
7970 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007971 if (patchHandle) {
7972 index = mAudioPatches.indexOfKey(*patchHandle);
7973 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007974 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007975 }
7976 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007977 return INVALID_OPERATION;
7978 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007979 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007980 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007981 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007982 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007983 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007984 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007985 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007986 return status;
7987}
7988
7989status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007990 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007991 bool force,
7992 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007993{
7994 status_t status = NO_ERROR;
7995
Eric Laurent1f2f2232014-06-02 12:01:23 -07007996 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007997 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7998 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007999
François Gaffie11d30102018-11-02 16:09:09 +01008000 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07008001 PatchBuilder patchBuilder;
8002 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07008003 // AUDIO_SOURCE_HOTWORD is for internal use only:
8004 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07008005 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
8006 auto result = usecase;
8007 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
8008 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
8009 }
Dean Wheatleyb9841832024-10-01 14:56:29 +10008010 return result; });
Eric Laurent1c333e22014-05-20 10:48:17 -07008011 //only one input device for now
Dean Wheatleyb9841832024-10-01 14:56:29 +10008012 if (audio_is_remote_submix_device(device->type())) {
8013 // remote submix HAL does not support audio conversion, need source device
8014 // audio config to match the sink input descriptor audio config, otherwise AIDL
8015 // HAL patching will fail
8016 audio_port_config srcDevicePortConfig = {};
8017 device->toAudioPortConfig(&srcDevicePortConfig, nullptr);
8018 srcDevicePortConfig.sample_rate = inputDesc->getSamplingRate();
8019 srcDevicePortConfig.channel_mask = inputDesc->getChannelMask();
8020 srcDevicePortConfig.format = inputDesc->getFormat();
8021 patchBuilder.addSource(srcDevicePortConfig);
8022 } else {
8023 patchBuilder.addSource(device);
8024 }
Mikhail Naganovdc769682018-05-04 15:34:08 -07008025 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008026 }
8027 }
8028 return status;
8029}
8030
Eric Laurent6a94d692014-05-20 11:18:06 -07008031status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8032 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008033{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008034 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008035 ssize_t index;
8036 if (patchHandle) {
8037 index = mAudioPatches.indexOfKey(*patchHandle);
8038 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008039 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008040 }
8041 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008042 return INVALID_OPERATION;
8043 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008044 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008045 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008046 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008047 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008048 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008049 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008050 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008051 return status;
8052}
8053
François Gaffie11d30102018-11-02 16:09:09 +01008054sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008055 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008056 audio_format_t& format,
8057 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008058 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008059{
8060 // Choose an input profile based on the requested capture parameters: select the first available
8061 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008062 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008063
Atneya Nair0f0a8032022-12-12 16:20:12 -08008064 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8065 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8066 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8067
8068 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008069
jiabin2fd710d2022-05-02 23:20:22 +00008070 for (;;) {
8071 sp<IOProfile> firstInexact = nullptr;
8072 uint32_t updatedSamplingRate = 0;
8073 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8074 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8075 for (const auto& hwModule : mHwModules) {
8076 for (const auto& profile : hwModule->getInputProfiles()) {
8077 // profile->log();
8078 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008079 if (profile->getCompatibilityScore(
8080 DeviceVector(device),
8081 samplingRate,
8082 &updatedSamplingRate,
8083 format,
8084 &updatedFormat,
8085 channelMask,
8086 &updatedChannelMask,
8087 // FIXME ugly cast
8088 (audio_output_flags_t) flags,
8089 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8090 samplingRate = updatedSamplingRate;
8091 format = updatedFormat;
8092 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008093 return profile;
8094 }
jiabin66acc432024-02-06 00:57:36 +00008095 if (firstInexact == nullptr
8096 && profile->getCompatibilityScore(
8097 DeviceVector(device),
8098 samplingRate,
8099 &updatedSamplingRate,
8100 format,
8101 &updatedFormat,
8102 channelMask,
8103 &updatedChannelMask,
8104 // FIXME ugly cast
8105 (audio_output_flags_t) flags,
8106 false /*exactMatchRequiredForInputFlags*/)
8107 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008108 firstInexact = profile;
8109 }
8110 }
8111 }
8112
8113 if (firstInexact != nullptr) {
8114 samplingRate = updatedSamplingRate;
8115 format = updatedFormat;
8116 channelMask = updatedChannelMask;
8117 return firstInexact;
8118 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8119 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8120 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8121 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8122 flags = AUDIO_INPUT_FLAG_NONE;
8123 } else { // fail
8124 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8125 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8126 samplingRate, format, channelMask, oriFlags);
8127 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008128 }
8129 }
jiabin2fd710d2022-05-02 23:20:22 +00008130
8131 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008132}
8133
Vlad Popa87e0e582024-05-20 18:49:20 -07008134float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8135 VolumeSource volumeSource,
8136 int index,
8137 const DeviceTypeSet &deviceTypes)
8138{
8139 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8140 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8141 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8142
8143 if (com_android_media_audio_abs_volume_index_fix()) {
8144 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8145 mAbsoluteVolumeDrivingStreams.end()) {
8146 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8147 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8148 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8149 ALOGD("%s: no group matching with %s", __FUNCTION__,
8150 toString(attributesToDriveAbs).c_str());
8151 return volumeDb;
8152 }
8153
8154 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8155 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8156 if (vsToDriveAbs == volumeSource) {
8157 // attenuation is applied by the abs volume controller
8158 return volumeDbMax;
8159 } else {
8160 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8161 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8162 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8163 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8164 curvesAbs.getVolumeIndexMax());
8165 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8166 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8167 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8168 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8169 return newVolumeDb;
8170 }
8171 }
8172 return volumeDb;
8173 } else {
8174 return volumeDb;
8175 }
8176}
8177
François Gaffieaaac0fd2018-11-22 17:56:39 +01008178float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8179 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008180 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008181 const DeviceTypeSet& deviceTypes,
8182 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008183{
Vlad Popa87e0e582024-05-20 18:49:20 -07008184 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008185 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8186 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8187
8188 if (!computeInternalInteraction) {
8189 return volumeDb;
8190 }
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008191
8192 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8193 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8194 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8195 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008196 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8197 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8198 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8199 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8200 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008201 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008202 mOutputs.isActive(ringVolumeSrc, 0)) {
8203 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008204 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8205 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008206 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008207 }
8208
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008209 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008210 if ((volumeSource != callVolumeSrc && (isInCall() ||
8211 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008212 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008213 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8214 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008215 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8216 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8217 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008218 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008219 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008220 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008221 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008222 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8223 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008224 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008225 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8226 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8227 // programmatically muted.
8228 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8229 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8230 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008231 bool exemptFromCapping =
8232 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8233 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008234 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8235 volumeSource, volumeDb);
8236 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008237 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8238 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8239 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008240 }
8241 }
Eric Laurente552edb2014-03-10 17:42:56 -07008242 // if a headset is connected, apply the following rules to ring tones and notifications
8243 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008244 // - always attenuate notifications volume by 6dB
8245 // - attenuate ring tones volume by 6dB unless music is not playing and
8246 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008247 // - if music is playing, always limit the volume to current music volume,
8248 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008249 if (!Intersection(deviceTypes,
8250 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8251 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008252 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8253 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008254 ((volumeSource == alarmVolumeSrc ||
8255 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008256 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8257 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8258 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008259 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8260 curves.canBeMuted()) {
8261
Eric Laurente552edb2014-03-10 17:42:56 -07008262 // when the phone is ringing we must consider that music could have been paused just before
8263 // by the music application and behave as if music was active if the last music track was
8264 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008265 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8266 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008267 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008268 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008269 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8270 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008271 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008272 float musicVolDb = computeVolume(musicCurves,
8273 musicVolumeSrc,
8274 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008275 musicDevice,
8276 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008277 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8278 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8279 if (volumeDb > minVolDb) {
8280 volumeDb = minVolDb;
8281 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008282 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008283 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8284 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008285 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8286 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8287 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8288 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008289 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008290 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008291 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8292 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008293 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8294 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008295 }
8296 }
jiabin9a3361e2019-10-01 09:38:30 -07008297 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008298 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008299 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008300 }
8301 }
8302
François Gaffie43c73442018-11-08 08:21:55 +01008303 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008304}
8305
Eric Laurent3839bc02018-07-10 18:33:34 -07008306int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008307 VolumeSource fromVolumeSource,
8308 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008309{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008310 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008311 return srcIndex;
8312 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008313 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8314 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008315 float minSrc = (float)srcCurves.getVolumeIndexMin();
8316 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8317 float minDst = (float)dstCurves.getVolumeIndexMin();
8318 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008319
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008320 // preserve mute request or correct range
8321 if (srcIndex < minSrc) {
8322 if (srcIndex == 0) {
8323 return 0;
8324 }
8325 srcIndex = minSrc;
8326 } else if (srcIndex > maxSrc) {
8327 srcIndex = maxSrc;
8328 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008329 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8330}
8331
François Gaffieaaac0fd2018-11-22 17:56:39 +01008332status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8333 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008334 int index,
8335 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008336 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008337 int delayMs,
8338 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008339{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008340 // APM is single threaded, and single instance.
8341 static std::set<IVolumeCurves*> invalidCurvesReported;
8342
François Gaffieaaac0fd2018-11-22 17:56:39 +01008343 // do not change actual attributes volume if the attributes is muted
8344 if (outputDesc->isMuted(volumeSource)) {
8345 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8346 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008347 return NO_ERROR;
8348 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008349
Eric Laurent5baf07c2024-01-11 16:57:27 +00008350 bool isVoiceVolSrc;
8351 bool isBtScoVolSrc;
8352 if (!isVolumeConsistentForCalls(
8353 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008354 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008355 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008356 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008357 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008358
jiabin9a3361e2019-10-01 09:38:30 -07008359 if (deviceTypes.empty()) {
8360 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008361 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008362 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008363 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008364 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008365
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008366 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008367 if (!invalidCurvesReported.count(&curves)) {
8368 invalidCurvesReported.insert(&curves);
8369 String8 dump;
8370 curves.dump(&dump);
8371 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8372 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008373 return BAD_VALUE;
8374 }
8375
jiabin9a3361e2019-10-01 09:38:30 -07008376 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8377 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008378 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008379 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008380 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8381 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008382 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008383 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008384 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008385 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8386 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008387
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008388 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008389 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8390 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8391 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008392 }
Eric Laurente552edb2014-03-10 17:42:56 -07008393 return NO_ERROR;
8394}
8395
Eric Laurent5baf07c2024-01-11 16:57:27 +00008396void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008397 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008398 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008399 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008400 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008401 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008402 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8403 } else {
8404 voiceVolume = index == 0 ? 0.0 : 1.0;
8405 }
8406 if (voiceVolume != mLastVoiceVolume) {
8407 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8408 mLastVoiceVolume = voiceVolume;
8409 }
8410}
8411
8412bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8413 const DeviceTypeSet& deviceTypes,
8414 bool& isVoiceVolSrc,
8415 bool& isBtScoVolSrc,
8416 const char* caller) {
8417 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8418 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8419 const bool isScoRequested = isScoRequestedForComm();
8420 const bool isHAUsed = isHearingAidUsedForComm();
8421
8422 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8423 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8424
8425 if ((callVolSrc != btScoVolSrc) &&
8426 ((isVoiceVolSrc && isScoRequested) ||
8427 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8428 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8429 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8430 volumeSource, isScoRequested ? " " : " not ");
8431 return false;
8432 }
8433 return true;
8434}
8435
Eric Laurentc75307b2015-03-17 15:29:32 -07008436void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008437 const DeviceTypeSet& deviceTypes,
8438 int delayMs,
8439 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008440{
jiabincd510522020-01-22 09:40:55 -08008441 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008442 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8443 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8444 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008445 curves.getVolumeIndex(deviceTypes),
8446 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008447 }
8448}
8449
François Gaffiec005e562018-11-06 15:04:49 +01008450void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8451 bool on,
8452 const sp<AudioOutputDescriptor>& outputDesc,
8453 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008454 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008455{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008456 std::vector<VolumeSource> sourcesToMute;
8457 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8458 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8459 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008460 VolumeSource source = toVolumeSource(attributes, false);
8461 if ((source != VOLUME_SOURCE_NONE) &&
8462 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8463 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008464 sourcesToMute.push_back(source);
8465 }
Eric Laurente552edb2014-03-10 17:42:56 -07008466 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008467 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008468 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008469 }
8470
Eric Laurente552edb2014-03-10 17:42:56 -07008471}
8472
François Gaffieaaac0fd2018-11-22 17:56:39 +01008473void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8474 bool on,
8475 const sp<AudioOutputDescriptor>& outputDesc,
8476 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008477 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008478{
jiabin9a3361e2019-10-01 09:38:30 -07008479 if (deviceTypes.empty()) {
8480 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008481 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008482 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008483 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008484 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008485 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008486 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008487 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8488 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008489 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008490 }
8491 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008492 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8493 // ignored
8494 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008495 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008496 if (!outputDesc->isMuted(volumeSource)) {
8497 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008498 return;
8499 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008500 if (outputDesc->decMuteCount(volumeSource) == 0) {
8501 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008502 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008503 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008504 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008505 delayMs);
8506 }
8507 }
8508}
8509
François Gaffie53615e22015-03-19 09:24:12 +01008510bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8511{
François Gaffiec005e562018-11-06 15:04:49 +01008512 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008513 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8514 return true;
8515 }
8516
8517 // has known usage?
8518 switch (paa->usage) {
8519 case AUDIO_USAGE_UNKNOWN:
8520 case AUDIO_USAGE_MEDIA:
8521 case AUDIO_USAGE_VOICE_COMMUNICATION:
8522 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8523 case AUDIO_USAGE_ALARM:
8524 case AUDIO_USAGE_NOTIFICATION:
8525 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8526 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8527 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8528 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8529 case AUDIO_USAGE_NOTIFICATION_EVENT:
8530 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8531 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8532 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8533 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008534 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008535 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008536 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008537 case AUDIO_USAGE_EMERGENCY:
8538 case AUDIO_USAGE_SAFETY:
8539 case AUDIO_USAGE_VEHICLE_STATUS:
8540 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008541 break;
8542 default:
8543 return false;
8544 }
8545 return true;
8546}
8547
François Gaffie2110e042015-03-24 08:41:51 +01008548audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8549{
8550 return mEngine->getForceUse(usage);
8551}
8552
Eric Laurent96d1dda2022-03-14 17:14:19 +01008553bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008554 return isStateInCall(mEngine->getPhoneState());
8555}
8556
Eric Laurent96d1dda2022-03-14 17:14:19 +01008557bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008558 return is_state_in_call(state);
8559}
8560
Eric Laurentf9cccec2022-11-16 19:12:00 +01008561bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008562 audio_mode_t mode = mEngine->getPhoneState();
8563 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008564 || (mode == AUDIO_MODE_CALL_SCREEN)
8565 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008566}
8567
Eric Laurentf9cccec2022-11-16 19:12:00 +01008568bool AudioPolicyManager::isInCallOrScreening() const {
8569 audio_mode_t mode = mEngine->getPhoneState();
8570 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8571}
8572
Eric Laurentd60560a2015-04-10 11:31:20 -07008573void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8574{
8575 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008576 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008577 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008578 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurent963dbcc2024-06-20 12:34:15 +00008579 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008580 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008581 }
8582 }
8583
8584 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8585 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8586 bool release = false;
8587 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8588 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8589 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8590 source->ext.device.type == deviceDesc->type()) {
8591 release = true;
8592 }
8593 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008594 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008595 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8596 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8597 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008598 sink->ext.device.type == deviceDesc->type() &&
8599 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8600 || strncmp(sink->ext.device.address, address,
8601 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008602 release = true;
8603 }
8604 }
8605 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008606 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8607 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008608 }
8609 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008610
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008611 mInputs.clearSessionRoutesForDevice(deviceDesc);
8612
Francois Gaffie716e1432019-01-14 16:58:59 +01008613 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008614}
8615
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008616void AudioPolicyManager::modifySurroundFormats(
8617 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008618 std::unordered_set<audio_format_t> enforcedSurround(
8619 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008620 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008621 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008622 allSurround.insert(pair.first);
8623 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8624 }
Phil Burk09bc4612016-02-24 15:58:15 -08008625
8626 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8627 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008628 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008629 // This is the resulting set of formats depending on the surround mode:
8630 // 'all surround' = allSurround
8631 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8632 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8633 // 'manual surround' = mManualSurroundFormats
8634 // AUTO: formats v 'enforced surround'
8635 // ALWAYS: formats v 'all surround' v 'enforced surround'
8636 // NEVER: formats ^ 'non-surround'
8637 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008638
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008639 std::unordered_set<audio_format_t> formatSet;
8640 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8641 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008642 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008643 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008644 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008645 formatSet.insert(*formatIter);
8646 }
8647 }
8648 } else {
8649 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8650 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008651 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008652
jiabin81772902018-04-02 17:52:27 -07008653 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008654 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008655 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8656 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8657 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008658 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008659 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8660 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8661 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008662 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008663 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008664 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008665 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008666 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008667 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008668}
8669
jiabin06e4bab2019-07-29 10:13:34 -07008670void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8671 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008672 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8673 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8674
8675 // If NEVER, then remove support for channelMasks > stereo.
8676 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008677 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8678 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008679 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008680 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008681 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008682 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008683 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008684 }
8685 }
jiabin81772902018-04-02 17:52:27 -07008686 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8687 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8688 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008689 bool supports5dot1 = false;
8690 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008691 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008692 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8693 supports5dot1 = true;
8694 break;
8695 }
8696 }
8697 // If not then add 5.1 support.
8698 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008699 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008700 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008701 }
Phil Burk09bc4612016-02-24 15:58:15 -08008702 }
8703}
8704
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008705void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008706 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008707 const sp<IOProfile>& profile) {
8708 if (!profile->hasDynamicAudioProfile()) {
8709 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008710 }
François Gaffie112b0af2015-11-19 16:13:25 +01008711
jiabin12537fc2023-10-12 17:56:08 +00008712 audio_port_v7 devicePort;
8713 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008714
jiabin12537fc2023-10-12 17:56:08 +00008715 audio_port_v7 mixPort;
8716 profile->toAudioPort(&mixPort);
8717 mixPort.ext.mix.handle = ioHandle;
8718
8719 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8720 if (status != NO_ERROR) {
8721 ALOGE("%s failed to query the attributes of the mix port", __func__);
8722 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008723 }
jiabin12537fc2023-10-12 17:56:08 +00008724
8725 std::set<audio_format_t> supportedFormats;
8726 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8727 supportedFormats.insert(mixPort.audio_profiles[i].format);
8728 }
8729 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8730 mReportedFormatsMap[devDesc] = formats;
8731
8732 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
hongchao.yinf0c82082024-07-24 19:41:02 +08008733 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_ARC ||
8734 devDesc->type() == AUDIO_DEVICE_OUT_HDMI_EARC ||
jiabin12537fc2023-10-12 17:56:08 +00008735 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8736 modifySurroundFormats(devDesc, &formats);
8737 size_t modifiedNumProfiles = 0;
8738 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8739 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8740 formats.end()) {
8741 // Skip the format that is not present after modifying surround formats.
8742 continue;
8743 }
8744 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8745 sizeof(struct audio_profile));
8746 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8747 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8748 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8749 modifySurroundChannelMasks(&channels);
8750 std::copy(channels.begin(), channels.end(),
8751 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8752 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8753 }
8754 mixPort.num_audio_profiles = modifiedNumProfiles;
8755 }
8756 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008757}
Eric Laurentd60560a2015-04-10 11:31:20 -07008758
Mikhail Naganovdc769682018-05-04 15:34:08 -07008759status_t AudioPolicyManager::installPatch(const char *caller,
8760 audio_patch_handle_t *patchHandle,
8761 AudioIODescriptorInterface *ioDescriptor,
8762 const struct audio_patch *patch,
8763 int delayMs)
8764{
8765 ssize_t index = mAudioPatches.indexOfKey(
8766 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8767 *patchHandle : ioDescriptor->getPatchHandle());
8768 sp<AudioPatch> patchDesc;
8769 status_t status = installPatch(
8770 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8771 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008772 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008773 }
8774 return status;
8775}
8776
8777status_t AudioPolicyManager::installPatch(const char *caller,
8778 ssize_t index,
8779 audio_patch_handle_t *patchHandle,
8780 const struct audio_patch *patch,
8781 int delayMs,
8782 uid_t uid,
8783 sp<AudioPatch> *patchDescPtr)
8784{
8785 sp<AudioPatch> patchDesc;
8786 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8787 if (index >= 0) {
8788 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008789 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008790 }
8791
8792 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8793 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8794 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8795 if (status == NO_ERROR) {
8796 if (index < 0) {
8797 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008798 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008799 } else {
8800 patchDesc->mPatch = *patch;
8801 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008802 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008803 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008804 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008805 }
8806 nextAudioPortGeneration();
8807 mpClientInterface->onAudioPatchListUpdate();
8808 }
8809 if (patchDescPtr) *patchDescPtr = patchDesc;
8810 return status;
8811}
8812
jiabinbce0c1d2020-10-05 11:20:18 -07008813bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8814{
8815 const TrackClientVector activeClients = output->getActiveClients();
8816 if (activeClients.empty()) {
8817 return true;
8818 }
8819 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8820 if (index < 0) {
8821 ALOGE("%s, no audio patch found while there are active clients on output %d",
8822 __func__, output->getId());
8823 return false;
8824 }
8825 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8826 DeviceVector routedDevices;
8827 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8828 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8829 patchDesc->mPatch.sinks[i].id);
8830 if (device == nullptr) {
8831 ALOGE("%s, no audio device found with id(%d)",
8832 __func__, patchDesc->mPatch.sinks[i].id);
8833 return false;
8834 }
8835 routedDevices.add(device);
8836 }
8837 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008838 if (client->isInvalid()) {
8839 // No need to take care about invalidated clients.
8840 continue;
8841 }
jiabinbce0c1d2020-10-05 11:20:18 -07008842 sp<DeviceDescriptor> preferredDevice =
8843 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8844 if (mEngine->getOutputDevicesForAttributes(
8845 client->attributes(), preferredDevice, false) == routedDevices) {
8846 return false;
8847 }
8848 }
8849 return true;
8850}
8851
8852sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008853 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008854 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8855 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008856{
8857 for (const auto& device : devices) {
8858 // TODO: This should be checking if the profile supports the device combo.
8859 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008860 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8861 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008862 return nullptr;
8863 }
8864 }
8865 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8866 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008867 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00008868 status_t status = desc->open(halConfig, mixerConfig, devices,
Dean Wheatleydfb67b82024-01-23 09:36:29 +11008869 AUDIO_STREAM_DEFAULT, &flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008870 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008871 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008872 return nullptr;
8873 }
jiabin14b50cc2023-12-13 19:01:52 +00008874 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8875 auto portConfig = desc->getConfig();
8876 for (const auto& device : devices) {
8877 device->setPreferredConfig(&portConfig);
8878 }
8879 }
jiabinbce0c1d2020-10-05 11:20:18 -07008880
8881 // Here is where the out_set_parameters() for card & device gets called
8882 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8883 const audio_devices_t deviceType = device->type();
8884 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008885 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008886 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8887 mpClientInterface->setParameters(output, String8(param));
8888 free(param);
8889 }
jiabin12537fc2023-10-12 17:56:08 +00008890 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008891 if (!profile->hasValidAudioProfile()) {
8892 ALOGW("%s() missing param", __func__);
8893 desc->close();
8894 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008895 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8896 // Reopen the output with the best audio profile picked by APM when the profile supports
8897 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008898 desc->close();
8899 output = AUDIO_IO_HANDLE_NONE;
8900 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8901 profile->pickAudioProfile(
8902 config.sample_rate, config.channel_mask, config.format);
8903 config.offload_info.sample_rate = config.sample_rate;
8904 config.offload_info.channel_mask = config.channel_mask;
8905 config.offload_info.format = config.format;
8906
Dean Wheatleydfb67b82024-01-23 09:36:29 +11008907 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, &flags, &output,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008908 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008909 if (status != NO_ERROR) {
8910 return nullptr;
8911 }
8912 }
8913
8914 addOutput(output, desc);
Mikhail Naganovccd149c2024-09-26 14:16:13 -07008915 // The version check is essentially to avoid making this call in the case of the HIDL HAL.
8916 if (auto hwModule = mHwModules.getModuleFromHandle(mPrimaryModuleHandle); hwModule &&
8917 hwModule->getHalVersionMajor() >= 3) {
8918 setOutputDevices(__func__, desc, devices, true, 0, NULL);
8919 }
baek.kim -61c20122022-07-27 10:05:32 +00008920 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8921 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8922
jiabinbce0c1d2020-10-05 11:20:18 -07008923 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8924 sp<AudioPolicyMix> policyMix;
8925 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8926 policyMix->setOutput(desc);
8927 desc->mPolicyMix = policyMix;
8928 } else {
8929 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008930 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008931 }
8932
baek.kim -61c20122022-07-27 10:05:32 +00008933 } else if (hasPrimaryOutput() && speaker != nullptr
8934 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008935 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8936 // no duplicated output for:
8937 // - direct outputs
8938 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008939 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008940 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8941
8942 //TODO: configure audio effect output stage here
8943
8944 // open a duplicating output thread for the new output and the primary output
8945 sp<SwAudioOutputDescriptor> dupOutputDesc =
8946 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8947 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8948 if (status == NO_ERROR) {
8949 // add duplicated output descriptor
8950 addOutput(duplicatedOutput, dupOutputDesc);
8951 } else {
8952 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8953 mPrimaryOutput->mIoHandle, output);
8954 desc->close();
8955 removeOutput(output);
8956 nextAudioPortGeneration();
8957 return nullptr;
8958 }
8959 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008960 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8961 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8962 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008963 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008964 }
jiabinbce0c1d2020-10-05 11:20:18 -07008965 return desc;
8966}
8967
jiabinf1c73972022-04-14 16:28:52 -07008968status_t AudioPolicyManager::getDevicesForAttributes(
8969 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8970 // Devices are determined in the following precedence:
8971 //
8972 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8973 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8974 //
8975 // If no such dynamic policy then
8976 // 2) Devices containing an active client using setPreferredDevice
8977 // with same strategy as the attributes.
8978 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8979 //
8980 // If no corresponding active client with setPreferredDevice then
8981 // 3) Devices associated with the strategy determined by the attributes
8982 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8983 //
8984 // See related getOutputForAttrInt().
8985
8986 // check dynamic policies but only for primary descriptors (secondary not used for audible
8987 // audio routing, only used for duplication for playback capture)
8988 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008989 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008990 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008991 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8992 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8993 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008994 if (status != OK) {
8995 return status;
8996 }
8997
8998 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8999 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
9000 // as they are unaffected by device/stream volume
9001 // (per SwAudioOutputDescriptor::isFixedVolume()).
9002 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
9003 ) {
9004 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
9005 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
9006 devices.add(deviceDesc);
9007 } else {
9008 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
9009 // which selects setPreferredDevice if active. This means forVolume call
9010 // will take an active setPreferredDevice, if such exists.
9011
9012 devices = mEngine->getOutputDevicesForAttributes(
9013 attr, nullptr /* preferredDevice */, false /* fromCache */);
9014 }
9015
9016 if (forVolume) {
9017 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
9018 // for single volume control in AudioService (such relationship should exist if
9019 // SPEAKER_SAFE is present).
9020 //
9021 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
9022 DeviceVector speakerSafeDevices =
9023 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
9024 if (!speakerSafeDevices.isEmpty()) {
9025 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9026 devices.remove(speakerSafeDevices);
9027 }
9028 }
9029
9030 return NO_ERROR;
9031}
9032
9033status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9034 AudioProfileVector& audioProfiles,
9035 uint32_t flags,
9036 bool isInput) {
9037 for (const auto& hwModule : mHwModules) {
9038 // the MSD module checks for different conditions
9039 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9040 continue;
9041 }
9042 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9043 : hwModule->getOutputProfiles();
9044 for (const auto& profile : ioProfiles) {
9045 if (!profile->areAllDevicesSupported(devices) ||
9046 !profile->isCompatibleProfileForFlags(
9047 flags, false /*exactMatchRequiredForInputFlags*/)) {
9048 continue;
9049 }
9050 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9051 }
9052 }
9053
9054 if (!isInput) {
9055 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9056 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9057 if (msdModule != nullptr) {
9058 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9059 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9060 for (const auto &profile: msdModule->getOutputProfiles()) {
9061 if (!profile->asAudioPort()->isDirectOutput()) {
9062 continue;
9063 }
9064 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9065 }
9066 } else {
9067 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9068 }
9069 }
9070 }
9071
9072 return NO_ERROR;
9073}
9074
jiabin3ff8d7d2022-12-13 06:27:44 +00009075sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9076 const audio_config_t *config,
9077 audio_output_flags_t flags,
9078 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009079 closeOutput(outputDesc->mIoHandle);
9080 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9081 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9082 if (preferredOutput == nullptr) {
9083 ALOGE("%s failed to reopen output device=%d, caller=%s",
9084 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009085 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009086 return preferredOutput;
9087}
9088
9089void AudioPolicyManager::reopenOutputsWithDevices(
9090 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9091 for (const auto& [output, devices] : outputsToReopen) {
9092 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9093 closeOutput(output);
9094 openOutputWithProfileAndDevice(desc->mProfile, devices);
9095 }
jiabina84c3d32022-12-02 18:59:55 +00009096}
9097
jiabinc44b3462022-12-08 12:52:31 -08009098PortHandleVector AudioPolicyManager::getClientsForStream(
9099 audio_stream_type_t streamType) const {
9100 PortHandleVector clients;
9101 for (size_t i = 0; i < mOutputs.size(); ++i) {
9102 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9103 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9104 }
9105 return clients;
9106}
9107
9108void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9109 PortHandleVector clients;
9110 for (auto stream : streams) {
9111 PortHandleVector clientsForStream = getClientsForStream(stream);
9112 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9113 }
9114 mpClientInterface->invalidateTracks(clients);
9115}
9116
jiabin220eea12024-05-17 17:55:20 +00009117void AudioPolicyManager::updateClientsInternalMute(
9118 const sp<android::SwAudioOutputDescriptor> &desc) {
9119 if (!desc->isBitPerfect() ||
9120 !com::android::media::audioserver::
9121 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9122 // This is only used for bit perfect output now.
9123 return;
9124 }
9125 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9126 bool bitPerfectClientInternalMute = false;
9127 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9128 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9129 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9130 bitPerfectClient = client;
9131 continue;
9132 }
9133 bool muted = false;
9134 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9135 // System sound is muted.
9136 muted = true;
9137 } else {
9138 bitPerfectClientInternalMute = true;
9139 }
9140 if (client->setInternalMute(muted)) {
9141 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9142 if (!result.ok()) {
9143 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9144 continue;
9145 }
9146 media::TrackInternalMuteInfo info;
9147 info.portId = result.value();
9148 info.muted = client->getInternalMute();
9149 clientsInternalMute.push_back(std::move(info));
9150 }
9151 }
9152 if (bitPerfectClient != nullptr &&
9153 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9154 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9155 if (result.ok()) {
9156 media::TrackInternalMuteInfo info;
9157 info.portId = result.value();
9158 info.muted = bitPerfectClient->getInternalMute();
9159 clientsInternalMute.push_back(std::move(info));
9160 } else {
9161 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9162 __func__, bitPerfectClient->portId());
9163 }
9164 }
9165 if (!clientsInternalMute.empty()) {
9166 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9167 status != NO_ERROR) {
9168 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9169 }
9170 }
9171}
9172
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009173} // namespace android