blob: c290acddb098914bb1685af8a85ff5c6e86c70d3 [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 =
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001626 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output,
1627 attributes);
Eric Laurentc529cf62020-04-17 18:19:10 -07001628
1629 // only accept an output with the requested parameters
1630 if (status != NO_ERROR ||
1631 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1632 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1633 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1634 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1635 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1636 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1637 config->channel_mask, outputDesc->getChannelMask());
1638 if (*output != AUDIO_IO_HANDLE_NONE) {
1639 outputDesc->close();
1640 }
1641 // fall back to mixer output if possible when the direct output could not be open
1642 if (audio_is_linear_pcm(config->format) &&
1643 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1644 return NAME_NOT_FOUND;
1645 }
1646 *output = AUDIO_IO_HANDLE_NONE;
1647 return BAD_VALUE;
1648 }
1649 outputDesc->mDirectOpenCount = 1;
1650 outputDesc->mDirectClientSession = session;
1651
1652 addOutput(*output, outputDesc);
Eric Laurent0ca09402024-05-16 17:48:59 +00001653 setOutputDevices(__func__, outputDesc,
1654 devices,
1655 true,
1656 0,
1657 NULL);
Eric Laurentc529cf62020-04-17 18:19:10 -07001658 mPreviousOutputs = mOutputs;
1659 ALOGV("%s returns new direct output %d", __func__, *output);
1660 mpClientInterface->onAudioPortListUpdate();
1661 return NO_ERROR;
1662}
1663
François Gaffie11d30102018-11-02 16:09:09 +01001664audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1665 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001666 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001667 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001668 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001669 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001670 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001671 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001672 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001673{
Andy Hungc88b0642018-04-27 15:42:35 -07001674 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001675
jiabine375d412019-02-26 12:54:53 -08001676 // Discard haptic channel mask when forcing muting haptic channels.
1677 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001678 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1679 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001680
Eric Laurente552edb2014-03-10 17:42:56 -07001681 // open a direct output if required by specified parameters
1682 //force direct flag if offload flag is set: offloading implies a direct output stream
1683 // and all common behaviors are driven by checking only the direct flag
1684 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001685 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1686 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001687 }
Nadav Bar766fb022018-01-07 12:18:03 +02001688 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1689 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001690 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001691
1692 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1693
Eric Laurente83b55d2014-11-14 10:06:21 -08001694 // only allow deep buffering for music stream type
1695 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001696 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001697 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Mikhail Naganov285c1732024-09-05 17:26:50 -07001698 *flags == AUDIO_OUTPUT_FLAG_NONE && mConfig->useDeepBufferForMedia()) {
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001699 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001700 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001701 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001702 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001703 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001704 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001705 audio_is_linear_pcm(config->format) &&
1706 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001707 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001708 AUDIO_OUTPUT_FLAG_DIRECT);
1709 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001710 }
Eric Laurente552edb2014-03-10 17:42:56 -07001711
Carter Hsua3abb402021-10-26 11:11:20 +08001712 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1713 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1714 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1715 }
1716
Eric Laurentf9230d52024-01-26 18:49:09 +01001717 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao57b93392024-04-26 04:12:21 +00001718 // was specified and offload or direct playback is not explicitly requested, and there is no
1719 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001720 *isSpatialized = false;
Shunkai Yao57b93392024-04-26 04:12:21 +00001721 if (mSpatializerOutput != nullptr &&
1722 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1723 prefMixerConfigInfo == nullptr &&
1724 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1725 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001726 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001727 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001728 }
1729
Eric Laurentc529cf62020-04-17 18:19:10 -07001730 audio_config_t directConfig = *config;
1731 directConfig.channel_mask = channelMask;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07001732
1733 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output,
1734 *attr);
Eric Laurentc529cf62020-04-17 18:19:10 -07001735 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001736 return output;
1737 }
1738
Eric Laurent14cbfca2016-03-17 09:42:16 -07001739 // A request for HW A/V sync cannot fallback to a mixed output because time
1740 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001741 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001742 return AUDIO_IO_HANDLE_NONE;
1743 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001744 // A request for Tuner cannot fallback to a mixed output
1745 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1746 return AUDIO_IO_HANDLE_NONE;
1747 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001748
Eric Laurente552edb2014-03-10 17:42:56 -07001749 // ignoring channel mask due to downmix capability in mixer
1750
1751 // open a non direct output
1752
1753 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001754 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001755 // get which output is suitable for the specified stream. The actual
1756 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001757 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001758 if (prefMixerConfigInfo != nullptr) {
1759 for (audio_io_handle_t outputHandle : outputs) {
1760 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1761 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1762 output = outputHandle;
1763 break;
1764 }
1765 }
1766 if (output == AUDIO_IO_HANDLE_NONE) {
1767 // No output open with the preferred profile. Open a new one.
1768 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1769 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1770 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1771 config.format = prefMixerConfigInfo->getConfigBase().format;
1772 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1773 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1774 &config, prefMixerConfigInfo->getFlags());
1775 if (preferredOutput == nullptr) {
1776 ALOGE("%s failed to open output with preferred mixer config", __func__);
1777 } else {
1778 output = preferredOutput->mIoHandle;
1779 }
1780 }
1781 } else {
1782 // at this stage we should ignore the DIRECT flag as no direct output could be
1783 // found earlier
1784 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
jiabin220eea12024-05-17 17:55:20 +00001785 if (com::android::media::audioserver::
1786 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
1787 // If the preferred mixer attributes is null, do not select the bit-perfect output
1788 // unless the bit-perfect output is the only output.
1789 // The bit-perfect output can exist while the passed in preferred mixer attributes
1790 // info is null when it is a high priority client. The high priority clients are
1791 // ringtone or alarm, which is not a bit-perfect use case.
1792 size_t i = 0;
1793 while (i < outputs.size() && outputs.size() > 1) {
1794 auto desc = mOutputs.valueFor(outputs[i]);
1795 // The output descriptor must not be null here.
1796 if (desc->isBitPerfect()) {
1797 outputs.removeItemsAt(i);
1798 } else {
1799 i += 1;
1800 }
1801 }
1802 }
jiabina84c3d32022-12-02 18:59:55 +00001803 output = selectOutput(
1804 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1805 }
Eric Laurente552edb2014-03-10 17:42:56 -07001806 }
François Gaffie11d30102018-11-02 16:09:09 +01001807 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001808 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001809 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001810
Eric Laurente552edb2014-03-10 17:42:56 -07001811 return output;
1812}
1813
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001814sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001815 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1816 mAvailableInputDevices);
1817 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1818}
1819
1820DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1821 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1822 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001823}
1824
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001825const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001826 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001827 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1828 if (msdModule != 0) {
1829 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1830 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1831 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1832 const struct audio_port_config *source = &patch->mPatch.sources[j];
1833 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1834 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001835 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001836 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001837 }
1838 }
1839 }
1840 return msdPatches;
1841}
1842
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001843bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1844 ssize_t index = mAudioPatches.indexOfKey(handle);
1845 if (index < 0) {
1846 return false;
1847 }
1848 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1849 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1850 if (msdModule == nullptr) {
1851 return false;
1852 }
1853 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1854 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1855 return true;
1856 }
1857 index = getMsdOutputPatches().indexOfKey(handle);
1858 if (index < 0) {
1859 return false;
1860 }
1861 return true;
1862}
1863
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001864status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1865 const InputProfileCollection &inputProfiles,
1866 const OutputProfileCollection &outputProfiles,
1867 const sp<DeviceDescriptor> &sourceDevice,
1868 const sp<DeviceDescriptor> &sinkDevice,
1869 AudioProfileVector& sourceProfiles,
1870 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001871 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001872 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001873 return NO_INIT;
1874 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001875 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001876 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001877 return NO_INIT;
1878 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001879 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001880 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1881 inProfile->supportsDevice(sourceDevice)) {
1882 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001883 }
1884 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001885 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001886 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001887 outProfile->supportsDevice(sinkDevice)) {
1888 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001889 }
1890 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001891 return NO_ERROR;
1892}
1893
1894status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1895 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1896 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1897{
Dean Wheatley16809da2022-12-09 14:55:46 +11001898 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1899 static const std::vector<audio_format_t> formatsOrder = {{
1900 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001901 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1902 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001903 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1904 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1905 // preferred).
1906 std::vector<audio_channel_mask_t> masks = {{
1907 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1908 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1909 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1910 // insert index masks (higher counts most preferred) as preferred over position masks
1911 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1912 masks.insert(
1913 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1914 }
1915 return masks;
1916 }();
1917
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001918 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001919 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1920 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001921 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001922 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1923 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001924 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001925 }
1926 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1927 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1928 sinkConfig->format = bestSinkConfig.format;
1929 // For encoded streams force direct flag to prevent downstream mixing.
1930 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1931 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001932 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1933 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001934 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001935 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1936 // raw and IEC61937 framed streams.
1937 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1938 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1939 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001940 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1941 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001942 sourceConfig->channel_mask =
1943 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1944 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1945 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001946 sourceConfig->format = bestSinkConfig.format;
1947 // Copy input stream directly without any processing (e.g. resampling).
1948 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1949 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1950 if (hwAvSync) {
1951 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1952 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1953 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1954 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1955 }
1956 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1957 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1958 sinkConfig->config_mask |= config_mask;
1959 sourceConfig->config_mask |= config_mask;
1960 return NO_ERROR;
1961}
1962
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001963PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1964 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001965{
1966 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001967 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1968 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1969 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1970 if (deviceModule == nullptr) {
1971 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1972 return patchBuilder;
1973 }
1974 const InputProfileCollection inputProfiles = msdIsSource ?
1975 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1976 const OutputProfileCollection outputProfiles = msdIsSource ?
1977 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1978
1979 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1980 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1981 device : getMsdAudioOutDevices().itemAt(0);
1982 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1983
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001984 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1985 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001986 AudioProfileVector sourceProfiles;
1987 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001988 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1989 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001990 for (auto hwAvSync : { true, false }) {
1991 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1992 sourceProfiles, sinkProfiles) != NO_ERROR) {
1993 continue;
1994 }
1995 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1996 &sinkConfig) == NO_ERROR) {
1997 // Found a matching config. Re-create PatchBuilder with this config.
1998 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1999 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002000 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002001 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002002 " supporting PCM format conversion.", __func__);
2003 return patchBuilder;
2004}
2005
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002006status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11002007 DeviceVector devices;
2008 if (outputDevices != nullptr && outputDevices->size() > 0) {
2009 devices.add(*outputDevices);
2010 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002011 // Use media strategy for unspecified output device. This should only
2012 // occur on checkForDeviceAndOutputChanges(). Device connection events may
2013 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11002014 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01002015 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11002016 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002017 }
Michael Chan6fb34492020-12-08 15:44:49 +11002018 std::vector<PatchBuilder> patchesToCreate;
2019 for (auto i = 0u; i < devices.size(); ++i) {
2020 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002021 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11002022 }
2023 // Retain only the MSD patches associated with outputDevices request.
2024 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002025 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002026 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
2027 auto retainedPatch = false;
2028 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2029 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
2030 patchesToRemove.removeItemsAt(i);
2031 retainedPatch = true;
2032 break;
2033 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002034 }
Michael Chan6fb34492020-12-08 15:44:49 +11002035 if (retainedPatch) {
2036 it = patchesToCreate.erase(it);
2037 continue;
2038 }
2039 ++it;
2040 }
2041 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
2042 return NO_ERROR;
2043 }
2044 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
2045 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01002046 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002047 }
Michael Chan6fb34492020-12-08 15:44:49 +11002048 status_t status = NO_ERROR;
2049 for (const auto &p : patchesToCreate) {
2050 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
2051 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
2052 char message[256];
2053 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
2054 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
2055 currStatus == NO_ERROR ? "Success" : "Error",
2056 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
2057 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
2058 if (currStatus == NO_ERROR) {
2059 ALOGD("%s", message);
2060 } else {
2061 ALOGE("%s", message);
2062 if (status == NO_ERROR) {
2063 status = currStatus;
2064 }
2065 }
2066 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11002067 return status;
2068}
2069
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002070void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2071 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002072 for (size_t i = 0; i < msdPatches.size(); i++) {
2073 const auto& patch = msdPatches[i];
2074 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2075 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2076 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2077 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2078 releaseAudioPatch(patch->getHandle(), mUidCached);
2079 break;
2080 }
2081 }
2082 }
2083}
2084
Dorin Drimus94d94412022-02-02 09:05:02 +01002085bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002086 DeviceVector devicesToCheck =
2087 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002088 AudioPatchCollection msdPatches = getMsdOutputPatches();
2089 for (size_t i = 0; i < msdPatches.size(); i++) {
2090 const auto& patch = msdPatches[i];
2091 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2092 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2093 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2094 const auto& foundDevice = devicesToCheck.getDevice(
2095 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2096 if (foundDevice != nullptr) {
2097 devicesToCheck.remove(foundDevice);
2098 if (devicesToCheck.isEmpty()) {
2099 return true;
2100 }
2101 }
2102 }
2103 }
2104 }
2105 return false;
2106}
2107
Eric Laurente0720872014-03-11 09:30:41 -07002108audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002109 audio_output_flags_t flags,
2110 audio_format_t format,
2111 audio_channel_mask_t channelMask,
2112 uint32_t samplingRate,
2113 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002114{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002115 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2116 "%s called with format %#x", __func__, format);
2117
jiabinebb6af42020-06-09 17:31:17 -07002118 // Return the output that haptic-generating attached to when 1) session id is specified,
2119 // 2) haptic-generating effect exists for given session id and 3) the output that
2120 // haptic-generating effect attached to is in given outputs.
2121 if (sessionId != AUDIO_SESSION_NONE) {
2122 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2123 sessionId, FX_IID_HAPTICGENERATOR);
2124 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2125 return hapticGeneratingOutput;
2126 }
2127 }
2128
Eric Laurent16c66dd2019-05-01 17:54:10 -07002129 // Flags disqualifying an output: the match must happen before calling selectOutput()
2130 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2131 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2132
2133 // Flags expressing a functional request: must be honored in priority over
2134 // other criteria
2135 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2136 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002137 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2138 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002139 // Flags expressing a performance request: have lower priority than serving
2140 // requested sampling rate or channel mask
2141 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2142 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2143 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2144
2145 const audio_output_flags_t functionalFlags =
2146 (audio_output_flags_t)(flags & kFunctionalFlags);
2147 const audio_output_flags_t performanceFlags =
2148 (audio_output_flags_t)(flags & kPerformanceFlags);
2149
2150 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2151
Eric Laurente552edb2014-03-10 17:42:56 -07002152 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002153 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002154 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002155 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002156 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002157 // with tiebreak preferring the minimum number of extra functional flags
2158 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002159 // 3: the output supporting the exact channel mask
2160 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002161 // 5: the output with the highest sampling rate if the requested sample rate is
2162 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002163 // 6: the output with the highest number of requested performance flags
2164 // 7: the output with the bit depth the closest to the requested one
2165 // 8: the primary output
2166 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002167
Eric Laurent16c66dd2019-05-01 17:54:10 -07002168 // matching criteria values in priority order for best matching output so far
2169 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002170
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002171 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002172 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2173 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2174 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002175
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002176 for (audio_io_handle_t output : outputs) {
2177 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002178 // matching criteria values in priority order for current output
2179 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002180
Eric Laurent16c66dd2019-05-01 17:54:10 -07002181 if (outputDesc->isDuplicated()) {
2182 continue;
2183 }
2184 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2185 continue;
2186 }
Eric Laurent8838a382014-09-08 16:44:28 -07002187
Eric Laurent16c66dd2019-05-01 17:54:10 -07002188 // If haptic channel is specified, use the haptic output if present.
2189 // When using haptic output, same audio format and sample rate are required.
2190 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002191 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao808da212024-04-05 22:50:56 +00002192 // skip if haptic channel specified but output does not support it, or output support haptic
2193 // but there is no haptic channel requested AND no orphan haptic effect exist
2194 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2195 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002196 continue;
2197 }
Shunkai Yao808da212024-04-05 22:50:56 +00002198 // In the case of audio-coupled-haptic playback, there is no format conversion and
2199 // resampling in the framework, same format/channel/sampleRate for client and the output
2200 // thread is required. In the case of HapticGenerator effect, do not require format
2201 // matching.
2202 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2203 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao57b93392024-04-26 04:12:21 +00002204 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao808da212024-04-05 22:50:56 +00002205 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002206 }
2207
2208 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002209 const int matchingFunctionalFlags =
2210 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2211 const int totalFunctionalFlags =
2212 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2213 // Prefer matching functional flags, but subtract unnecessary functional flags.
2214 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002215
2216 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002217 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2218 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002219 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2220 channelCount <= outputChannelCount) {
2221 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002222 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2223 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002224 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002225 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002226 currentMatchCriteria[3] = outputChannelCount;
2227 }
2228
2229 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002230 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002231 int diff; // avoid unsigned integer overflow.
2232 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2233
2234 // prefer the closest output sampling rate greater than or equal to target
2235 // if none exists, prefer the closest output sampling rate less than target.
2236 //
2237 // criteria is offset to make non-negative.
2238 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002239 }
2240
2241 // performance flags match
2242 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2243
2244 // format match
2245 if (format != AUDIO_FORMAT_INVALID) {
2246 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002247 PolicyAudioPort::kFormatDistanceMax -
2248 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002249 }
2250
2251 // primary output match
2252 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2253
2254 // compare match criteria by priority then value
2255 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2256 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2257 bestMatchCriteria = currentMatchCriteria;
2258 bestOutput = output;
2259
2260 std::stringstream result;
2261 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2262 std::ostream_iterator<int>(result, " "));
2263 ALOGV("%s new bestOutput %d criteria %s",
2264 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002265 }
2266 }
2267
Eric Laurent16c66dd2019-05-01 17:54:10 -07002268 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002269}
2270
Eric Laurent8fc147b2018-07-22 19:13:55 -07002271status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002272{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002273 ALOGV("%s portId %d", __FUNCTION__, portId);
2274
2275 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2276 if (outputDesc == 0) {
2277 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002278 return BAD_VALUE;
2279 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002280 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002281
Eric Laurent8fc147b2018-07-22 19:13:55 -07002282 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002283 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002284
jiabin220eea12024-05-17 17:55:20 +00002285 if (com::android::media::audioserver::fix_concurrent_playback_behavior_with_bit_perfect_client()
2286 && gHighPriorityUseCases.count(client->attributes().usage) != 0
2287 && outputDesc->isBitPerfect()) {
2288 // Usually, APM selects bit-perfect output for high priority use cases only when
2289 // bit-perfect output is the only output that can be routed to the selected device.
2290 // However, here is no need to play high priority use cases such as ringtone and alarm
2291 // on the bit-perfect path. Reopen the output and return DEAD_OBJECT so that the client
2292 // can attach to new output.
2293 ALOGD("%s: reopen bit-perfect output as high priority use case(%d) is starting",
2294 __func__, client->stream());
2295 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2296 return DEAD_OBJECT;
2297 }
2298
Eric Laurent733ce942017-12-07 12:18:25 -08002299 status_t status = outputDesc->start();
2300 if (status != NO_ERROR) {
2301 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002302 }
2303
Eric Laurent97ac8712018-07-27 18:59:02 -07002304 uint32_t delayMs;
2305 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002306
2307 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002308 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002309 if (status == DEAD_OBJECT) {
2310 sp<SwAudioOutputDescriptor> desc =
2311 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2312 if (desc == nullptr) {
2313 // This is not common, it may indicate something wrong with the HAL.
2314 ALOGE("%s unable to open output with default config", __func__);
2315 return status;
2316 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002317 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002318 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002319 }
jiabina84c3d32022-12-02 18:59:55 +00002320
2321 // If the client is the first one active on preferred mixer parameters, reopen the output
2322 // if the current mixer parameters doesn't match the preferred one.
2323 if (outputDesc->devices().size() == 1) {
2324 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2325 outputDesc->devices()[0]->getId(), client->strategy());
2326 if (info != nullptr && info->getUid() == client->uid()) {
2327 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2328 info->getConfigBase(), info->getFlags())) {
2329 stopSource(outputDesc, client);
2330 outputDesc->stop();
2331 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2332 config.channel_mask = info->getConfigBase().channel_mask;
2333 config.sample_rate = info->getConfigBase().sample_rate;
2334 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002335 sp<SwAudioOutputDescriptor> desc =
2336 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2337 if (desc == nullptr) {
2338 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002339 }
jiabin220eea12024-05-17 17:55:20 +00002340 desc->mPreferredAttrInfo = info;
jiabina84c3d32022-12-02 18:59:55 +00002341 // Intentionally return error to let the client side resending request for
2342 // creating and starting.
2343 return DEAD_OBJECT;
2344 }
2345 info->increaseActiveClient();
jiabin220eea12024-05-17 17:55:20 +00002346 if (info->getActiveClientCount() == 1 && info->isBitPerfect()) {
jiabine3d1f552023-06-14 17:42:17 +00002347 // If it is first bit-perfect client, reroute all clients that will be routed to
2348 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2349 PortHandleVector clientsToInvalidate;
2350 for (size_t i = 0; i < mOutputs.size(); i++) {
2351 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002352 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002353 continue;
2354 }
2355 for (const auto& c : mOutputs[i]->getClientIterable()) {
2356 clientsToInvalidate.push_back(c->portId());
2357 }
2358 }
2359 if (!clientsToInvalidate.empty()) {
2360 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2361 __func__);
2362 mpClientInterface->invalidateTracks(clientsToInvalidate);
2363 }
2364 }
jiabina84c3d32022-12-02 18:59:55 +00002365 }
2366 }
2367
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002368 if (client->hasPreferredDevice()) {
2369 // playback activity with preferred device impacts routing occurred, inform upper layers
2370 mpClientInterface->onRoutingUpdated();
2371 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002372 if (delayMs != 0) {
2373 usleep(delayMs * 1000);
2374 }
2375
jiabin220eea12024-05-17 17:55:20 +00002376 if (status == NO_ERROR &&
2377 outputDesc->mPreferredAttrInfo != nullptr &&
2378 outputDesc->isBitPerfect() &&
2379 com::android::media::audioserver::
2380 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
2381 // A new client is started on bit-perfect output, update all clients internal mute.
2382 updateClientsInternalMute(outputDesc);
2383 }
2384
Eric Laurentc75307b2015-03-17 15:29:32 -07002385 return status;
2386}
2387
Eric Laurent96d1dda2022-03-14 17:14:19 +01002388bool AudioPolicyManager::isLeUnicastActive() const {
2389 if (isInCall()) {
2390 return true;
2391 }
2392 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2393}
2394
2395bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2396 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2397 return false;
2398 }
2399 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2400 ALOGV("%s active %d", __func__, active);
2401 return active;
2402}
2403
Eric Laurent97ac8712018-07-27 18:59:02 -07002404status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2405 const sp<TrackClientDescriptor>& client,
2406 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002407{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002408 // cannot start playback of STREAM_TTS if any other output is being used
2409 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002410
2411 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002412 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002413 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002414 auto clientStrategy = client->strategy();
2415 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002416 if (stream == AUDIO_STREAM_TTS) {
2417 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002418 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002419 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002420 return INVALID_OPERATION;
2421 } else {
2422 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2423 }
2424 } else {
2425 // some playback other than beacon starts
2426 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2427 }
2428
Eric Laurent77305a62016-07-25 16:39:22 -07002429 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002430 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002431 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002432
François Gaffie11d30102018-11-02 16:09:09 +01002433 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002434 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002435 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002436 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002437 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002438 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002439 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002440 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002441 } else {
2442 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002443 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002444 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2445 AUDIO_FORMAT_DEFAULT);
2446 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2447 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002448 }
2449
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002450 // requiresMuteCheck is false when we can bypass mute strategy.
2451 // It covers a common case when there is no materially active audio
2452 // and muting would result in unnecessary delay and dropped audio.
2453 const uint32_t outputLatencyMs = outputDesc->latency();
2454 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002455 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002456
Eric Laurente552edb2014-03-10 17:42:56 -07002457 // increment usage count for this stream on the requested output:
2458 // NOTE that the usage count is the same for duplicated output and hardware output which is
2459 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002460 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002461
2462 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002463 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002464 // Preferred device may be exclusive, use only if no other active clients on this output
2465 devices = DeviceVector(
2466 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2467 } else {
2468 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2469 }
François Gaffie11d30102018-11-02 16:09:09 +01002470 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002471 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002472 }
2473 }
Eric Laurente552edb2014-03-10 17:42:56 -07002474
François Gaffiec005e562018-11-06 15:04:49 +01002475 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002476 selectOutputForMusicEffects();
2477 }
2478
François Gaffie1c878552018-11-22 16:53:21 +01002479 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002480 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002481 if (devices.isEmpty()) {
2482 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002483 }
François Gaffiec005e562018-11-06 15:04:49 +01002484 bool shouldWait =
2485 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2486 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2487 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002488 uint32_t waitMs = beaconMuteLatency;
jiabin220eea12024-05-17 17:55:20 +00002489 const bool needToCloseBitPerfectOutput =
2490 (com::android::media::audioserver::
2491 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2492 gHighPriorityUseCases.count(clientAttr.usage) != 0);
2493 std::vector<sp<SwAudioOutputDescriptor>> outputsToReopen;
Eric Laurente552edb2014-03-10 17:42:56 -07002494 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002495 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002496 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002497 // An output has a shared device if
2498 // - managed by the same hw module
2499 // - supports the currently selected device
2500 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002501 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002502
Eric Laurent77305a62016-07-25 16:39:22 -07002503 // force a device change if any other output is:
2504 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002505 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002506 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002507 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002508 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002509 // change the device currently selected by the other output.
2510 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002511 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002512 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002513 force = true;
2514 }
2515 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002516 // a notification so that audio focus effect can propagate, or that a mute/unmute
2517 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002518 const uint32_t latencyMs = desc->latency();
2519 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2520
2521 if (shouldWait && isActive && (waitMs < latencyMs)) {
2522 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002523 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002524
2525 // Require mute check if another output is on a shared device
2526 // and currently active to have proper drain and avoid pops.
2527 // Note restoring AudioTracks onto this output needs to invoke
2528 // a volume ramp if there is no mute.
2529 requiresMuteCheck |= sharedDevice && isActive;
jiabin220eea12024-05-17 17:55:20 +00002530
2531 if (needToCloseBitPerfectOutput && desc->isBitPerfect()) {
2532 outputsToReopen.push_back(desc);
2533 }
Eric Laurente552edb2014-03-10 17:42:56 -07002534 }
2535 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002536
jiabin220eea12024-05-17 17:55:20 +00002537 if (outputDesc->mPreferredAttrInfo != nullptr && devices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002538 // If the output is open with preferred mixer attributes, but the routed device is
2539 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2540 // changed.
2541 return DEAD_OBJECT;
2542 }
jiabin220eea12024-05-17 17:55:20 +00002543 for (auto& outputToReopen : outputsToReopen) {
2544 reopenOutput(outputToReopen, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2545 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002546 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302547 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2548 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002549
Eric Laurente552edb2014-03-10 17:42:56 -07002550 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002551 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002552 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002553 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002554 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002555 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002556 outputDesc->useHwGain() /*force*/)) {
2557 // request AudioService to reinitialize the volume curves asynchronously
2558 ALOGE("checkAndSetVolume failed, requesting volume range init");
2559 mpClientInterface->onVolumeRangeInitRequest();
2560 };
Eric Laurente552edb2014-03-10 17:42:56 -07002561
2562 // update the outputs if starting an output with a stream that can affect notification
2563 // routing
2564 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002565
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002566 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002567 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002568 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002569 }
Eric Laurentdc462862016-07-19 12:29:53 -07002570
2571 if (waitMs > muteWaitMs) {
2572 *delayMs = waitMs - muteWaitMs;
2573 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002574
2575 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2576 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2577 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2578 // change occurs after the MixerThread starts and causes a stream volume
2579 // glitch.
2580 //
2581 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002582 }
Eric Laurentdc462862016-07-19 12:29:53 -07002583
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002584 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002585 mEngine->getForceUse(
2586 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002587 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002588 }
2589
Eric Laurent97ac8712018-07-27 18:59:02 -07002590 // Automatically enable the remote submix input when output is started on a re routing mix
2591 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002592 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2593 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002594 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2595 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2596 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002597 "remote-submix",
2598 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002599 }
2600
Eric Laurent96d1dda2022-03-14 17:14:19 +01002601 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2602
Eric Laurente552edb2014-03-10 17:42:56 -07002603 return NO_ERROR;
2604}
2605
Eric Laurent96d1dda2022-03-14 17:14:19 +01002606void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2607 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2608 bool isUnicastActive = isLeUnicastActive();
2609
2610 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002611 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002612 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2613 for (size_t i = 0; i < mOutputs.size(); i++) {
2614 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2615 if (desc != ignoredOutput && desc->isActive()
2616 && ((isUnicastActive &&
2617 !desc->devices().
2618 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2619 || (wasUnicastActive &&
2620 !desc->devices().getDevicesFromTypes(
2621 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2622 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2623 bool force = desc->devices() != newDevices;
jiabin220eea12024-05-17 17:55:20 +00002624 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002625 // If the device is using preferred mixer attributes, the output need to reopen
2626 // with default configuration when the new selected devices are different from
2627 // current routing devices.
2628 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2629 continue;
2630 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302631 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002632 // re-apply device specific volume if not done by setOutputDevice()
2633 if (!force) {
2634 applyStreamVolumes(desc, newDevices.types(), delayMs);
2635 }
2636 }
2637 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002638 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002639 }
2640}
2641
Eric Laurent8fc147b2018-07-22 19:13:55 -07002642status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002643{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002644 ALOGV("%s portId %d", __FUNCTION__, portId);
2645
2646 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2647 if (outputDesc == 0) {
2648 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002649 return BAD_VALUE;
2650 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002651 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002652
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002653 if (client->hasPreferredDevice(true)) {
2654 // playback activity with preferred device impacts routing occurred, inform upper layers
2655 mpClientInterface->onRoutingUpdated();
2656 }
2657
Eric Laurent97ac8712018-07-27 18:59:02 -07002658 ALOGV("stopOutput() output %d, stream %d, session %d",
2659 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002660
Eric Laurent97ac8712018-07-27 18:59:02 -07002661 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002662
Eric Laurent733ce942017-12-07 12:18:25 -08002663 if (status == NO_ERROR ) {
2664 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002665 } else {
2666 return status;
2667 }
2668
2669 if (outputDesc->devices().size() == 1) {
2670 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2671 outputDesc->devices()[0]->getId(), client->strategy());
jiabin220eea12024-05-17 17:55:20 +00002672 bool outputReopened = false;
jiabina84c3d32022-12-02 18:59:55 +00002673 if (info != nullptr && info->getUid() == client->uid()) {
2674 info->decreaseActiveClient();
2675 if (info->getActiveClientCount() == 0) {
2676 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
jiabin220eea12024-05-17 17:55:20 +00002677 outputReopened = true;
jiabina84c3d32022-12-02 18:59:55 +00002678 }
2679 }
jiabin220eea12024-05-17 17:55:20 +00002680 if (com::android::media::audioserver::
2681 fix_concurrent_playback_behavior_with_bit_perfect_client() &&
2682 !outputReopened && outputDesc->isBitPerfect()) {
2683 // Only need to update the clients' internal mute when the output is bit-perfect and it
2684 // is not reopened.
2685 updateClientsInternalMute(outputDesc);
2686 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002687 }
2688 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002689}
2690
Eric Laurent97ac8712018-07-27 18:59:02 -07002691status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2692 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002693{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002694 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002695 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002696 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002697 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002698
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002699 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2700
François Gaffie1c878552018-11-22 16:53:21 +01002701 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2702 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002703 // Automatically disable the remote submix input when output is stopped on a
2704 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002705 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002706 if (isSingleDeviceType(
2707 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002708 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002709 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002710 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2711 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002712 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002713 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002714 }
2715 }
2716 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002717 if (client->hasPreferredDevice(true) &&
2718 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002719 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002720 forceDeviceUpdate = true;
2721 }
2722
Eric Laurente552edb2014-03-10 17:42:56 -07002723 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002724 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002725
Eric Laurente552edb2014-03-10 17:42:56 -07002726 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002727 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002728 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002729 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002730
2731 // If the routing does not change, if an output is routed on a device using HwGain
2732 // (aka setAudioPortConfig) and there are still active clients following different
2733 // volume group(s), force reapply volume
2734 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2735 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2736
Eric Laurente552edb2014-03-10 17:42:56 -07002737 // delay the device switch by twice the latency because stopOutput() is executed when
2738 // the track stop() command is received and at that time the audio track buffer can
2739 // still contain data that needs to be drained. The latency only covers the audio HAL
2740 // and kernel buffers. Also the latency does not always include additional delay in the
2741 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302742 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002743 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002744
2745 // force restoring the device selection on other active outputs if it differs from the
2746 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002747 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002748 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002749 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002750 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002751 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002752 desc->isActive() &&
2753 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002754 (newDevices != desc->devices())) {
2755 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2756 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002757
jiabin220eea12024-05-17 17:55:20 +00002758 if (desc->mPreferredAttrInfo != nullptr && force) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002759 // If the device is using preferred mixer attributes, the output need to
2760 // reopen with default configuration when the new selected devices are
2761 // different from current routing devices.
2762 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2763 continue;
2764 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302765 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002766
Eric Laurent57de36c2016-09-28 16:59:11 -07002767 // re-apply device specific volume if not done by setOutputDevice()
2768 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002769 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002770 }
Eric Laurente552edb2014-03-10 17:42:56 -07002771 }
2772 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002773 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002774 // update the outputs if stopping one with a stream that can affect notification routing
2775 handleNotificationRoutingForStream(stream);
2776 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002777
2778 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2779 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002780 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002781 }
2782
François Gaffiec005e562018-11-06 15:04:49 +01002783 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002784 selectOutputForMusicEffects();
2785 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002786
2787 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2788
Eric Laurente552edb2014-03-10 17:42:56 -07002789 return NO_ERROR;
2790 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002791 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002792 return INVALID_OPERATION;
2793 }
2794}
2795
jiabinbce0c1d2020-10-05 11:20:18 -07002796bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002797{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002798 ALOGV("%s portId %d", __FUNCTION__, portId);
2799
2800 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2801 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002802 // If an output descriptor is closed due to a device routing change,
2803 // then there are race conditions with releaseOutput from tracks
2804 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2805 // destroyed shortly thereafter.
2806 //
2807 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002808 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002809 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002810 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002811
2812 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002813
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302814 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2815 if (outputDesc->isClientActive(client)) {
2816 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2817 stopOutput(portId);
2818 }
2819
Eric Laurent8fc147b2018-07-22 19:13:55 -07002820 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2821 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002822 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002823 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002824 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002825 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002826 if (--outputDesc->mDirectOpenCount == 0) {
2827 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002828 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002829 }
2830 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302831
Andy Hung39efb7a2018-09-26 15:39:28 -07002832 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002833 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2834 // The output is pending reopened to query dynamic profiles and
2835 // there is no active clients
2836 closeOutput(outputDesc->mIoHandle);
2837 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2838 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2839 if (newOutputDesc == nullptr) {
2840 ALOGE("%s failed to open output", __func__);
2841 }
2842 return true;
2843 }
2844 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002845}
2846
Eric Laurentcaf7f482014-11-25 17:50:47 -08002847status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2848 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002849 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002850 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002851 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002852 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002853 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002854 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002855 input_type_t *inputType,
Marvin Ramine5a122d2023-12-07 13:57:59 +01002856 audio_port_handle_t *portId,
2857 uint32_t *virtualDeviceId)
Eric Laurente552edb2014-03-10 17:42:56 -07002858{
François Gaffiec005e562018-11-06 15:04:49 +01002859 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002860 "flags %#x attributes=%s requested device ID %d",
2861 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2862 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002863
Eric Laurentad2e7b92017-09-14 20:06:42 -07002864 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002865 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002866 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002867 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002868 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002869 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002870 sp<RecordClientDescriptor> clientDesc;
2871 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002872 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002873 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002874
2875 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2876 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2877 return INVALID_OPERATION;
2878 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002879
Francois Gaffie716e1432019-01-14 16:58:59 +01002880 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2881 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002882 }
2883
Paul McLean466dc8e2015-04-17 13:15:36 -06002884 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002885 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002886 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002887
Eric Laurentad2e7b92017-09-14 20:06:42 -07002888 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2889 // possible
2890 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2891 *input != AUDIO_IO_HANDLE_NONE) {
2892 ssize_t index = mInputs.indexOfKey(*input);
2893 if (index < 0) {
2894 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2895 status = BAD_VALUE;
2896 goto error;
2897 }
2898 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002899 RecordClientVector clients = inputDesc->getClientsForSession(session);
2900 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002901 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2902 status = BAD_VALUE;
2903 goto error;
2904 }
2905 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2906 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002907 // corresponds to a new client and is only permitted from the same UID.
2908 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002909 if (clients.size() > 1) {
2910 for (const auto& client : clients) {
2911 // The client map is ordered by key values (portId) and portIds are allocated
2912 // incrementaly. So the first client in this list is the one opened by audio flinger
2913 // when the mmap stream is created and should be ignored as it does not correspond
2914 // to an actual client
2915 if (client == *clients.cbegin()) {
2916 continue;
2917 }
2918 if (uid != client->uid() && !client->isSilenced()) {
2919 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2920 uid, client->portId(), client->uid());
2921 status = INVALID_OPERATION;
2922 goto error;
2923 }
Eric Laurent331679c2018-04-16 17:03:16 -07002924 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002925 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002926 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002927 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002928
Eric Laurentfecbceb2021-02-09 14:46:43 +01002929 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002930 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002931 }
2932
2933 *input = AUDIO_IO_HANDLE_NONE;
2934 *inputType = API_INPUT_INVALID;
2935
Francois Gaffie716e1432019-01-14 16:58:59 +01002936 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002937 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002938 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002939 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002940 ALOGW("%s could not find input mix for attr %s",
2941 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002942 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002943 }
jiabinc1de2df2019-05-07 14:26:40 -07002944 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2945 String8(attr->tags + strlen("addr=")),
2946 AUDIO_FORMAT_DEFAULT);
2947 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002948 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002949 __func__, attributes.source, attributes.tags);
2950 status = BAD_VALUE;
2951 goto error;
2952 }
2953
Kevin Rocard25f9b052019-02-27 15:08:54 -08002954 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2955 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2956 } else {
2957 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2958 }
Marvin Ramine5a122d2023-12-07 13:57:59 +01002959 if (virtualDeviceId) {
2960 *virtualDeviceId = policyMix->mVirtualDeviceId;
2961 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002962 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002963 if (explicitRoutingDevice != nullptr) {
2964 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002965 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002966 // Prevent from storing invalid requested device id in clients
2967 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002968 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002969 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2970 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002971 }
François Gaffie11d30102018-11-02 16:09:09 +01002972 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002973 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002974 status = BAD_VALUE;
2975 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002976 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002977 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2978 *inputType = API_INPUT_MIX_CAPTURE;
2979 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002980 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2981 // there is an external policy, but this input is attached to a mix of recorders,
2982 // meaning it receives audio injected into the framework, so the recorder doesn't
2983 // know about it and is therefore considered "legacy"
2984 *inputType = API_INPUT_LEGACY;
Marvin Ramine5a122d2023-12-07 13:57:59 +01002985
2986 if (virtualDeviceId) {
2987 *virtualDeviceId = policyMix->mVirtualDeviceId;
2988 }
François Gaffie11d30102018-11-02 16:09:09 +01002989 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002990 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002991 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002992 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002993 } else {
2994 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002995 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002996
Eric Laurent599c7582015-12-07 18:05:55 -08002997 }
2998
François Gaffiec005e562018-11-06 15:04:49 +01002999 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08003000 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07003001 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07003002 AudioProfileVector profiles;
3003 status_t ret = getProfilesForDevices(
3004 DeviceVector(device), profiles, flags, true /*isInput*/);
3005 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00003006 const auto channels = profiles[0]->getChannels();
3007 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
3008 config->channel_mask = *channels.begin();
3009 }
3010 const auto sampleRates = profiles[0]->getSampleRates();
3011 if (!sampleRates.empty() &&
3012 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
3013 config->sample_rate = *sampleRates.begin();
3014 }
jiabinf1c73972022-04-14 16:28:52 -07003015 config->format = profiles[0]->getFormat();
3016 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07003017 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08003018 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08003019
Marvin Ramine5a122d2023-12-07 13:57:59 +01003020
3021 if (policyMix != nullptr && virtualDeviceId != nullptr) {
3022 *virtualDeviceId = policyMix->mVirtualDeviceId;
3023 }
3024
Eric Laurent8f42ea12018-08-08 09:08:25 -07003025exit:
3026
François Gaffiec005e562018-11-06 15:04:49 +01003027 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
3028 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07003029
Francois Gaffie716e1432019-01-14 16:58:59 +01003030 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08003031 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07003032 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003033
Mikhail Naganov2996f672019-04-18 12:29:59 -07003034 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01003035 requestedDeviceId, attributes.source, flags,
3036 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003037 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01003038 // Move (if found) effect for the client session to its input
3039 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003040 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003041
3042 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
3043 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07003044
Eric Laurent599c7582015-12-07 18:05:55 -08003045 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07003046
3047error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07003048 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08003049}
3050
3051
François Gaffie11d30102018-11-02 16:09:09 +01003052audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08003053 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01003054 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07003055 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08003056 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003057 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08003058{
3059 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01003060 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08003061 bool isSoundTrigger = false;
3062
François Gaffiec005e562018-11-06 15:04:49 +01003063 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08003064 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
3065 if (index >= 0) {
3066 input = mSoundTriggerSessions.valueFor(session);
3067 isSoundTrigger = true;
3068 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
3069 ALOGV("SoundTrigger capture on session %d input %d", session, input);
3070 } else {
3071 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07003072 }
François Gaffiec005e562018-11-06 15:04:49 +01003073 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08003074 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07003075 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07003076 }
3077
Carter Hsua3abb402021-10-26 11:11:20 +08003078 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
3079 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
3080 }
3081
Eric Laurentfe231122017-11-17 17:48:06 -08003082 // sampling rate and flags may be updated by getInputProfile
3083 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
3084 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00003085 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08003086 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07003087 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00003088 // find a compatible input profile (not necessarily identical in parameters)
3089 sp<IOProfile> profile = getInputProfile(
3090 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
3091 if (profile == nullptr) {
3092 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003093 }
jiabin2fd710d2022-05-02 23:20:22 +00003094
Glenn Kasten05ddca52016-02-11 08:17:12 -08003095 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08003096 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08003097 if (samplingRate == 0) {
3098 samplingRate = profileSamplingRate;
3099 }
Eric Laurente552edb2014-03-10 17:42:56 -07003100
Eric Laurent322b4d22015-04-03 15:57:54 -07003101 if (profile->getModuleHandle() == 0) {
3102 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08003103 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07003104 }
3105
Eric Laurentec376dc2021-04-08 20:41:22 +02003106 // Reuse an already opened input if a client with the same session ID already exists
3107 // on that input
3108 for (size_t i = 0; i < mInputs.size(); i++) {
3109 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
3110 if (desc->mProfile != profile) {
3111 continue;
3112 }
3113 RecordClientVector clients = desc->clientsList();
3114 for (const auto &client : clients) {
3115 if (session == client->session()) {
3116 return desc->mIoHandle;
3117 }
3118 }
3119 }
3120
Eric Laurent3974e3b2017-12-07 17:58:43 -08003121 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08003122 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003123 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003124 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003125 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003126 continue;
3127 }
3128 // if sound trigger, reuse input if used by other sound trigger on same session
3129 // else
3130 // reuse input if active client app is not in IDLE state
3131 //
3132 RecordClientVector clients = desc->clientsList();
3133 bool doClose = false;
3134 for (const auto& client : clients) {
3135 if (isSoundTrigger != client->isSoundTrigger()) {
3136 continue;
3137 }
3138 if (client->isSoundTrigger()) {
3139 if (session == client->session()) {
3140 return desc->mIoHandle;
3141 }
3142 continue;
3143 }
3144 if (client->active() && client->appState() != APP_STATE_IDLE) {
3145 return desc->mIoHandle;
3146 }
3147 doClose = true;
3148 }
3149 if (doClose) {
3150 closeInput(desc->mIoHandle);
3151 } else {
3152 i++;
3153 }
3154 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003155 }
3156
Eric Laurentfe231122017-11-17 17:48:06 -08003157 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003158
Eric Laurentfe231122017-11-17 17:48:06 -08003159 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3160 lConfig.sample_rate = profileSamplingRate;
3161 lConfig.channel_mask = profileChannelMask;
3162 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003163
François Gaffie11d30102018-11-02 16:09:09 +01003164 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003165
3166 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003167 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003168 (profileSamplingRate != lConfig.sample_rate) ||
3169 !audio_formats_match(profileFormat, lConfig.format) ||
3170 (profileChannelMask != lConfig.channel_mask)) {
3171 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003172 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003173 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003174 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003175 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003176 }
Eric Laurent599c7582015-12-07 18:05:55 -08003177 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003178 }
3179
Eric Laurentc722f302014-12-10 11:21:49 -08003180 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003181
Eric Laurent599c7582015-12-07 18:05:55 -08003182 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003183 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003184
Eric Laurent599c7582015-12-07 18:05:55 -08003185 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003186}
3187
Eric Laurent4eb58f12018-12-07 16:41:02 -08003188status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003189{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003190 ALOGV("%s portId %d", __FUNCTION__, portId);
3191
3192 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3193 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003194 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003195 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003196 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003197 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003198 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003199 if (client->active()) {
3200 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3201 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003202 }
3203
Eric Laurent8f42ea12018-08-08 09:08:25 -07003204 audio_session_t session = client->session();
3205
Eric Laurent4eb58f12018-12-07 16:41:02 -08003206 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003207
Eric Laurent4eb58f12018-12-07 16:41:02 -08003208 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003209
Eric Laurent4eb58f12018-12-07 16:41:02 -08003210 status_t status = inputDesc->start();
3211 if (status != NO_ERROR) {
3212 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003213 }
Eric Laurente552edb2014-03-10 17:42:56 -07003214
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003215 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003216 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003217 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003218
Eric Laurent8f42ea12018-08-08 09:08:25 -07003219 // indicate active capture to sound trigger service if starting capture from a mic on
3220 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003221 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003222 if (device != nullptr) {
3223 status = setInputDevice(input, device, true /* force */);
3224 } else {
3225 ALOGW("%s no new input device can be found for descriptor %d",
3226 __FUNCTION__, inputDesc->getId());
3227 status = BAD_VALUE;
3228 }
Eric Laurente552edb2014-03-10 17:42:56 -07003229
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003230 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003231 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003232 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003233 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003234 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3235 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003236 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003237 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003238
François Gaffie11d30102018-11-02 16:09:09 +01003239 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3240 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003241 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003242 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003243 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003244
Eric Laurent8f42ea12018-08-08 09:08:25 -07003245 // automatically enable the remote submix output when input is started if not
3246 // used by a policy mix of type MIX_TYPE_RECORDERS
3247 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003248 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003249 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003250 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003251 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003252 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3253 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003254 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003255 if (address != "") {
3256 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3257 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003258 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003259 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003260 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003261 } else if (status != NO_ERROR) {
3262 // Restore client activity state.
3263 inputDesc->setClientActive(client, false);
3264 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003265 }
3266
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003267 ALOGV("%s input %d source = %d status = %d exit",
3268 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003269
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003270 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003271}
3272
Eric Laurent8fc147b2018-07-22 19:13:55 -07003273status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003274{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003275 ALOGV("%s portId %d", __FUNCTION__, portId);
3276
3277 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3278 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003279 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003280 return BAD_VALUE;
3281 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003282 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003283 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003284 if (!client->active()) {
3285 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003286 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003287 }
Carter Hsue6139d52021-07-08 10:30:20 +08003288 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003289 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003290
Eric Laurent8f42ea12018-08-08 09:08:25 -07003291 inputDesc->stop();
3292 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003293 auto current_source = inputDesc->source();
3294 setInputDevice(input, getNewInputDevice(inputDesc),
3295 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003296 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003297 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003298 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003299 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003300 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3301 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003302 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003303 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003304
3305 // automatically disable the remote submix output when input is stopped if not
3306 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003307 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003308 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003309 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003310 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003311 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3312 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003313 }
3314 if (address != "") {
3315 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3316 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003317 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003318 }
3319 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003320 resetInputDevice(input);
3321
3322 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3323 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003324 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3325 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003326 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003327 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003328 }
3329 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003330 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003331 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003332}
3333
Eric Laurent8fc147b2018-07-22 19:13:55 -07003334void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003335{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003336 ALOGV("%s portId %d", __FUNCTION__, portId);
3337
3338 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3339 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003340 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003341 return;
3342 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003343 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003344 audio_io_handle_t input = inputDesc->mIoHandle;
3345
Eric Laurent8f42ea12018-08-08 09:08:25 -07003346 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003347
Andy Hung39efb7a2018-09-26 15:39:28 -07003348 inputDesc->removeClient(portId);
Eric Laurentc03ada62024-03-21 14:02:22 +00003349
3350 // If no more clients are present in this session, park effects to an orphan chain
3351 RecordClientVector clientsOnSession = inputDesc->getClientsForSession(client->session());
3352 if (clientsOnSession.size() == 0) {
3353 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
3354 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003355 if (inputDesc->getClientCount() > 0) {
3356 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003357 return;
3358 }
3359
Eric Laurent05b90f82014-08-27 15:32:29 -07003360 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003361 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003362 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003363}
3364
Eric Laurent8f42ea12018-08-08 09:08:25 -07003365void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003366{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003367 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003368
3369 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003370 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003371 }
3372}
3373
Eric Laurent8f42ea12018-08-08 09:08:25 -07003374void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3375{
3376 stopInput(portId);
3377 releaseInput(portId);
3378}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003379
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003380bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3381 if (input->clientsList().size() == 0
3382 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3383 return true;
3384 }
3385 for (const auto& client : input->clientsList()) {
3386 sp<DeviceDescriptor> device =
3387 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3388 client->session());
3389 if (!input->supportedDevices().contains(device)) {
3390 return true;
3391 }
3392 }
3393 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3394 return false;
3395}
3396
Eric Laurent0dd51852019-04-19 18:18:58 -07003397void AudioPolicyManager::checkCloseInputs() {
3398 // After connecting or disconnecting an input device, close input if:
3399 // - it has no client (was just opened to check profile) OR
3400 // - none of its supported devices are connected anymore OR
3401 // - one of its clients cannot be routed to one of its supported
3402 // devices anymore. Otherwise update device selection
3403 std::vector<audio_io_handle_t> inputsToClose;
3404 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003405 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003406 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003407 }
3408 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003409 for (const audio_io_handle_t handle : inputsToClose) {
3410 ALOGV("%s closing input %d", __func__, handle);
3411 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003412 }
Eric Laurentd4692962014-05-05 18:13:44 -07003413}
3414
Vlad Popa87e0e582024-05-20 18:49:20 -07003415status_t AudioPolicyManager::setDeviceAbsoluteVolumeEnabled(audio_devices_t deviceType,
3416 const char *address __unused,
3417 bool enabled,
3418 audio_stream_type_t streamToDriveAbs)
3419{
3420 audio_attributes_t attributesToDriveAbs = mEngine->getAttributesForStreamType(streamToDriveAbs);
3421 if (attributesToDriveAbs == AUDIO_ATTRIBUTES_INITIALIZER) {
3422 ALOGW("%s: no attributes for stream %s, bailing out", __func__,
3423 toString(streamToDriveAbs).c_str());
3424 return BAD_VALUE;
3425 }
3426
3427 if (enabled) {
3428 mAbsoluteVolumeDrivingStreams[deviceType] = attributesToDriveAbs;
3429 } else {
3430 mAbsoluteVolumeDrivingStreams.erase(deviceType);
3431 }
3432
3433 return NO_ERROR;
3434}
3435
François Gaffie251c7f02018-11-07 10:41:08 +01003436void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003437{
3438 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003439 if (indexMin < 0 || indexMax < 0) {
3440 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3441 return;
3442 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003443 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003444
3445 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003446 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3447 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003448 continue;
3449 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003450 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003451 }
Eric Laurente552edb2014-03-10 17:42:56 -07003452}
3453
Eric Laurente0720872014-03-11 09:30:41 -07003454status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003455 int index,
3456 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003457{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003458 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003459 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3460 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3461 return NO_ERROR;
3462 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303463 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3464 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003465 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003466}
3467
Eric Laurente0720872014-03-11 09:30:41 -07003468status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003469 int *index,
3470 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003471{
François Gaffiec005e562018-11-06 15:04:49 +01003472 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3473 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003474 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003475 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003476 deviceTypes = mEngine->getOutputDevicesForStream(
3477 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003478 }
jiabin9a3361e2019-10-01 09:38:30 -07003479 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003480}
3481
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003482status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003483 int index,
3484 audio_devices_t device)
3485{
3486 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003487 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3488 if (group == VOLUME_GROUP_NONE) {
3489 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003490 return BAD_VALUE;
3491 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003492 ALOGV("%s: group %d matching with %s index %d",
3493 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003494 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003495 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003496 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003497 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3498 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3499 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3500 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003501 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3502
3503 status = setVolumeCurveIndex(index, device, curves);
3504 if (status != NO_ERROR) {
3505 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3506 return status;
3507 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003508
jiabin9a3361e2019-10-01 09:38:30 -07003509 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003510 auto curCurvAttrs = curves.getAttributes();
3511 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3512 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003513 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003514 } else if (!curves.getStreamTypes().empty()) {
3515 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003516 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003517 } else {
3518 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3519 return BAD_VALUE;
3520 }
jiabin9a3361e2019-10-01 09:38:30 -07003521 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3522 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003523
François Gaffiecfe17322018-11-07 13:41:29 +01003524 // update volume on all outputs and streams matching the following:
3525 // - The requested stream (or a stream matching for volume control) is active on the output
3526 // - The device (or devices) selected by the engine for this stream includes
3527 // the requested device
3528 // - For non default requested device, currently selected device on the output is either the
3529 // requested device or one of the devices selected by the engine for this stream
3530 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3531 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003532 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003533 for (size_t i = 0; i < mOutputs.size(); i++) {
3534 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003535 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003536
jiabin9a3361e2019-10-01 09:38:30 -07003537 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3538 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003539 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003540
3541 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003542 continue;
3543 }
3544 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3545 curDevices.find(device) == curDevices.end()) {
3546 continue;
3547 }
3548 bool applyVolume = false;
3549 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3550 curSrcDevices.insert(device);
3551 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003552 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3553 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003554 } else {
3555 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3556 }
3557 if (!applyVolume) {
3558 continue; // next output
3559 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003560 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3561 // If a higher priority strategy is active, and the output is routed to a device with a
3562 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003563 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003564 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003565 // If the volume source is active with higher priority source, ensure at least Sw Muted
3566 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003567 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3568 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3569 false /*preferredDevice*/);
3570 if (activeClients.empty()) {
3571 continue;
3572 }
3573 bool isPreempted = false;
3574 bool isHigherPriority = productStrategy < strategy;
3575 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003576 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003577 ALOGV("%s: Strategy=%d (\nrequester:\n"
3578 " group %d, volumeGroup=%d attributes=%s)\n"
3579 " higher priority source active:\n"
3580 " volumeGroup=%d attributes=%s) \n"
3581 " on output %zu, bailing out", __func__, productStrategy,
3582 group, group, toString(attributes).c_str(),
3583 client->volumeSource(), toString(client->attributes()).c_str(), i);
3584 applyVolume = false;
3585 isPreempted = true;
3586 break;
3587 }
3588 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003589 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003590 applyVolume = true;
3591 }
3592 }
3593 if (isPreempted || applyVolume) {
3594 break;
3595 }
3596 }
3597 if (!applyVolume) {
3598 continue; // next output
3599 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003600 }
François Gaffieed91f582020-01-31 10:35:37 +01003601 //FIXME: workaround for truncated touch sounds
3602 // delayed volume change for system stream to be removed when the problem is
3603 // handled by system UI
3604 status_t volStatus = checkAndSetVolume(
3605 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003606 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003607 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3608 if (volStatus != NO_ERROR) {
3609 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003610 }
3611 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003612
3613 // update voice volume if the an active call route exists
3614 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3615 && (curSrcDevices.find(
3616 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3617 != curSrcDevices.end())) {
3618 bool isVoiceVolSrc;
3619 bool isBtScoVolSrc;
3620 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3621 isVoiceVolSrc, isBtScoVolSrc, __func__)
3622 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003623 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3624 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3625 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003626 }
3627 }
3628
François Gaffiecfe17322018-11-07 13:41:29 +01003629 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3630 return status;
3631}
3632
François Gaffieaaac0fd2018-11-22 17:56:39 +01003633status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003634 audio_devices_t device,
3635 IVolumeCurves &volumeCurves)
3636{
3637 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3638 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003639 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3640 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003641 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303642 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3643 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003644 return BAD_VALUE;
3645 }
3646 if (!audio_is_output_device(device)) {
3647 return BAD_VALUE;
3648 }
3649
3650 // Force max volume if stream cannot be muted
3651 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3652
François Gaffieaaac0fd2018-11-22 17:56:39 +01003653 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003654 volumeCurves.addCurrentVolumeIndex(device, index);
3655 return NO_ERROR;
3656}
3657
3658status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3659 int &index,
3660 audio_devices_t device)
3661{
3662 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3663 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003664 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003665 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003666 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003667 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003668 }
jiabin9a3361e2019-10-01 09:38:30 -07003669 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003670}
3671
3672status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3673 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003674 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003675{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003676 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003677 return BAD_VALUE;
3678 }
jiabin9a3361e2019-10-01 09:38:30 -07003679 index = curves.getVolumeIndex(deviceTypes);
3680 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003681 return NO_ERROR;
3682}
3683
3684status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3685 int &index)
3686{
3687 index = getVolumeCurves(attr).getVolumeIndexMin();
3688 return NO_ERROR;
3689}
3690
3691status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3692 int &index)
3693{
3694 index = getVolumeCurves(attr).getVolumeIndexMax();
3695 return NO_ERROR;
3696}
3697
Eric Laurent36829f92017-04-07 19:04:42 -07003698audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003699{
3700 // select one output among several suitable for global effects.
3701 // The priority is as follows:
3702 // 1: An offloaded output. If the effect ends up not being offloadable,
3703 // AudioFlinger will invalidate the track and the offloaded output
3704 // will be closed causing the effect to be moved to a PCM output.
3705 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003706 // 3: The primary output
3707 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003708
François Gaffiec005e562018-11-06 15:04:49 +01003709 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3710 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003711 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003712
Eric Laurent36829f92017-04-07 19:04:42 -07003713 if (outputs.size() == 0) {
3714 return AUDIO_IO_HANDLE_NONE;
3715 }
Eric Laurente552edb2014-03-10 17:42:56 -07003716
Eric Laurent36829f92017-04-07 19:04:42 -07003717 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3718 bool activeOnly = true;
3719
3720 while (output == AUDIO_IO_HANDLE_NONE) {
3721 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3722 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3723 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3724
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003725 for (audio_io_handle_t output : outputs) {
3726 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003727 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003728 continue;
3729 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003730 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3731 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003732 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003733 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003734 }
3735 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003736 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003737 }
3738 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003739 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003740 }
3741 }
3742 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3743 output = outputOffloaded;
3744 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3745 output = outputDeepBuffer;
3746 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3747 output = outputPrimary;
3748 } else {
3749 output = outputs[0];
3750 }
3751 activeOnly = false;
3752 }
3753
3754 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003755 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3756 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003757 mMusicEffectOutput = output;
3758 }
3759
3760 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003761 return output;
3762}
3763
Eric Laurent36829f92017-04-07 19:04:42 -07003764audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3765{
3766 return selectOutputForMusicEffects();
3767}
3768
Eric Laurente0720872014-03-11 09:30:41 -07003769status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003770 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003771 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003772 int session,
3773 int id)
3774{
Shunkai Yao2fa06c12024-03-19 04:31:47 +00003775 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003776 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003777 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003778 index = mInputs.indexOfKey(io);
3779 if (index < 0) {
3780 ALOGW("registerEffect() unknown io %d", io);
3781 return INVALID_OPERATION;
3782 }
Eric Laurente552edb2014-03-10 17:42:56 -07003783 }
3784 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003785 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3786 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3787 || strategy == PRODUCT_STRATEGY_NONE));
3788 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003789}
3790
Eric Laurentc241b0d2018-11-28 09:08:49 -08003791status_t AudioPolicyManager::unregisterEffect(int id)
3792{
3793 if (mEffects.getEffect(id) == nullptr) {
3794 return INVALID_OPERATION;
3795 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003796 if (mEffects.isEffectEnabled(id)) {
3797 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3798 setEffectEnabled(id, false);
3799 }
3800 return mEffects.unregisterEffect(id);
3801}
3802
3803status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3804{
3805 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3806 if (effect == nullptr) {
3807 return INVALID_OPERATION;
3808 }
3809
3810 status_t status = mEffects.setEffectEnabled(id, enabled);
3811 if (status == NO_ERROR) {
3812 mInputs.trackEffectEnabled(effect, enabled);
3813 }
3814 return status;
3815}
3816
Eric Laurent6c796322019-04-09 14:13:17 -07003817
3818status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3819{
3820 mEffects.moveEffects(ids, io);
3821 return NO_ERROR;
3822}
3823
Eric Laurentc75307b2015-03-17 15:29:32 -07003824bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3825{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003826 auto vs = toVolumeSource(stream, false);
3827 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003828}
3829
3830bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3831{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003832 auto vs = toVolumeSource(stream, false);
3833 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003834}
3835
Eric Laurente0720872014-03-11 09:30:41 -07003836bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003837{
3838 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003839 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003840 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003841 return true;
3842 }
3843 }
3844 return false;
3845}
3846
Eric Laurent275e8e92014-11-30 15:14:47 -08003847// Register a list of custom mixes with their attributes and format.
3848// When a mix is registered, corresponding input and output profiles are
3849// added to the remote submix hw module. The profile contains only the
3850// parameters (sampling rate, format...) specified by the mix.
3851// The corresponding input remote submix device is also connected.
3852//
3853// When a remote submix device is connected, the address is checked to select the
3854// appropriate profile and the corresponding input or output stream is opened.
3855//
3856// When capture starts, getInputForAttr() will:
3857// - 1 look for a mix matching the address passed in attribtutes tags if any
3858// - 2 if none found, getDeviceForInputSource() will:
3859// - 2.1 look for a mix matching the attributes source
3860// - 2.2 if none found, default to device selection by policy rules
3861// At this time, the corresponding output remote submix device is also connected
3862// and active playback use cases can be transferred to this mix if needed when reconnecting
3863// after AudioTracks are invalidated
3864//
3865// When playback starts, getOutputForAttr() will:
3866// - 1 look for a mix matching the address passed in attribtutes tags if any
3867// - 2 if none found, look for a mix matching the attributes usage
3868// - 3 if none found, default to device and output selection by policy rules.
3869
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003870status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003871{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003872 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3873 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003874 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003875 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003876 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003877 // examine each mix's route type
3878 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003879 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003880 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3881 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3882 ALOGE("Unsupported Policy Mix %zu of %zu: "
3883 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3884 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003885 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003886 break;
3887 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003888 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3889 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003890 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003891 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3892 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003893 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003894 rSubmixModule = mHwModules.getModuleFromName(
3895 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3896 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003897 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003898 i);
3899 res = INVALID_OPERATION;
3900 break;
3901 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003902 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003903
Eric Laurent97ac8712018-07-27 18:59:02 -07003904 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003905 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003906 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003907 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003908 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3909 } else {
3910 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3911 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003912 }
François Gaffie036e1e92015-03-19 10:16:24 +01003913
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003914 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003915 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003916 res = INVALID_OPERATION;
3917 break;
3918 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003919 audio_config_t outputConfig = mix.mFormat;
3920 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003921 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3922 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003923 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3924 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003925 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003926 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3927 audio_is_linear_pcm(outputConfig.format)
3928 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003929 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003930 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3931 audio_is_linear_pcm(inputConfig.format)
3932 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003933
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003934 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003935 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003936 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003937 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003938 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003939 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003940 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003941 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3942 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003943 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003944 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003945 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003946
3947 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3948 mix.mDeviceType, mix.mDeviceAddress,
3949 String8(), AUDIO_FORMAT_DEFAULT);
3950 if (device == nullptr) {
3951 res = INVALID_OPERATION;
3952 break;
3953 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003954
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003955 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003956 // First try to find an already opened output supporting the device
3957 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003958 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003959
Eric Laurentc529cf62020-04-17 18:19:10 -07003960 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003961 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003962 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003963 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003964 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003965 } else {
3966 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003967 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003968 }
3969 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003970 // If no output found, try to find a direct output profile supporting the device
3971 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3972 sp<HwModule> module = mHwModules[i];
3973 for (size_t j = 0;
3974 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3975 j++) {
3976 sp<IOProfile> profile = module->getOutputProfiles()[j];
3977 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3978 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3979 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003980 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003981 res = INVALID_OPERATION;
3982 } else {
3983 foundOutput = true;
3984 }
3985 }
3986 }
3987 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003988 if (res != NO_ERROR) {
3989 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003990 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003991 res = INVALID_OPERATION;
3992 break;
3993 } else if (!foundOutput) {
3994 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003995 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003996 res = INVALID_OPERATION;
3997 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003998 } else {
3999 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01004000 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004001 }
Eric Laurentc722f302014-12-10 11:21:49 -08004002 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004003 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004004 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01004005 if (audio_flags::audio_mix_ownership()) {
4006 // Only unregister mixes that were actually registered to not accidentally unregister
4007 // mixes that already existed previously.
4008 unregisterPolicyMixes(registeredMixes);
4009 registeredMixes.clear();
4010 } else {
4011 unregisterPolicyMixes(mixes);
4012 }
Eric Laurentc209fe42020-06-05 18:11:23 -07004013 } else if (checkOutputs) {
4014 checkForDeviceAndOutputChanges();
4015 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004016 }
4017 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004018}
4019
4020status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
4021{
Eric Laurent7b279bb2015-12-14 10:18:23 -08004022 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004023 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07004024 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004025 sp<HwModule> rSubmixModule;
4026 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004027 for (const auto& mix : mixes) {
4028 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01004029
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004030 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08004031 rSubmixModule = mHwModules.getModuleFromName(
4032 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
4033 if (rSubmixModule == 0) {
4034 res = INVALID_OPERATION;
4035 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004036 }
4037 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004038
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004039 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08004040
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004041 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004042 res = INVALID_OPERATION;
4043 continue;
4044 }
4045
Marvin Ramin0783e202024-03-05 12:45:50 +01004046 for (auto device: {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004047 if (getDeviceConnectionState(device, address.c_str()) ==
Marvin Ramin0783e202024-03-05 12:45:50 +01004048 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
4049 status_t currentRes =
4050 setDeviceConnectionStateInt(device,
4051 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
4052 address.c_str(),
4053 "remote-submix",
4054 AUDIO_FORMAT_DEFAULT);
4055 if (!audio_flags::audio_mix_ownership()) {
4056 res = currentRes;
4057 }
4058 if (currentRes != OK) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07004059 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004060 "with type %d, address %s", device, address.c_str());
Marvin Ramin0783e202024-03-05 12:45:50 +01004061 res = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07004062 }
4063 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004064 }
jiabin5740f082019-08-19 15:08:30 -07004065 rSubmixModule->removeOutputProfile(address.c_str());
4066 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004067
Kevin Rocard153f92d2018-12-18 18:33:28 -08004068 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07004069 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004070 res = INVALID_OPERATION;
4071 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07004072 } else {
4073 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004074 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004075 }
Eric Laurent275e8e92014-11-30 15:14:47 -08004076 }
Marvin Ramin0783e202024-03-05 12:45:50 +01004077
4078 if (res == NO_ERROR && checkOutputs) {
4079 checkForDeviceAndOutputChanges();
4080 updateCallAndOutputRouting();
Eric Laurentc209fe42020-06-05 18:11:23 -07004081 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08004082 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08004083}
4084
Marvin Raminbdefaf02023-11-01 09:10:32 +01004085status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
4086 if (!audio_flags::audio_mix_test_api()) {
4087 return INVALID_OPERATION;
4088 }
4089
4090 _aidl_return.clear();
4091 _aidl_return.reserve(mPolicyMixes.size());
4092 for (const auto &policyMix: mPolicyMixes) {
4093 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
4094 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
4095 policyMix->mCbFlags);
4096 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01004097 _aidl_return.back().mToken = policyMix->mToken;
Marvin Ramine5a122d2023-12-07 13:57:59 +01004098 _aidl_return.back().mVirtualDeviceId = policyMix->mVirtualDeviceId;
Marvin Raminbdefaf02023-11-01 09:10:32 +01004099 }
4100
Vlad Popaa5d73f32024-03-08 16:05:38 -08004101 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return.size());
Marvin Raminbdefaf02023-11-01 09:10:32 +01004102 return OK;
4103}
4104
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02004105status_t AudioPolicyManager::updatePolicyMix(
4106 const AudioMix& mix,
4107 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
4108 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
4109 if (res == NO_ERROR) {
4110 checkForDeviceAndOutputChanges();
4111 updateCallAndOutputRouting();
4112 }
4113 return res;
4114}
4115
Mikhail Naganov100f0122018-11-29 11:22:16 -08004116void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
4117{
4118 size_t i = 0;
4119 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
4120 for (const auto& fmt : mManualSurroundFormats) {
4121 if (i++ != 0) dst->append(", ");
4122 std::string sfmt;
4123 FormatConverter::toString(fmt, sfmt);
4124 dst->append(sfmt.size() >= audioFormatPrefixLen ?
4125 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
4126 }
4127}
4128
Eric Laurentc529cf62020-04-17 18:19:10 -07004129// Returns true if all devices types match the predicate and are supported by one HW module
4130bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07004131 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07004132 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01004133 const char *context,
4134 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004135 for (size_t i = 0; i < devices.size(); i++) {
4136 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07004137 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01004138 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07004139 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004140 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07004141 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07004142 return false;
4143 }
4144 }
4145 return true;
4146}
4147
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004148void AudioPolicyManager::changeOutputDevicesMuteState(
4149 const AudioDeviceTypeAddrVector& devices) {
4150 ALOGVV("%s() num devices %zu", __func__, devices.size());
4151
4152 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4153 getSoftwareOutputsForDevices(devices);
4154
4155 for (size_t i = 0; i < outputs.size(); i++) {
4156 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4157 DeviceVector prevDevices = outputDesc->devices();
4158 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4159 }
4160}
4161
4162std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4163 const AudioDeviceTypeAddrVector& devices) const
4164{
4165 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4166 DeviceVector deviceDescriptors;
4167 for (size_t j = 0; j < devices.size(); j++) {
4168 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4169 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4170 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4171 ALOGE("%s: device type %#x address %s not supported or not an output device",
4172 __func__, devices[j].mType, devices[j].getAddress());
4173 continue;
4174 }
4175 deviceDescriptors.add(desc);
4176 }
4177 for (size_t i = 0; i < mOutputs.size(); i++) {
4178 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4179 continue;
4180 }
4181 outputs.push_back(mOutputs.valueAt(i));
4182 }
4183 return outputs;
4184}
4185
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004186status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004187 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004188 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004189 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4190 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004191 }
4192 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004193 if (res != NO_ERROR) {
4194 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4195 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004196 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004197
4198 checkForDeviceAndOutputChanges();
4199 updateCallAndOutputRouting();
4200
4201 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004202}
4203
4204status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4205 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004206 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4207 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004208 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004209 __FUNCTION__, uid);
4210 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004211 }
4212
Eric Laurentc529cf62020-04-17 18:19:10 -07004213 checkForDeviceAndOutputChanges();
4214 updateCallAndOutputRouting();
4215
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004216 return res;
4217}
4218
Eric Laurent2517af32020-11-25 15:31:27 +01004219
jiabin0a488932020-08-07 17:32:40 -07004220status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4221 device_role_t role,
4222 const AudioDeviceTypeAddrVector &devices) {
4223 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4224 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004225
Eric Laurentc529cf62020-04-17 18:19:10 -07004226 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004227 return BAD_VALUE;
4228 }
jiabin0a488932020-08-07 17:32:40 -07004229 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004230 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004231 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4232 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004233 return status;
4234 }
4235
4236 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004237
4238 bool forceVolumeReeval = false;
4239 // FIXME: workaround for truncated touch sounds
4240 // to be removed when the problem is handled by system UI
4241 uint32_t delayMs = 0;
4242 if (strategy == mCommunnicationStrategy) {
4243 forceVolumeReeval = true;
4244 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4245 updateInputRouting();
4246 }
4247 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004248
4249 return NO_ERROR;
4250}
4251
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004252void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4253 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004254{
4255 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004256 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004257 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004258 // Only apply special touch sound delay once
4259 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004260 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004261 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004262 for (size_t i = 0; i < mOutputs.size(); i++) {
4263 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4264 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004265 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4266 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004267 // As done in setDeviceConnectionState, we could also fix default device issue by
4268 // preventing the force re-routing in case of default dev that distinguishes on address.
4269 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004270 bool forceRouting = !newDevices.isEmpty();
jiabin220eea12024-05-17 17:55:20 +00004271 if (outputDesc->mPreferredAttrInfo != nullptr && newDevices != outputDesc->devices()) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004272 // If the device is using preferred mixer attributes, the output need to reopen
4273 // with default configuration when the new selected devices are different from
4274 // current routing devices.
4275 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4276 continue;
4277 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304278
4279 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4280 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004281 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004282 // Only apply special touch sound delay once
4283 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004284 }
4285 if (forceVolumeReeval && !newDevices.isEmpty()) {
4286 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4287 }
4288 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004289 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004290 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004291}
4292
Eric Laurent2517af32020-11-25 15:31:27 +01004293void AudioPolicyManager::updateInputRouting() {
4294 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304295 // Skip for hotword recording as the input device switch
4296 // is handled within sound trigger HAL
4297 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4298 continue;
4299 }
Eric Laurent2517af32020-11-25 15:31:27 +01004300 auto newDevice = getNewInputDevice(activeDesc);
4301 // Force new input selection if the new device can not be reached via current input
4302 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4303 setInputDevice(activeDesc->mIoHandle, newDevice);
4304 } else {
4305 closeInput(activeDesc->mIoHandle);
4306 }
4307 }
4308}
4309
Paul Wang5d7cdb52022-11-22 09:45:06 +00004310status_t
4311AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4312 device_role_t role,
4313 const AudioDeviceTypeAddrVector &devices) {
4314 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4315 dumpAudioDeviceTypeAddrVector(devices).c_str());
4316
Eric Laurent78fedbf2023-03-09 14:40:44 +01004317 if (!areAllDevicesSupported(
4318 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004319 return BAD_VALUE;
4320 }
4321 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4322 if (status != NO_ERROR) {
4323 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4324 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4325 return status;
4326 }
4327
4328 checkForDeviceAndOutputChanges();
4329
4330 bool forceVolumeReeval = false;
4331 // TODO(b/263479999): workaround for truncated touch sounds
4332 // to be removed when the problem is handled by system UI
4333 uint32_t delayMs = 0;
4334 if (strategy == mCommunnicationStrategy) {
4335 forceVolumeReeval = true;
4336 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4337 updateInputRouting();
4338 }
4339 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4340
4341 return NO_ERROR;
4342}
4343
4344status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4345 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004346{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004347 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004348
Paul Wang5d7cdb52022-11-22 09:45:06 +00004349 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004350 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004351 ALOGW_IF(status != NAME_NOT_FOUND,
4352 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004353 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004354 return status;
4355 }
4356
4357 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004358
4359 bool forceVolumeReeval = false;
4360 // FIXME: workaround for truncated touch sounds
4361 // to be removed when the problem is handled by system UI
4362 uint32_t delayMs = 0;
4363 if (strategy == mCommunnicationStrategy) {
4364 forceVolumeReeval = true;
4365 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4366 updateInputRouting();
4367 }
4368 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004369
4370 return NO_ERROR;
4371}
4372
jiabin0a488932020-08-07 17:32:40 -07004373status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4374 device_role_t role,
4375 AudioDeviceTypeAddrVector &devices) {
4376 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004377}
4378
Jiabin Huang3b98d322020-09-03 17:54:16 +00004379status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4380 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4381 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4382 dumpAudioDeviceTypeAddrVector(devices).c_str());
4383
Mikhail Naganov55773032020-10-01 15:08:13 -07004384 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004385 return BAD_VALUE;
4386 }
4387 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4388 ALOGW_IF(status != NO_ERROR,
4389 "Engine could not set preferred devices %s for audio source %d role %d",
4390 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4391
4392 return status;
4393}
4394
4395status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4396 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4397 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4398 dumpAudioDeviceTypeAddrVector(devices).c_str());
4399
Mikhail Naganov55773032020-10-01 15:08:13 -07004400 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004401 return BAD_VALUE;
4402 }
4403 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4404 ALOGW_IF(status != NO_ERROR,
4405 "Engine could not add preferred devices %s for audio source %d role %d",
4406 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4407
Eric Laurent2517af32020-11-25 15:31:27 +01004408 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004409 return status;
4410}
4411
4412status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4413 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4414{
4415 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4416 dumpAudioDeviceTypeAddrVector(devices).c_str());
4417
Eric Laurent78fedbf2023-03-09 14:40:44 +01004418 if (!areAllDevicesSupported(
4419 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004420 return BAD_VALUE;
4421 }
4422
4423 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4424 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004425 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004426 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004427 if (status == NO_ERROR) {
4428 updateInputRouting();
4429 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004430 return status;
4431}
4432
4433status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4434 device_role_t role) {
4435 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4436
4437 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004438 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004439 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004440 if (status == NO_ERROR) {
4441 updateInputRouting();
4442 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004443 return status;
4444}
4445
4446status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4447 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4448 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4449}
4450
Oscar Azucena90e77632019-11-27 17:12:28 -08004451status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004452 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004453 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004454 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4455 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004456 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004457 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4458 if (status != NO_ERROR) {
4459 ALOGE("%s() could not set device affinity for userId %d",
4460 __FUNCTION__, userId);
4461 return status;
4462 }
4463
4464 // reevaluate outputs for all devices
4465 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004466 changeOutputDevicesMuteState(devices);
4467 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4468 true /* skipDelays */);
4469 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004470
4471 return NO_ERROR;
4472}
4473
4474status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004475 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004476 AudioDeviceTypeAddrVector devices;
4477 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004478 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4479 if (status != NO_ERROR) {
4480 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4481 __FUNCTION__, userId);
4482 return status;
4483 }
4484
4485 // reevaluate outputs for all devices
4486 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004487 changeOutputDevicesMuteState(devices);
4488 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4489 true /* skipDelays */);
4490 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004491
4492 return NO_ERROR;
4493}
4494
Andy Hungc29d82b2018-10-05 12:23:17 -07004495void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004496{
Andy Hungc29d82b2018-10-05 12:23:17 -07004497 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004498 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004499 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004500 std::string stateLiteral;
4501 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004502 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004503 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4504 "communications", "media", "record", "dock", "system",
4505 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4506 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4507 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004508 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4509 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4510 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4511 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4512 dst->append(" (MANUAL: ");
4513 dumpManualSurroundFormats(dst);
4514 dst->append(")");
4515 }
4516 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004517 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004518 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4519 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004520 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004521 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004522
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004523 dst->append("\n");
4524 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4525 dst->append("\n");
4526 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004527 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004528 mOutputs.dump(dst);
4529 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004530 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004531 mAudioPatches.dump(dst);
4532 mPolicyMixes.dump(dst);
4533 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004534
Kevin Rocardb99cc752019-03-21 20:52:24 -07004535 dst->appendFormat(" AllowedCapturePolicies:\n");
4536 for (auto& policy : mAllowedCapturePolicies) {
4537 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4538 }
4539
jiabina84c3d32022-12-02 18:59:55 +00004540 dst->appendFormat(" Preferred mixer audio configuration:\n");
4541 for (const auto it : mPreferredMixerAttrInfos) {
4542 dst->appendFormat(" - device port id: %d\n", it.first);
4543 for (const auto preferredMixerInfoIt : it.second) {
4544 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4545 preferredMixerInfoIt.second->dump(dst);
4546 }
4547 }
4548
François Gaffiec005e562018-11-06 15:04:49 +01004549 dst->appendFormat("\nPolicy Engine dump:\n");
4550 mEngine->dump(dst);
Vlad Popa87e0e582024-05-20 18:49:20 -07004551
4552 dst->appendFormat("\nAbsolute volume devices with driving streams:\n");
4553 for (const auto it : mAbsoluteVolumeDrivingStreams) {
4554 dst->appendFormat(" - device type: %s, driving stream %d\n",
4555 dumpDeviceTypes({it.first}).c_str(),
4556 mEngine->getVolumeGroupForAttributes(it.second));
4557 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004558}
4559
4560status_t AudioPolicyManager::dump(int fd)
4561{
4562 String8 result;
4563 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004564 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004565 return NO_ERROR;
4566}
4567
Kevin Rocardb99cc752019-03-21 20:52:24 -07004568status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4569{
4570 mAllowedCapturePolicies[uid] = capturePolicy;
4571 return NO_ERROR;
4572}
4573
Eric Laurente552edb2014-03-10 17:42:56 -07004574// This function checks for the parameters which can be offloaded.
4575// This can be enhanced depending on the capability of the DSP and policy
4576// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004577audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004578{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004579 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004580 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004581 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004582 offloadInfo.format,
4583 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4584 offloadInfo.has_video);
4585
jiabin2b9d5a12021-12-10 01:06:29 +00004586 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004587 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004588 }
4589
4590 // See if there is a profile to support this.
4591 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004592 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004593 offloadInfo.sample_rate,
4594 offloadInfo.format,
4595 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004596 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4597 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004598 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4599 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4600 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004601 if (profile == nullptr) {
4602 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4603 }
4604 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4605 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4606 }
4607 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004608}
4609
Michael Chana94fbb22018-04-24 14:31:19 +10004610bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4611 const audio_attributes_t& attributes) {
4612 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004613 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004614 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4615 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004616 config.sample_rate,
4617 config.format,
4618 config.channel_mask,
4619 output_flags,
4620 true /* directOnly */);
4621 ALOGV("%s() profile %sfound with name: %s, "
4622 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4623 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004624 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004625 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004626
4627 // also try the MSD module if compatible profile not found
4628 if (profile == nullptr) {
4629 profile = getMsdProfileForOutput(outputDevices,
4630 config.sample_rate,
4631 config.format,
4632 config.channel_mask,
4633 output_flags,
4634 true /* directOnly */);
4635 ALOGV("%s() MSD profile %sfound with name: %s, "
4636 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4637 __FUNCTION__, profile != 0 ? "" : "NOT ",
4638 (profile != 0 ? profile->getTagName().c_str() : "null"),
4639 config.sample_rate, config.format, config.channel_mask, output_flags);
4640 }
4641 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004642}
4643
jiabin2b9d5a12021-12-10 01:06:29 +00004644bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4645 bool durationIgnored) {
4646 if (mMasterMono) {
4647 return false; // no offloading if mono is set.
4648 }
4649
4650 // Check if offload has been disabled
4651 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4652 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4653 return false;
4654 }
4655
4656 // Check if stream type is music, then only allow offload as of now.
4657 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4658 {
4659 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4660 return false;
4661 }
4662
4663 //TODO: enable audio offloading with video when ready
4664 const bool allowOffloadWithVideo =
4665 property_get_bool("audio.offload.video", false /* default_value */);
4666 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4667 ALOGV("%s: has_video == true, returning false", __func__);
4668 return false;
4669 }
4670
4671 //If duration is less than minimum value defined in property, return false
4672 const int min_duration_secs = property_get_int32(
4673 "audio.offload.min.duration.secs", -1 /* default_value */);
4674 if (!durationIgnored) {
4675 if (min_duration_secs >= 0) {
4676 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4677 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4678 __func__, min_duration_secs);
4679 return false;
4680 }
4681 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4682 ALOGV("%s: Offload denied by duration < default min(=%u)",
4683 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4684 return false;
4685 }
4686 }
4687
4688 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4689 // creating an offloaded track and tearing it down immediately after start when audioflinger
4690 // detects there is an active non offloadable effect.
4691 // FIXME: We should check the audio session here but we do not have it in this context.
4692 // This may prevent offloading in rare situations where effects are left active by apps
4693 // in the background.
4694 if (mEffects.isNonOffloadableEffectEnabled()) {
4695 return false;
4696 }
4697
4698 return true;
4699}
4700
4701audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4702 const audio_config_t *config) {
4703 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4704 offloadInfo.format = config->format;
4705 offloadInfo.sample_rate = config->sample_rate;
4706 offloadInfo.channel_mask = config->channel_mask;
4707 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4708 offloadInfo.has_video = false;
4709 offloadInfo.is_streaming = false;
4710 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4711
4712 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4713 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4714 audio_flags_to_audio_output_flags(attr->flags, &flags);
4715 // only retain flags that will drive compressed offload or passthrough
4716 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4717 if (offloadPossible) {
4718 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4719 }
4720 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4721
Dorin Drimusfae3c642022-03-17 18:36:30 +01004722 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004723 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004724 DeviceVector outputDevices = engineOutputDevices;
4725 // the MSD module checks for different conditions and output devices
4726 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4727 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4728 continue;
4729 }
4730 outputDevices = getMsdAudioOutDevices();
4731 }
jiabin2b9d5a12021-12-10 01:06:29 +00004732 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004733 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004734 config->sample_rate, nullptr /*updatedSamplingRate*/,
4735 config->format, nullptr /*updatedFormat*/,
4736 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004737 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004738 continue;
4739 }
4740 // reject profiles not corresponding to a device currently available
4741 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4742 continue;
4743 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004744 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4745 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004746 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004747 != AUDIO_DIRECT_NOT_SUPPORTED) {
4748 // Already reports offload gapless supported. No need to report offload support.
4749 continue;
4750 }
4751 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4752 != AUDIO_OUTPUT_FLAG_NONE) {
4753 // If offload gapless is reported, no need to report offload support.
4754 directMode = (audio_direct_mode_t) ((directMode &
4755 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4756 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4757 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004758 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004759 }
4760 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004761 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004762 }
4763 }
4764 }
4765 return directMode;
4766}
4767
Dorin Drimusf2196d82022-01-03 12:11:18 +01004768status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4769 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004770 if (mEffects.isNonOffloadableEffectEnabled()) {
4771 return OK;
4772 }
jiabinf1c73972022-04-14 16:28:52 -07004773 DeviceVector devices;
4774 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004775 if (status != OK) {
4776 return status;
4777 }
4778 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4779 if (devices.empty()) {
4780 return OK; // no output devices for the attributes
4781 }
jiabinf1c73972022-04-14 16:28:52 -07004782 return getProfilesForDevices(devices, audioProfilesVector,
4783 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004784}
4785
jiabina84c3d32022-12-02 18:59:55 +00004786status_t AudioPolicyManager::getSupportedMixerAttributes(
4787 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4788 ALOGV("%s, portId=%d", __func__, portId);
4789 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4790 if (deviceDescriptor == nullptr) {
4791 ALOGE("%s the requested device is currently unavailable", __func__);
4792 return BAD_VALUE;
4793 }
jiabin96daffc2023-05-11 17:51:55 +00004794 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4795 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4796 deviceDescriptor->type());
4797 return BAD_VALUE;
4798 }
jiabina84c3d32022-12-02 18:59:55 +00004799 for (const auto& hwModule : mHwModules) {
4800 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4801 if (curProfile->supportsDevice(deviceDescriptor)) {
4802 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4803 }
4804 }
4805 }
4806 return NO_ERROR;
4807}
4808
4809status_t AudioPolicyManager::setPreferredMixerAttributes(
4810 const audio_attributes_t *attr,
4811 audio_port_handle_t portId,
4812 uid_t uid,
4813 const audio_mixer_attributes_t *mixerAttributes) {
4814 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4815 "mixerBehavior=%d}, uid=%d, portId=%u",
4816 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4817 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4818 mixerAttributes->mixer_behavior, uid, portId);
4819 if (attr->usage != AUDIO_USAGE_MEDIA) {
4820 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4821 return BAD_VALUE;
4822 }
4823 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4824 if (deviceDescriptor == nullptr) {
4825 ALOGE("%s the requested device is currently unavailable", __func__);
4826 return BAD_VALUE;
4827 }
4828 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4829 ALOGE("%s(%d), type=%d, is not a usb output device",
4830 __func__, portId, deviceDescriptor->type());
4831 return BAD_VALUE;
4832 }
4833
4834 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4835 audio_flags_to_audio_output_flags(attr->flags, &flags);
4836 flags = (audio_output_flags_t) (flags |
4837 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4838 sp<IOProfile> profile = nullptr;
4839 DeviceVector devices(deviceDescriptor);
4840 for (const auto& hwModule : mHwModules) {
4841 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4842 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004843 && curProfile->getCompatibilityScore(
4844 devices,
4845 mixerAttributes->config.sample_rate,
4846 nullptr /*updatedSamplingRate*/,
4847 mixerAttributes->config.format,
4848 nullptr /*updatedFormat*/,
4849 mixerAttributes->config.channel_mask,
4850 nullptr /*updatedChannelMask*/,
4851 flags,
4852 false /*exactMatchRequiredForInputFlags*/)
4853 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004854 profile = curProfile;
4855 break;
4856 }
4857 }
4858 }
4859 if (profile == nullptr) {
4860 ALOGE("%s, there is no compatible profile found", __func__);
4861 return BAD_VALUE;
4862 }
4863
4864 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4865 sp<PreferredMixerAttributesInfo>::make(
4866 uid, portId, profile, flags, *mixerAttributes);
4867 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4868 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4869
4870 // If 1) there is any client from the preferred mixer configuration owner that is currently
4871 // active and matches the strategy and 2) current output is on the preferred device and the
4872 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4873 // configuration.
4874 std::vector<audio_io_handle_t> outputsToReopen;
4875 for (size_t i = 0; i < mOutputs.size(); i++) {
4876 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004877 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4878 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
jiabin220eea12024-05-17 17:55:20 +00004879 output->mPreferredAttrInfo = mixerAttrInfo;
jiabin3ff8d7d2022-12-13 06:27:44 +00004880 } else {
4881 for (const auto &client: output->getActiveClients()) {
4882 if (client->uid() == uid && client->strategy() == strategy) {
4883 client->setIsInvalid();
4884 outputsToReopen.push_back(output->mIoHandle);
4885 }
jiabina84c3d32022-12-02 18:59:55 +00004886 }
4887 }
4888 }
4889 }
4890 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4891 config.sample_rate = mixerAttributes->config.sample_rate;
4892 config.channel_mask = mixerAttributes->config.channel_mask;
4893 config.format = mixerAttributes->config.format;
4894 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004895 sp<SwAudioOutputDescriptor> desc =
4896 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4897 if (desc == nullptr) {
4898 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4899 continue;
4900 }
jiabin220eea12024-05-17 17:55:20 +00004901 desc->mPreferredAttrInfo = mixerAttrInfo;
jiabina84c3d32022-12-02 18:59:55 +00004902 }
4903
4904 return NO_ERROR;
4905}
4906
4907sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004908 audio_port_handle_t devicePortId,
4909 product_strategy_t strategy,
4910 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004911 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4912 if (it == mPreferredMixerAttrInfos.end()) {
4913 return nullptr;
4914 }
jiabind9a58d32023-06-01 17:57:30 +00004915 if (activeBitPerfectPreferred) {
4916 for (auto [strategy, info] : it->second) {
jiabin220eea12024-05-17 17:55:20 +00004917 if (info->isBitPerfect() && info->getActiveClientCount() != 0) {
jiabind9a58d32023-06-01 17:57:30 +00004918 return info;
4919 }
4920 }
jiabina84c3d32022-12-02 18:59:55 +00004921 }
jiabind9a58d32023-06-01 17:57:30 +00004922 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4923 return strategyMatchedMixerAttrInfoIt == it->second.end()
4924 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004925}
4926
4927status_t AudioPolicyManager::getPreferredMixerAttributes(
4928 const audio_attributes_t *attr,
4929 audio_port_handle_t portId,
4930 audio_mixer_attributes_t* mixerAttributes) {
4931 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4932 portId, mEngine->getProductStrategyForAttributes(*attr));
4933 if (info == nullptr) {
4934 return NAME_NOT_FOUND;
4935 }
4936 *mixerAttributes = info->getMixerAttributes();
4937 return NO_ERROR;
4938}
4939
4940status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4941 audio_port_handle_t portId,
4942 uid_t uid) {
4943 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4944 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4945 if (preferredMixerAttrInfo == nullptr) {
4946 return NAME_NOT_FOUND;
4947 }
4948 if (preferredMixerAttrInfo->getUid() != uid) {
4949 ALOGE("%s, requested uid=%d, owned uid=%d",
4950 __func__, uid, preferredMixerAttrInfo->getUid());
4951 return PERMISSION_DENIED;
4952 }
4953 mPreferredMixerAttrInfos[portId].erase(strategy);
4954 if (mPreferredMixerAttrInfos[portId].empty()) {
4955 mPreferredMixerAttrInfos.erase(portId);
4956 }
4957
4958 // Reconfig existing output
4959 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4960 for (size_t i = 0; i < mOutputs.size(); i++) {
4961 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4962 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4963 }
4964 }
4965 for (const auto output : potentialOutputsToReopen) {
4966 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4967 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4968 preferredMixerAttrInfo->getFlags())) {
4969 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4970 }
4971 }
4972 return NO_ERROR;
4973}
4974
Eric Laurent6a94d692014-05-20 11:18:06 -07004975status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4976 audio_port_type_t type,
4977 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004978 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004979 unsigned int *generation)
4980{
jiabin19cdba52020-11-24 11:28:58 -08004981 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4982 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004983 return BAD_VALUE;
4984 }
4985 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004986 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004987 *num_ports = 0;
4988 }
4989
4990 size_t portsWritten = 0;
4991 size_t portsMax = *num_ports;
4992 *num_ports = 0;
4993 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004994 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4995 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004996 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004997 for (const auto& dev : mAvailableOutputDevices) {
4998 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004999 continue;
5000 }
5001 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005002 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005003 }
5004 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005005 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005006 }
5007 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005008 for (const auto& dev : mAvailableInputDevices) {
5009 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07005010 continue;
5011 }
5012 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005013 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07005014 }
5015 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005017 }
5018 }
5019 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
5020 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
5021 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
5022 mInputs[i]->toAudioPort(&ports[portsWritten++]);
5023 }
5024 *num_ports += mInputs.size();
5025 }
5026 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07005027 size_t numOutputs = 0;
5028 for (size_t i = 0; i < mOutputs.size(); i++) {
5029 if (!mOutputs[i]->isDuplicated()) {
5030 numOutputs++;
5031 if (portsWritten < portsMax) {
5032 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
5033 }
5034 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005035 }
Eric Laurent84c70242014-06-23 08:46:27 -07005036 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07005037 }
5038 }
jiabina84c3d32022-12-02 18:59:55 +00005039
Eric Laurent6a94d692014-05-20 11:18:06 -07005040 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07005041 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07005042 return NO_ERROR;
5043}
5044
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005045status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
5046 std::vector<media::AudioPortFw>* _aidl_return) {
5047 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
5048 audio_port_v7 port;
5049 dev->toAudioPort(&port);
5050 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
5051 _aidl_return->push_back(std::move(aidlPort));
5052 return OK;
5053 };
5054
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005055 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07005056 for (const auto& dev : module->getDeclaredDevices()) {
5057 if (role == media::AudioPortRole::NONE ||
5058 ((role == media::AudioPortRole::SOURCE)
5059 == audio_is_input_device(dev->type()))) {
5060 RETURN_STATUS_IF_ERROR(pushPort(dev));
5061 }
5062 }
5063 }
5064 return OK;
5065}
5066
jiabin19cdba52020-11-24 11:28:58 -08005067status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07005068{
Eric Laurent99fcae42018-05-17 16:59:18 -07005069 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
5070 return BAD_VALUE;
5071 }
5072 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
5073 if (dev != 0) {
5074 dev->toAudioPort(port);
5075 return NO_ERROR;
5076 }
5077 dev = mAvailableInputDevices.getDeviceFromId(port->id);
5078 if (dev != 0) {
5079 dev->toAudioPort(port);
5080 return NO_ERROR;
5081 }
5082 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
5083 if (out != 0) {
5084 out->toAudioPort(port);
5085 return NO_ERROR;
5086 }
5087 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
5088 if (in != 0) {
5089 in->toAudioPort(port);
5090 return NO_ERROR;
5091 }
5092 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005093}
5094
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005095status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
5096 audio_patch_handle_t *handle,
5097 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005098{
François Gaffieafd4cea2019-11-18 15:50:22 +01005099 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005100 if (handle == NULL || patch == NULL) {
5101 return BAD_VALUE;
5102 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005103 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07005104 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07005105 return BAD_VALUE;
5106 }
5107 // only one source per audio patch supported for now
5108 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005109 return INVALID_OPERATION;
5110 }
Eric Laurent874c42872014-08-08 15:13:39 -07005111 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005112 return INVALID_OPERATION;
5113 }
Eric Laurent874c42872014-08-08 15:13:39 -07005114 for (size_t i = 0; i < patch->num_sinks; i++) {
5115 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
5116 return INVALID_OPERATION;
5117 }
5118 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005119
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005120 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
5121 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
5122 if (srcDevice == nullptr || sinkDevice == nullptr) {
5123 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
5124 return BAD_VALUE;
5125 }
5126 ALOGV("%s between source %s and sink %s", __func__,
5127 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
5128 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
5129 // Default attributes, default volume priority, not to infer with non raw audio patches.
5130 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
5131 const struct audio_port_config *source = &patch->sources[0];
5132 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01005133 new SourceClientDescriptor(
5134 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
5135 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005136 true, false /*isCallRx*/, false /*isCallTx*/);
Eric Laurent541a2002024-01-15 18:11:42 +01005137 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005138
5139 status_t status =
5140 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
5141
5142 if (status != NO_ERROR) {
5143 return INVALID_OPERATION;
5144 }
5145 mAudioSources.add(portId, sourceDesc);
5146 return NO_ERROR;
5147}
5148
5149status_t AudioPolicyManager::connectAudioSourceToSink(
5150 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5151 const struct audio_patch *patch,
5152 audio_patch_handle_t &handle,
5153 uid_t uid, uint32_t delayMs)
5154{
5155 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5156 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5157 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5158 return INVALID_OPERATION;
5159 }
5160 sourceDesc->connect(handle, sinkDevice);
5161 if (isMsdPatch(handle)) {
5162 return NO_ERROR;
5163 }
5164 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5165 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5166 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5167 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5168 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5169 goto FailurePatchAdded;
5170 }
5171 status = swOutput->start();
5172 if (status != NO_ERROR) {
5173 goto FailureSourceAdded;
5174 }
5175 swOutput->addClient(sourceDesc);
5176 status = startSource(swOutput, sourceDesc, &delayMs);
5177 if (status != NO_ERROR) {
5178 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5179 goto FailureSourceActive;
5180 }
5181 if (delayMs != 0) {
5182 usleep(delayMs * 1000);
5183 }
5184 return NO_ERROR;
5185
5186FailureSourceActive:
5187 swOutput->stop();
5188 releaseOutput(sourceDesc->portId());
5189FailureSourceAdded:
5190 sourceDesc->setSwOutput(nullptr);
5191FailurePatchAdded:
5192 releaseAudioPatchInternal(handle);
5193 return INVALID_OPERATION;
5194}
5195
5196status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5197 audio_patch_handle_t *handle,
5198 uid_t uid, uint32_t delayMs,
5199 const sp<SourceClientDescriptor>& sourceDesc)
5200{
5201 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005202 sp<AudioPatch> patchDesc;
5203 ssize_t index = mAudioPatches.indexOfKey(*handle);
5204
François Gaffieafd4cea2019-11-18 15:50:22 +01005205 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5206 patch->sources[0].role,
5207 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005208#if LOG_NDEBUG == 0
5209 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005210 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5211 patch->sinks[i].role,
5212 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005213 }
5214#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005215
5216 if (index >= 0) {
5217 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005218 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5219 __func__, mUidCached, patchDesc->getUid(), uid);
5220 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005221 return INVALID_OPERATION;
5222 }
5223 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005224 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005225 }
5226
5227 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005228 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005229 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005230 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 return BAD_VALUE;
5232 }
Eric Laurent84c70242014-06-23 08:46:27 -07005233 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5234 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005235 if (patchDesc != 0) {
5236 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005237 ALOGV("%s source id differs for patch current id %d new id %d",
5238 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005239 return BAD_VALUE;
5240 }
5241 }
Eric Laurent874c42872014-08-08 15:13:39 -07005242 DeviceVector devices;
5243 for (size_t i = 0; i < patch->num_sinks; i++) {
5244 // Only support mix to devices connection
5245 // TODO add support for mix to mix connection
5246 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005247 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005248 return INVALID_OPERATION;
5249 }
5250 sp<DeviceDescriptor> devDesc =
5251 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5252 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005253 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005254 return BAD_VALUE;
5255 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005256
jiabin66acc432024-02-06 00:57:36 +00005257 if (outputDesc->mProfile->getCompatibilityScore(
5258 DeviceVector(devDesc),
5259 patch->sources[0].sample_rate,
5260 nullptr, // updatedSamplingRate
5261 patch->sources[0].format,
5262 nullptr, // updatedFormat
5263 patch->sources[0].channel_mask,
5264 nullptr, // updatedChannelMask
5265 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005266 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005267 return INVALID_OPERATION;
5268 }
5269 devices.add(devDesc);
5270 }
5271 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005272 return INVALID_OPERATION;
5273 }
Eric Laurent874c42872014-08-08 15:13:39 -07005274
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005276 ALOGV("%s setting device %s on output %d",
5277 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305278 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005279 index = mAudioPatches.indexOfKey(*handle);
5280 if (index >= 0) {
5281 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005282 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 }
5284 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005285 patchDesc->setUid(uid);
5286 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005287 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005288 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005289 return INVALID_OPERATION;
5290 }
5291 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5292 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5293 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005294 // only one sink supported when connecting an input device to a mix
5295 if (patch->num_sinks > 1) {
5296 return INVALID_OPERATION;
5297 }
François Gaffie53615e22015-03-19 09:24:12 +01005298 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005299 if (inputDesc == NULL) {
5300 return BAD_VALUE;
5301 }
5302 if (patchDesc != 0) {
5303 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5304 return BAD_VALUE;
5305 }
5306 }
François Gaffie11d30102018-11-02 16:09:09 +01005307 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005308 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005309 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005310 return BAD_VALUE;
5311 }
5312
jiabin66acc432024-02-06 00:57:36 +00005313 if (inputDesc->mProfile->getCompatibilityScore(
5314 DeviceVector(device),
5315 patch->sinks[0].sample_rate,
5316 nullptr, /*updatedSampleRate*/
5317 patch->sinks[0].format,
5318 nullptr, /*updatedFormat*/
5319 patch->sinks[0].channel_mask,
5320 nullptr, /*updatedChannelMask*/
5321 // FIXME for the parameter type,
5322 // and the NONE
5323 (audio_output_flags_t)
5324 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005325 return INVALID_OPERATION;
5326 }
5327 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005328 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005329 device->toString().c_str(), inputDesc->mIoHandle);
5330 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005331 index = mAudioPatches.indexOfKey(*handle);
5332 if (index >= 0) {
5333 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005334 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005335 }
5336 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005337 patchDesc->setUid(uid);
5338 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005339 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005340 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005341 return INVALID_OPERATION;
5342 }
5343 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5344 // device to device connection
5345 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005346 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005347 return BAD_VALUE;
5348 }
5349 }
François Gaffie11d30102018-11-02 16:09:09 +01005350 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005351 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005352 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005353 return BAD_VALUE;
5354 }
Eric Laurent874c42872014-08-08 15:13:39 -07005355
Eric Laurent6a94d692014-05-20 11:18:06 -07005356 //update source and sink with our own data as the data passed in the patch may
5357 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005358 PatchBuilder patchBuilder;
5359 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005360
5361 // if first sink is to MSD, establish single MSD patch
5362 if (getMsdAudioOutDevices().contains(
5363 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5364 ALOGV("%s patching to MSD", __FUNCTION__);
5365 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5366 goto installPatch;
5367 }
5368
François Gaffieafd4cea2019-11-18 15:50:22 +01005369 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5370 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005371
Eric Laurent874c42872014-08-08 15:13:39 -07005372 for (size_t i = 0; i < patch->num_sinks; i++) {
5373 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005374 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005375 return INVALID_OPERATION;
5376 }
François Gaffie11d30102018-11-02 16:09:09 +01005377 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005378 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005379 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005380 return BAD_VALUE;
5381 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005382 audio_port_config sinkPortConfig = {};
5383 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5384 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005385
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005386 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5387 // volume management purpose (tracking activity)
5388 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5389 // in config XML to reach the sink so that is can be declared as available.
5390 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005391 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005392 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005393 // take care of dynamic routing for SwOutput selection,
5394 audio_attributes_t attributes = sourceDesc->attributes();
5395 audio_stream_type_t stream = sourceDesc->stream();
5396 audio_attributes_t resultAttr;
5397 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5398 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005399 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5400 config.channel_mask =
5401 (audio_channel_mask_get_representation(sourceMask)
5402 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5403 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005404 config.format = sourceDesc->config().format;
5405 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5406 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5407 bool isRequestedDeviceForExclusiveUse = false;
5408 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005409 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005410 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005411 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5412 &stream, sourceDesc->uid(), &config, &flags,
5413 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005414 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005415 if (output == AUDIO_IO_HANDLE_NONE) {
5416 ALOGV("%s no output for device %s",
5417 __FUNCTION__, sinkDevice->toString().c_str());
5418 return INVALID_OPERATION;
5419 }
5420 outputDesc = mOutputs.valueFor(output);
5421 if (outputDesc->isDuplicated()) {
5422 ALOGE("%s output is duplicated", __func__);
5423 return INVALID_OPERATION;
5424 }
François Gaffie7e39df22022-04-26 12:48:49 +02005425 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5426 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005427 } else {
5428 // Same for "raw patches" aka created from createAudioPatch API
5429 SortedVector<audio_io_handle_t> outputs =
5430 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5431 // if the sink device is reachable via an opened output stream, request to
5432 // go via this output stream by adding a second source to the patch
5433 // description
5434 output = selectOutput(outputs);
5435 if (output == AUDIO_IO_HANDLE_NONE) {
5436 ALOGE("%s no output available for internal patch sink", __func__);
5437 return INVALID_OPERATION;
5438 }
5439 outputDesc = mOutputs.valueFor(output);
5440 if (outputDesc->isDuplicated()) {
5441 ALOGV("%s output for device %s is duplicated",
5442 __func__, sinkDevice->toString().c_str());
5443 return INVALID_OPERATION;
5444 }
François Gaffie7e39df22022-04-26 12:48:49 +02005445 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005446 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005447 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005448 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005449 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005450 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005451 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5452 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005453 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5454 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005455 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005456 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005457 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005458 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005459 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005460 return INVALID_OPERATION;
5461 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005462 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005463 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005464 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005465 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005466 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005467 srcMixPortConfig.ext.mix.usecase.stream =
Eric Laurent963dbcc2024-06-20 12:34:15 +00005468 (!sourceDesc->isInternal() || sourceDesc->isCallTx()) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005469 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5470 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005471 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005472 }
Eric Laurent83b88082014-06-20 18:31:16 -07005473 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005474 }
5475 // TODO: check from routing capabilities in config file and other conflicting patches
5476
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005477installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005478 status_t status = installPatch(
5479 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005480 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005481 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005482 return INVALID_OPERATION;
5483 }
5484 } else {
5485 return BAD_VALUE;
5486 }
5487 } else {
5488 return BAD_VALUE;
5489 }
5490 return NO_ERROR;
5491}
5492
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005493status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005494{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005495 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005496 ssize_t index = mAudioPatches.indexOfKey(handle);
5497
5498 if (index < 0) {
5499 return BAD_VALUE;
5500 }
5501 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005502 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5503 __func__, mUidCached, patchDesc->getUid(), uid);
5504 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005505 return INVALID_OPERATION;
5506 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005507 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5508 for (size_t i = 0; i < mAudioSources.size(); i++) {
5509 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5510 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5511 portId = sourceDesc->portId();
5512 break;
5513 }
5514 }
5515 return portId != AUDIO_PORT_HANDLE_NONE ?
5516 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005517}
Eric Laurent6a94d692014-05-20 11:18:06 -07005518
François Gaffieafd4cea2019-11-18 15:50:22 +01005519status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005520 uint32_t delayMs,
5521 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005522{
5523 ALOGV("%s patch %d", __func__, handle);
5524 if (mAudioPatches.indexOfKey(handle) < 0) {
5525 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5526 return BAD_VALUE;
5527 }
5528 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005529 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005530 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005531 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005532 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005533 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005534 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005535 return BAD_VALUE;
5536 }
5537
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305538 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005539 getNewOutputDevices(outputDesc, true /*fromCache*/),
5540 true,
5541 0,
5542 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005543 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5544 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005545 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005546 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005547 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005548 return BAD_VALUE;
5549 }
5550 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005551 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005552 true,
5553 NULL);
5554 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005555 status_t status =
5556 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5557 ALOGV("%s patch panel returned %d patchHandle %d",
5558 __func__, status, patchDesc->getAfHandle());
5559 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005560 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005561 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005562 // SW or HW Bridge
5563 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5564 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005565 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005566 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5567 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5568 outputDesc = sourceDesc->swOutput().promote();
5569 }
5570 if (outputDesc == nullptr) {
5571 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5572 // releaseOutput has already called closeOutput in case of direct output
5573 return NO_ERROR;
5574 }
François Gaffie7e39df22022-04-26 12:48:49 +02005575 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005576 // While using a HwBridge, force reconsidering device only if not reusing an existing
5577 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005578 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005579 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5580 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5581 // Reconsider device only for cases:
5582 // 1 / Active Output
5583 // 2 / Inactive Output previously hosting HwBridge
5584 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5585 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5586 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305587 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005588 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5589 outputDesc->devices(),
5590 force,
5591 0,
5592 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005593 } else {
5594 return BAD_VALUE;
5595 }
5596 } else {
5597 return BAD_VALUE;
5598 }
5599 return NO_ERROR;
5600}
5601
5602status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5603 struct audio_patch *patches,
5604 unsigned int *generation)
5605{
François Gaffie53615e22015-03-19 09:24:12 +01005606 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005607 return BAD_VALUE;
5608 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005609 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005610 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005611}
5612
Eric Laurente1715a42014-05-20 11:30:42 -07005613status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005614{
Eric Laurente1715a42014-05-20 11:30:42 -07005615 ALOGV("setAudioPortConfig()");
5616
5617 if (config == NULL) {
5618 return BAD_VALUE;
5619 }
5620 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5621 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005622 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5623 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005624 }
5625
Eric Laurenta121f902014-06-03 13:32:54 -07005626 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005627 if (config->type == AUDIO_PORT_TYPE_MIX) {
5628 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005629 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005630 if (outputDesc == NULL) {
5631 return BAD_VALUE;
5632 }
Eric Laurent84c70242014-06-23 08:46:27 -07005633 ALOG_ASSERT(!outputDesc->isDuplicated(),
5634 "setAudioPortConfig() called on duplicated output %d",
5635 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005636 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005637 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005638 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005639 if (inputDesc == NULL) {
5640 return BAD_VALUE;
5641 }
Eric Laurenta121f902014-06-03 13:32:54 -07005642 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005643 } else {
5644 return BAD_VALUE;
5645 }
5646 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5647 sp<DeviceDescriptor> deviceDesc;
5648 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5649 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5650 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5651 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5652 } else {
5653 return BAD_VALUE;
5654 }
5655 if (deviceDesc == NULL) {
5656 return BAD_VALUE;
5657 }
Eric Laurenta121f902014-06-03 13:32:54 -07005658 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005659 } else {
5660 return BAD_VALUE;
5661 }
5662
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005663 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005664 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5665 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005666 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005667 audioPortConfig->toAudioPortConfig(&newConfig, config);
5668 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005669 }
Eric Laurenta121f902014-06-03 13:32:54 -07005670 if (status != NO_ERROR) {
5671 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005672 }
Eric Laurente1715a42014-05-20 11:30:42 -07005673
5674 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005675}
5676
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005677void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5678{
Eric Laurentd60560a2015-04-10 11:31:20 -07005679 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005680 clearAudioPatches(uid);
5681 clearSessionRoutes(uid);
5682}
5683
Eric Laurent6a94d692014-05-20 11:18:06 -07005684void AudioPolicyManager::clearAudioPatches(uid_t uid)
5685{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005686 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005687 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005688 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005689 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005690 }
5691 }
5692}
5693
François Gaffiec005e562018-11-06 15:04:49 +01005694void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005695{
François Gaffiec005e562018-11-06 15:04:49 +01005696 // Take the first attributes following the product strategy as it is used to retrieve the routed
5697 // device. All attributes wihin a strategy follows the same "routing strategy"
5698 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5699 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005700 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005701 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005702 for (size_t j = 0; j < mOutputs.size(); j++) {
5703 if (mOutputs.keyAt(j) == ouptutToSkip) {
5704 continue;
5705 }
5706 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005707 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005708 continue;
5709 }
5710 // If the default device for this strategy is on another output mix,
5711 // invalidate all tracks in this strategy to force re connection.
5712 // Otherwise select new device on the output mix.
5713 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005714 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005715 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005716 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
jiabin220eea12024-05-17 17:55:20 +00005717 if (outputDesc->mPreferredAttrInfo != nullptr && outputDesc->devices() != newDevices) {
jiabin3ff8d7d2022-12-13 06:27:44 +00005718 // If the device is using preferred mixer attributes, the output need to reopen
5719 // with default configuration when the new selected devices are different from
5720 // current routing devices.
5721 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5722 continue;
5723 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305724 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005725 }
5726 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005727 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005728}
5729
5730void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5731{
5732 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005733 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005734 for (size_t i = 0; i < mOutputs.size(); i++) {
5735 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005736 for (const auto& client : outputDesc->getClientIterable()) {
5737 if (client->hasPreferredDevice() && client->uid() == uid) {
5738 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005739 auto clientStrategy = client->strategy();
5740 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5741 end(affectedStrategies)) {
5742 continue;
5743 }
5744 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005745 }
5746 }
5747 }
5748 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005749 for (const auto& strategy : affectedStrategies) {
5750 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005751 }
5752
5753 // remove input routes associated with this uid
5754 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005755 for (size_t i = 0; i < mInputs.size(); i++) {
5756 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005757 for (const auto& client : inputDesc->getClientIterable()) {
5758 if (client->hasPreferredDevice() && client->uid() == uid) {
5759 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5760 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005761 }
5762 }
5763 }
5764 // reroute inputs if necessary
5765 SortedVector<audio_io_handle_t> inputsToClose;
5766 for (size_t i = 0; i < mInputs.size(); i++) {
5767 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005768 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005769 inputsToClose.add(inputDesc->mIoHandle);
5770 }
5771 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005772 for (const auto& input : inputsToClose) {
5773 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005774 }
5775}
5776
Eric Laurentd60560a2015-04-10 11:31:20 -07005777void AudioPolicyManager::clearAudioSources(uid_t uid)
5778{
5779 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005780 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5781 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005782 stopAudioSource(mAudioSources.keyAt(i));
5783 }
5784 }
5785}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005786
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005787status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5788 audio_io_handle_t *ioHandle,
5789 audio_devices_t *device)
5790{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005791 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5792 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005793 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005794 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5795 if (deviceDesc == nullptr) {
5796 return INVALID_OPERATION;
5797 }
5798 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005799
François Gaffiedf372692015-03-19 10:43:27 +01005800 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005801}
5802
Eric Laurentd60560a2015-04-10 11:31:20 -07005803status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005804 const audio_attributes_t *attributes,
5805 audio_port_handle_t *portId,
Eric Laurent963dbcc2024-06-20 12:34:15 +00005806 uid_t uid) {
5807 return startAudioSourceInternal(source, attributes, portId, uid,
David Li48b6a832024-07-01 13:14:10 +00005808 false /*internal*/, false /*isCallRx*/, 0 /*delayMs*/);
Eric Laurent963dbcc2024-06-20 12:34:15 +00005809}
5810
5811status_t AudioPolicyManager::startAudioSourceInternal(const struct audio_port_config *source,
5812 const audio_attributes_t *attributes,
5813 audio_port_handle_t *portId,
David Li48b6a832024-07-01 13:14:10 +00005814 uid_t uid, bool internal, bool isCallRx,
5815 uint32_t delayMs)
Eric Laurent554a2772015-04-10 11:29:24 -07005816{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005817 ALOGV("%s", __FUNCTION__);
5818 *portId = AUDIO_PORT_HANDLE_NONE;
5819
5820 if (source == NULL || attributes == NULL || portId == NULL) {
5821 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5822 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005823 return BAD_VALUE;
5824 }
5825
Eric Laurentd60560a2015-04-10 11:31:20 -07005826 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5827 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005828 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5829 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005830 return INVALID_OPERATION;
5831 }
5832
François Gaffie11d30102018-11-02 16:09:09 +01005833 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005834 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005835 String8(source->ext.device.address),
5836 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005837 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005838 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005839 return BAD_VALUE;
5840 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005841
jiabin4ef93452019-09-10 14:29:54 -07005842 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005843
François Gaffieaaac0fd2018-11-22 17:56:39 +01005844 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005845 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005846 mEngine->getStreamTypeForAttributes(*attributes),
5847 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent963dbcc2024-06-20 12:34:15 +00005848 toVolumeSource(*attributes), internal, isCallRx, false);
Eric Laurentd60560a2015-04-10 11:31:20 -07005849
David Li48b6a832024-07-01 13:14:10 +00005850 status_t status = connectAudioSource(sourceDesc, delayMs);
Eric Laurentd60560a2015-04-10 11:31:20 -07005851 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005852 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005853 }
5854 return status;
5855}
5856
David Li48b6a832024-07-01 13:14:10 +00005857status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc,
5858 uint32_t delayMs)
Eric Laurentd60560a2015-04-10 11:31:20 -07005859{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005860 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005861
5862 // make sure we only have one patch per source.
5863 disconnectAudioSource(sourceDesc);
5864
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005865 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005866 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5867 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5868 sourceDesc->srcDevice()->type(),
5869 String8(sourceDesc->srcDevice()->address().c_str()),
5870 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005871 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005872 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005873 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005874 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005875 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5876 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5877 return INVALID_OPERATION;
5878 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005879 PatchBuilder patchBuilder;
5880 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5881 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005882
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005883 return connectAudioSourceToSink(
David Li48b6a832024-07-01 13:14:10 +00005884 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, delayMs);
Eric Laurent554a2772015-04-10 11:29:24 -07005885}
5886
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005887status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005888{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005889 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5890 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005891 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005892 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005893 return BAD_VALUE;
5894 }
5895 status_t status = disconnectAudioSource(sourceDesc);
5896
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005897 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005898 return status;
5899}
5900
Andy Hung2ddee192015-12-18 17:34:44 -08005901status_t AudioPolicyManager::setMasterMono(bool mono)
5902{
5903 if (mMasterMono == mono) {
5904 return NO_ERROR;
5905 }
5906 mMasterMono = mono;
5907 // if enabling mono we close all offloaded devices, which will invalidate the
5908 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5909 // for recreating the new AudioTrack as non-offloaded PCM.
5910 //
5911 // If disabling mono, we leave all tracks as is: we don't know which clients
5912 // and tracks are able to be recreated as offloaded. The next "song" should
5913 // play back offloaded.
5914 if (mMasterMono) {
5915 Vector<audio_io_handle_t> offloaded;
5916 for (size_t i = 0; i < mOutputs.size(); ++i) {
5917 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5918 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5919 offloaded.push(desc->mIoHandle);
5920 }
5921 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005922 for (const auto& handle : offloaded) {
5923 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005924 }
5925 }
5926 // update master mono for all remaining outputs
5927 for (size_t i = 0; i < mOutputs.size(); ++i) {
5928 updateMono(mOutputs.keyAt(i));
5929 }
5930 return NO_ERROR;
5931}
5932
5933status_t AudioPolicyManager::getMasterMono(bool *mono)
5934{
5935 *mono = mMasterMono;
5936 return NO_ERROR;
5937}
5938
Eric Laurentac9cef52017-06-09 15:46:26 -07005939float AudioPolicyManager::getStreamVolumeDB(
5940 audio_stream_type_t stream, int index, audio_devices_t device)
5941{
jiabin9a3361e2019-10-01 09:38:30 -07005942 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005943}
5944
jiabin81772902018-04-02 17:52:27 -07005945status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5946 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005947 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005948{
Kriti Dang6537def2021-03-02 13:46:59 +01005949 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5950 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005951 return BAD_VALUE;
5952 }
Kriti Dang6537def2021-03-02 13:46:59 +01005953 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5954 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005955
5956 size_t formatsWritten = 0;
5957 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005958
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005959 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005960 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5961 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005962 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005963 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005964 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005965 bool formatEnabled = true;
5966 switch (forceUse) {
5967 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005968 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005969 break;
5970 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5971 formatEnabled = false;
5972 break;
5973 default: // AUTO or ALWAYS => true
5974 break;
jiabin81772902018-04-02 17:52:27 -07005975 }
5976 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5977 }
jiabin81772902018-04-02 17:52:27 -07005978 }
5979 return NO_ERROR;
5980}
5981
Kriti Dang6537def2021-03-02 13:46:59 +01005982status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5983 audio_format_t *surroundFormats) {
5984 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5985 return BAD_VALUE;
5986 }
5987 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5988 __func__, *numSurroundFormats, surroundFormats);
5989
5990 size_t formatsWritten = 0;
5991 size_t formatsMax = *numSurroundFormats;
5992 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5993
5994 // Return formats from all device profiles that have already been resolved by
5995 // checkOutputsForDevice().
5996 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5997 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5998 audio_devices_t deviceType = device->type();
5999 // Enabling/disabling formats are applied to only HDMI devices. So, this function
6000 // returns formats reported by HDMI devices.
6001 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
6002 continue;
6003 }
6004 // Formats reported by sink devices
6005 std::unordered_set<audio_format_t> formatset;
6006 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
6007 formatset.insert(it->second.begin(), it->second.end());
6008 }
6009
6010 // Formats hard-coded in the in policy configuration file (if any).
6011 FormatVector encodedFormats = device->encodedFormats();
6012 formatset.insert(encodedFormats.begin(), encodedFormats.end());
6013 // Filter the formats which are supported by the vendor hardware.
6014 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006015 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01006016 formats.insert(*it);
6017 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006018 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01006019 if (pair.second.count(*it) != 0) {
6020 formats.insert(pair.first);
6021 break;
6022 }
6023 }
6024 }
6025 }
6026 }
6027 *numSurroundFormats = formats.size();
6028 for (const auto& format: formats) {
6029 if (formatsWritten < formatsMax) {
6030 surroundFormats[formatsWritten++] = format;
6031 }
6032 }
6033 return NO_ERROR;
6034}
6035
jiabin81772902018-04-02 17:52:27 -07006036status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
6037{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006038 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006039 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
6040 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006041 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07006042 return BAD_VALUE;
6043 }
6044
Mikhail Naganov100f0122018-11-29 11:22:16 -08006045 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
6046 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006047 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07006048 return INVALID_OPERATION;
6049 }
6050
Mikhail Naganov100f0122018-11-29 11:22:16 -08006051 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07006052 return NO_ERROR;
6053 }
6054
Mikhail Naganov100f0122018-11-29 11:22:16 -08006055 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07006056 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006057 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006058 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006059 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07006060 }
6061 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006062 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07006063 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08006064 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07006065 }
6066 }
6067
6068 sp<SwAudioOutputDescriptor> outputDesc;
6069 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07006070 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
6071 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07006072 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
6073 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006074 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006075 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006076 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6077 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6078 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006079 name.c_str(),
6080 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006081 if (status != NO_ERROR) {
6082 continue;
6083 }
6084 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
6085 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6086 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006087 name.c_str(),
6088 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006089 profileUpdated |= (status == NO_ERROR);
6090 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08006091 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07006092 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07006093 AUDIO_DEVICE_IN_HDMI);
6094 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
6095 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07006096 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07006097 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07006098 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6099 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
6100 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006101 name.c_str(),
6102 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006103 if (status != NO_ERROR) {
6104 continue;
6105 }
6106 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
6107 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
6108 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006109 name.c_str(),
6110 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07006111 profileUpdated |= (status == NO_ERROR);
6112 }
6113
jiabin81772902018-04-02 17:52:27 -07006114 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07006115 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08006116 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07006117 }
6118
6119 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
6120}
6121
Eric Laurent5ada82e2019-08-29 17:53:54 -07006122void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006123{
Eric Laurent5ada82e2019-08-29 17:53:54 -07006124 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08006125 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07006126 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08006127 }
6128}
6129
jiabin6012f912018-11-02 17:06:30 -07006130bool AudioPolicyManager::isHapticPlaybackSupported()
6131{
6132 for (const auto& hwModule : mHwModules) {
6133 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6134 for (const auto &outProfile : outputProfiles) {
6135 struct audio_port audioPort;
6136 outProfile->toAudioPort(&audioPort);
6137 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
6138 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
6139 return true;
6140 }
6141 }
6142 }
6143 }
6144 return false;
6145}
6146
Carter Hsu325a8eb2022-01-19 19:56:51 +08006147bool AudioPolicyManager::isUltrasoundSupported()
6148{
6149 bool hasUltrasoundOutput = false;
6150 bool hasUltrasoundInput = false;
6151 for (const auto& hwModule : mHwModules) {
6152 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
6153 if (!hasUltrasoundOutput) {
6154 for (const auto &outProfile : outputProfiles) {
6155 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
6156 hasUltrasoundOutput = true;
6157 break;
6158 }
6159 }
6160 }
6161
6162 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6163 if (!hasUltrasoundInput) {
6164 for (const auto &inputProfile : inputProfiles) {
6165 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6166 hasUltrasoundInput = true;
6167 break;
6168 }
6169 }
6170 }
6171
6172 if (hasUltrasoundOutput && hasUltrasoundInput)
6173 return true;
6174 }
6175 return false;
6176}
6177
Atneya Nair698f5ef2022-12-15 16:15:09 -08006178bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6179{
6180 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6181 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6182 for (const auto& hwModule : mHwModules) {
6183 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6184 for (const auto &inputProfile : inputProfiles) {
6185 if ((inputProfile->getFlags() & mask) == mask) {
6186 return true;
6187 }
6188 }
6189 }
6190 return false;
6191}
6192
Eric Laurent8340e672019-11-06 11:01:08 -08006193bool AudioPolicyManager::isCallScreenModeSupported()
6194{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006195 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006196}
6197
6198
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006199status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006200{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006201 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006202 if (!sourceDesc->isConnected()) {
6203 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6204 return NO_ERROR;
6205 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006206 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6207 if (swOutput != 0) {
6208 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006209 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006210 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006211 }
jiabinbce0c1d2020-10-05 11:20:18 -07006212 if (releaseOutput(sourceDesc->portId())) {
6213 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6214 // no need to release audio patch here but just return NO_ERROR.
6215 return NO_ERROR;
6216 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006217 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006218 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006219 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006220 // close Hwoutput and remove from mHwOutputs
6221 } else {
6222 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6223 }
6224 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006225 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006226 sourceDesc->disconnect();
6227 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006228}
6229
François Gaffiec005e562018-11-06 15:04:49 +01006230sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6231 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006232{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006233 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006234 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006235 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006236 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006237 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6238 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006239 source = sourceDesc;
6240 break;
6241 }
6242 }
6243 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006244}
6245
Eric Laurentb4f42a92022-01-17 17:37:31 +01006246bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006247 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006248 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006249{
6250 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6251 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006252 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006253 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006254 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6255 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6256 return false;
6257 }
6258 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6259 return false;
6260 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006261 }
6262
Eric Laurentd332bc82023-08-04 11:45:23 +02006263 // The caller can have the audio config criteria ignored by either passing a null ptr or
6264 // the AUDIO_CONFIG_INITIALIZER value.
6265 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006266 // some positional channel masks and PCM format and for stereo if low latency performance
6267 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006268
6269 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006270 static const bool stereo_spatialization_enabled =
6271 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006272 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006273 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006274 ? audio_channel_mask_contains_stereo(config->channel_mask)
6275 : audio_is_channel_mask_spatialized(config->channel_mask);
6276 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006277 return false;
6278 }
6279 if (!audio_is_linear_pcm(config->format)) {
6280 return false;
6281 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006282 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6283 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6284 return false;
6285 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006286 }
6287
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006288 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006289 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006290 if (profile == nullptr) {
6291 return false;
6292 }
6293
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006294 return true;
6295}
6296
Shunkai Yao57b93392024-04-26 04:12:21 +00006297// The Spatializer output is compatible with Haptic use cases if:
6298// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6299// with client if client haptic channel bits were set, or
6300// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6301// including the haptic bits or creating the HapticGenerator effect for same session.
6302bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6303 const audio_config_t* config, audio_session_t sessionId) const {
6304 const auto clientHapticChannel =
6305 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6306 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6307 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6308
6309 if (threadOutputHapticChannel) {
6310 // check format and sampleRate match if client haptic channel mask exist
6311 if (clientHapticChannel) {
6312 return mSpatializerOutput->getFormat() == config->format &&
6313 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6314 }
6315 return true;
6316 } else {
6317 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6318 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6319 // HapticGenerator effect for this session) are not supported.
6320 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006321 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao57b93392024-04-26 04:12:21 +00006322 }
6323}
6324
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006325void AudioPolicyManager::checkVirtualizerClientRoutes() {
6326 std::set<audio_stream_type_t> streamsToInvalidate;
6327 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006328 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6329 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006330 audio_attributes_t attr = client->attributes();
6331 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6332 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6333 audio_config_base_t clientConfig = client->config();
6334 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006335 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006336 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006337 streamsToInvalidate.insert(client->stream());
6338 }
6339 }
6340 }
6341
jiabinc44b3462022-12-08 12:52:31 -08006342 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006343}
6344
Eric Laurente191d1b2022-04-15 11:59:25 +02006345
6346bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6347 const sp<SwAudioOutputDescriptor>& outputDesc) {
6348 if (outputDesc->isDuplicated()) {
6349 return false;
6350 }
6351 DeviceVector devices = outputDesc->supportedDevices();
6352 for (size_t i = 0; i < mOutputs.size(); i++) {
6353 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6354 if (desc == outputDesc || desc->isDuplicated()) {
6355 continue;
6356 }
6357 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6358 if (!sharedDevices.isEmpty()
6359 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6360 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6361 return false;
6362 }
6363 }
6364 return true;
6365}
6366
6367
Eric Laurentfa0f6742021-08-17 18:39:44 +02006368status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006369 const audio_attributes_t *attr,
6370 audio_io_handle_t *output) {
6371 *output = AUDIO_IO_HANDLE_NONE;
6372
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006373 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6374 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6375 audio_config_t *configPtr = nullptr;
6376 audio_config_t config;
6377 if (mixerConfig != nullptr) {
6378 config = audio_config_initializer(mixerConfig);
6379 configPtr = &config;
6380 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006381 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006382 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006383 return BAD_VALUE;
6384 }
6385
6386 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006387 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006388 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006389 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006390 return BAD_VALUE;
6391 }
6392
Eric Laurente191d1b2022-04-15 11:59:25 +02006393 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006394 for (size_t i = 0; i < mOutputs.size(); i++) {
6395 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006396 if (!desc->isDuplicated()
6397 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6398 spatializerOutputs.push_back(desc);
6399 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006400 }
6401 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006402 mSpatializerOutput.clear();
6403 bool outputsChanged = false;
6404 for (const auto& desc : spatializerOutputs) {
6405 if (desc->mProfile == profile
6406 && (configPtr == nullptr
6407 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6408 mSpatializerOutput = desc;
6409 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6410 } else {
6411 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6412 " and devices %s", __func__, desc->mIoHandle,
6413 configPtr != nullptr ? configPtr->channel_mask : 0,
6414 devices.toString().c_str());
6415 closeOutput(desc->mIoHandle);
6416 outputsChanged = true;
6417 }
Eric Laurent39095982021-08-24 18:29:27 +02006418 }
6419
Eric Laurente191d1b2022-04-15 11:59:25 +02006420 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006421 sp<SwAudioOutputDescriptor> desc =
6422 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006423 if (desc != nullptr) {
6424 mSpatializerOutput = desc;
6425 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006426 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006427 }
6428
6429 checkVirtualizerClientRoutes();
6430
Eric Laurente191d1b2022-04-15 11:59:25 +02006431 if (outputsChanged) {
6432 mPreviousOutputs = mOutputs;
6433 mpClientInterface->onAudioPortListUpdate();
6434 }
6435
6436 if (mSpatializerOutput == nullptr) {
6437 ALOGV("%s could not open spatializer output with requested config", __func__);
6438 return BAD_VALUE;
6439 }
Eric Laurent39095982021-08-24 18:29:27 +02006440 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006441 ALOGV("%s returning new spatializer output %d", __func__, *output);
6442 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006443}
6444
Eric Laurentfa0f6742021-08-17 18:39:44 +02006445status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6446 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006447 return INVALID_OPERATION;
6448 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006449 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006450 return BAD_VALUE;
6451 }
Eric Laurent39095982021-08-24 18:29:27 +02006452
Eric Laurente191d1b2022-04-15 11:59:25 +02006453 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6454 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6455 closeOutput(mSpatializerOutput->mIoHandle);
6456 //from now on mSpatializerOutput is null
6457 checkVirtualizerClientRoutes();
6458 }
Eric Laurent39095982021-08-24 18:29:27 +02006459
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006460 return NO_ERROR;
6461}
6462
Eric Laurente552edb2014-03-10 17:42:56 -07006463// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006464// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006465// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006466uint32_t AudioPolicyManager::nextAudioPortGeneration()
6467{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006468 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006469}
6470
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006471AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006472 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006473 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006474 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006475 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006476 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006477 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006478 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006479 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006480 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006481 mAudioPortGeneration(1),
6482 mBeaconMuteRefCount(0),
6483 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006484 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006485 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006486 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006487 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006488{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006489}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006490
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006491status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006492 if (mEngine == nullptr) {
6493 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006494 }
6495 mEngine->setObserver(this);
6496 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006497 if (status != NO_ERROR) {
6498 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6499 return status;
6500 }
François Gaffie2110e042015-03-24 08:41:51 +01006501
jiabin29230182023-04-04 21:02:36 +00006502 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6503 // at the end of this function.
6504 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006505 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6506 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6507
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006508 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006509 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006510 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006511
Eric Laurent3a4311c2014-03-17 12:00:47 -07006512 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006513 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6514 defaultOutputDevice == nullptr ||
6515 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6516 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6517 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006518 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006519 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006520 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006521
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006522 // Silence ALOGV statements
6523 property_set("log.tag." LOG_TAG, "D");
6524
Eric Laurente552edb2014-03-10 17:42:56 -07006525 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006526 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006527}
6528
Eric Laurente0720872014-03-11 09:30:41 -07006529AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006530{
Eric Laurente552edb2014-03-10 17:42:56 -07006531 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006532 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006533 }
6534 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006535 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006536 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006537 mAvailableOutputDevices.clear();
6538 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006539 mOutputs.clear();
6540 mInputs.clear();
6541 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006542 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006543 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006544}
6545
Eric Laurente0720872014-03-11 09:30:41 -07006546status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006547{
Eric Laurent87ffa392015-05-22 10:32:38 -07006548 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006549}
6550
Eric Laurente552edb2014-03-10 17:42:56 -07006551// ---
6552
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006553void AudioPolicyManager::onNewAudioModulesAvailable()
6554{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006555 DeviceVector newDevices;
6556 onNewAudioModulesAvailableInt(&newDevices);
6557 if (!newDevices.empty()) {
6558 nextAudioPortGeneration();
6559 mpClientInterface->onAudioPortListUpdate();
6560 }
6561}
6562
6563void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6564{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006565 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006566 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6567 continue;
6568 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006569 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006570 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6571 handle != AUDIO_MODULE_HANDLE_NONE) {
6572 hwModule->setHandle(handle);
6573 } else {
6574 ALOGW("could not load HW module %s", hwModule->getName());
6575 continue;
6576 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006577 }
6578 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006579 // open all output streams needed to access attached devices.
6580 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006581 // This also validates mAvailableOutputDevices list
6582 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6583 if (!outProfile->canOpenNewIo()) {
6584 ALOGE("Invalid Output profile max open count %u for profile %s",
6585 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6586 continue;
6587 }
6588 if (!outProfile->hasSupportedDevices()) {
6589 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6590 continue;
6591 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006592 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6593 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006594 mTtsOutputAvailable = true;
6595 }
6596
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006597 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006598 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006599 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006600 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6601 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006602 } else {
6603 // choose first device present in profile's SupportedDevices also part of
6604 // mAvailableOutputDevices.
6605 if (availProfileDevices.isEmpty()) {
6606 continue;
6607 }
6608 supportedDevice = availProfileDevices.itemAt(0);
6609 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006610 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006611 continue;
6612 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306613
6614 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6615 && availProfileDevices.areAllDevicesAttached()) {
6616 ALOGV("%s skip opening output for mmap profile %s", __func__,
6617 outProfile->getTagName().c_str());
6618 continue;
6619 }
6620
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006621 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6622 mpClientInterface);
6623 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006624 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006625 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6626 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006627 AUDIO_STREAM_DEFAULT,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07006628 AUDIO_OUTPUT_FLAG_NONE, &output, attributes);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006629 if (status != NO_ERROR) {
6630 ALOGW("Cannot open output stream for devices %s on hw module %s",
6631 supportedDevice->toString().c_str(), hwModule->getName());
6632 continue;
6633 }
6634 for (const auto &device : availProfileDevices) {
6635 // give a valid ID to an attached device once confirmed it is reachable
6636 if (!device->isAttached()) {
6637 device->attach(hwModule);
6638 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006639 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006640 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006641 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6642 }
6643 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006644 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006645 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6646 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006647 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006648 }
Eric Laurent39095982021-08-24 18:29:27 +02006649 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006650 outputDesc->close();
6651 } else {
6652 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306653 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006654 DeviceVector(supportedDevice),
6655 true,
6656 0,
6657 NULL);
6658 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006659 }
6660 // open input streams needed to access attached devices to validate
6661 // mAvailableInputDevices list
6662 for (const auto& inProfile : hwModule->getInputProfiles()) {
6663 if (!inProfile->canOpenNewIo()) {
6664 ALOGE("Invalid Input profile max open count %u for profile %s",
6665 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6666 continue;
6667 }
6668 if (!inProfile->hasSupportedDevices()) {
6669 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6670 continue;
6671 }
6672 // chose first device present in profile's SupportedDevices also part of
6673 // available input devices
6674 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006675 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006676 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006677 ALOGV("%s: Input device list is empty! for profile %s",
6678 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006679 continue;
6680 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306681
6682 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6683 && availProfileDevices.areAllDevicesAttached()) {
6684 ALOGV("%s skip opening input for mmap profile %s", __func__,
6685 inProfile->getTagName().c_str());
6686 continue;
6687 }
6688
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006689 sp<AudioInputDescriptor> inputDesc =
6690 new AudioInputDescriptor(inProfile, mpClientInterface);
6691
6692 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6693 status_t status = inputDesc->open(nullptr,
6694 availProfileDevices.itemAt(0),
6695 AUDIO_SOURCE_MIC,
Mikhail Naganov08816472024-07-18 16:01:54 +00006696 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006697 &input);
6698 if (status != NO_ERROR) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306699 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6700 __func__, availProfileDevices.toString().c_str(),
6701 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006702 continue;
6703 }
6704 for (const auto &device : availProfileDevices) {
6705 // give a valid ID to an attached device once confirmed it is reachable
6706 if (!device->isAttached()) {
6707 device->attach(hwModule);
6708 device->importAudioPortAndPickAudioProfile(inProfile, true);
6709 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006710 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006711 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6712 }
6713 }
6714 inputDesc->close();
6715 }
6716 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006717
6718 // Check if spatializer outputs can be closed until used.
6719 // mOutputs vector never contains duplicated outputs at this point.
6720 std::vector<audio_io_handle_t> outputsClosed;
6721 for (size_t i = 0; i < mOutputs.size(); i++) {
6722 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6723 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6724 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6725 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006726 nextAudioPortGeneration();
6727 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6728 if (index >= 0) {
6729 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6730 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6731 patchDesc->getAfHandle(), 0);
6732 mAudioPatches.removeItemsAt(index);
6733 mpClientInterface->onAudioPatchListUpdate();
6734 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006735 desc->close();
6736 }
6737 }
6738 for (auto output : outputsClosed) {
6739 removeOutput(output);
6740 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006741}
6742
Eric Laurent98e38192018-02-15 18:31:53 -08006743void AudioPolicyManager::addOutput(audio_io_handle_t output,
6744 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006745{
Eric Laurent1c333e22014-05-20 10:48:17 -07006746 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006747 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006748 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006749 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006750 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006751}
6752
François Gaffie53615e22015-03-19 09:24:12 +01006753void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6754{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006755 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6756 ALOGV("%s: removing primary output", __func__);
6757 mPrimaryOutput = nullptr;
6758 }
François Gaffie53615e22015-03-19 09:24:12 +01006759 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006760 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006761}
6762
Eric Laurent98e38192018-02-15 18:31:53 -08006763void AudioPolicyManager::addInput(audio_io_handle_t input,
6764 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006765{
Eric Laurent1c333e22014-05-20 10:48:17 -07006766 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006767 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006768}
Eric Laurente552edb2014-03-10 17:42:56 -07006769
François Gaffie11d30102018-11-02 16:09:09 +01006770status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006771 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006772 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006773{
François Gaffie11d30102018-11-02 16:09:09 +01006774 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006775 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006776 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006777
François Gaffie11d30102018-11-02 16:09:09 +01006778 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006779 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006780 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006781 }
Eric Laurente552edb2014-03-10 17:42:56 -07006782
Eric Laurent3b73df72014-03-11 09:06:29 -07006783 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006784 // first call getAudioPort to get the supported attributes from the HAL
6785 struct audio_port_v7 port = {};
6786 device->toAudioPort(&port);
6787 status_t status = mpClientInterface->getAudioPort(&port);
6788 if (status == NO_ERROR) {
6789 device->importAudioPort(port);
6790 }
6791
6792 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006793 for (size_t i = 0; i < mOutputs.size(); i++) {
6794 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006795 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006796 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006797 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6798 mOutputs.keyAt(i), device->toString().c_str());
6799 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006800 }
6801 }
6802 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006803 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006804 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006805 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6806 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006807 if (profile->supportsDevice(device)) {
6808 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306809 ALOGV("%s(): adding profile %s from module %s",
6810 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006811 }
6812 }
6813 }
6814
Eric Laurent7b279bb2015-12-14 10:18:23 -08006815 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006816
Eric Laurente552edb2014-03-10 17:42:56 -07006817 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006818 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006819 return BAD_VALUE;
6820 }
6821
6822 // open outputs for matching profiles if needed. Direct outputs are also opened to
6823 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6824 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006825 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006826
6827 // nothing to do if one output is already opened for this profile
6828 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006829 for (j = 0; j < outputs.size(); j++) {
6830 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006831 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006832 // matching profile: save the sample rates, format and channel masks supported
6833 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006834 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006835 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006836 }
Eric Laurente552edb2014-03-10 17:42:56 -07006837 break;
6838 }
6839 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006840 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006841 continue;
6842 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306843 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6844 ALOGV("%s skip opening output for mmap profile %s",
6845 __func__, profile->getTagName().c_str());
6846 continue;
6847 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006848 if (!profile->canOpenNewIo()) {
6849 ALOGW("Max Output number %u already opened for this profile %s",
6850 profile->maxOpenCount, profile->getTagName().c_str());
6851 continue;
6852 }
6853
Eric Laurent83efe1c2017-07-09 16:51:08 -07006854 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006855 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006856 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6857 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006858 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006859 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006860 profiles.removeAt(profile_index);
6861 profile_index--;
6862 } else {
6863 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006864 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006865 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006866 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6867 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006868 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006869 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006870
François Gaffie11d30102018-11-02 16:09:09 +01006871 if (device_distinguishes_on_address(deviceType)) {
6872 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6873 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306874 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6875 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006876 }
Eric Laurente552edb2014-03-10 17:42:56 -07006877 ALOGV("checkOutputsForDevice(): adding output %d", output);
6878 }
6879 }
6880
6881 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006882 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006883 return BAD_VALUE;
6884 }
Eric Laurentd4692962014-05-05 18:13:44 -07006885 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006886 // check if one opened output is not needed any more after disconnecting one device
6887 for (size_t i = 0; i < mOutputs.size(); i++) {
6888 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006889 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006890 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006891 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006892 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006893 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006894 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006895 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6896 mOutputs.keyAt(i));
6897 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006898 }
Eric Laurente552edb2014-03-10 17:42:56 -07006899 }
6900 }
Eric Laurentd4692962014-05-05 18:13:44 -07006901 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006902 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006903 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6904 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006905 if (!profile->supportsDevice(device)) {
6906 continue;
6907 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306908 ALOGV("%s(): clearing direct output profile %s on module %s",
6909 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07006910 profile->clearAudioProfiles();
6911 if (!profile->hasDynamicAudioProfile()) {
6912 continue;
6913 }
6914 // When a device is disconnected, if there is an IOProfile that contains dynamic
6915 // profiles and supports the disconnected device, call getAudioPort to repopulate
6916 // the capabilities of the devices that is supported by the IOProfile.
6917 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6918 if (supportedDevice == device ||
6919 !mAvailableOutputDevices.contains(supportedDevice)) {
6920 continue;
6921 }
6922 struct audio_port_v7 port;
6923 supportedDevice->toAudioPort(&port);
6924 status_t status = mpClientInterface->getAudioPort(&port);
6925 if (status == NO_ERROR) {
6926 supportedDevice->importAudioPort(port);
6927 }
Eric Laurente552edb2014-03-10 17:42:56 -07006928 }
6929 }
6930 }
6931 }
6932 return NO_ERROR;
6933}
6934
François Gaffie11d30102018-11-02 16:09:09 +01006935status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006936 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006937{
François Gaffie11d30102018-11-02 16:09:09 +01006938 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006939 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006940 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006941 }
6942
Eric Laurentd4692962014-05-05 18:13:44 -07006943 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006944 sp<AudioInputDescriptor> desc;
6945
jiabinbf5f4262023-04-12 21:48:34 +00006946 // first call getAudioPort to get the supported attributes from the HAL
6947 struct audio_port_v7 port = {};
6948 device->toAudioPort(&port);
6949 status_t status = mpClientInterface->getAudioPort(&port);
6950 if (status == NO_ERROR) {
6951 device->importAudioPort(port);
6952 }
6953
Eric Laurent0dd51852019-04-19 18:18:58 -07006954 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006955 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006956 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006957 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006958 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006959 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006960 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006961
François Gaffie11d30102018-11-02 16:09:09 +01006962 if (profile->supportsDevice(device)) {
6963 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306964 ALOGV("%s : adding profile %s from module %s", __func__,
6965 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006966 }
6967 }
6968 }
6969
Eric Laurent0dd51852019-04-19 18:18:58 -07006970 if (profiles.isEmpty()) {
6971 ALOGW("%s: No input profile available for device %s",
6972 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006973 return BAD_VALUE;
6974 }
6975
6976 // open inputs for matching profiles if needed. Direct inputs are also opened to
6977 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6978 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6979
Eric Laurent1c333e22014-05-20 10:48:17 -07006980 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006981
Eric Laurentd4692962014-05-05 18:13:44 -07006982 // nothing to do if one input is already opened for this profile
6983 size_t input_index;
6984 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6985 desc = mInputs.valueAt(input_index);
6986 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006987 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006988 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006989 }
Eric Laurentd4692962014-05-05 18:13:44 -07006990 break;
6991 }
6992 }
6993 if (input_index != mInputs.size()) {
6994 continue;
6995 }
6996
Jaideep Sharma44824a22024-06-18 16:32:34 +05306997 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6998 ALOGV("%s skip opening input for mmap profile %s",
6999 __func__, profile->getTagName().c_str());
7000 continue;
7001 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08007002 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307003 ALOGW("%s Max Input number %u already opened for this profile %s",
7004 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08007005 continue;
7006 }
7007
Eric Laurentfe231122017-11-17 17:48:06 -08007008 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007009 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307010 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Mikhail Naganov08816472024-07-18 16:01:54 +00007011 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
7012 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07007013
Eric Laurentcf2c0212014-07-25 16:20:43 -07007014 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07007015 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00007016 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007017 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07007018 mpClientInterface->setParameters(input, String8(param));
7019 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07007020 }
jiabin12537fc2023-10-12 17:56:08 +00007021 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01007022 if (!profile->hasValidAudioProfile()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307023 ALOGW("%s direct input missing param for profile %s", __func__,
7024 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08007025 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07007026 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07007027 }
7028
Eric Laurent0dd51852019-04-19 18:18:58 -07007029 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07007030 addInput(input, desc);
7031 }
7032 } // endif input != 0
7033
Eric Laurentcf2c0212014-07-25 16:20:43 -07007034 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307035 ALOGW("%s could not open input for device %s on profile %s", __func__,
7036 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007037 profiles.removeAt(profile_index);
7038 profile_index--;
7039 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007040 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07007041 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07007042 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307043 ALOGV("%s: adding input %d for profile %s", __func__,
7044 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007045
7046 if (checkCloseInput(desc)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307047 ALOGV("%s: closing input %d for profile %s", __func__,
7048 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07007049 closeInput(input);
7050 }
Eric Laurentd4692962014-05-05 18:13:44 -07007051 }
7052 } // end scan profiles
7053
7054 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01007055 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07007056 return BAD_VALUE;
7057 }
7058 } else {
7059 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07007060 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08007061 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07007062 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007063 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07007064 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08007065 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01007066 if (profile->supportsDevice(device)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05307067 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
7068 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01007069 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07007070 }
7071 }
7072 }
7073 } // end disconnect
7074
7075 return NO_ERROR;
7076}
7077
7078
Eric Laurente0720872014-03-11 09:30:41 -07007079void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07007080{
7081 ALOGV("closeOutput(%d)", output);
7082
François Gaffie1c878552018-11-22 16:53:21 +01007083 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
7084 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07007085 ALOGW("closeOutput() unknown output %d", output);
7086 return;
7087 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007088 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00007089 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08007090
Eric Laurente552edb2014-03-10 17:42:56 -07007091 // look for duplicated outputs connected to the output being removed.
7092 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01007093 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
7094 if (dupOutput->isDuplicated() &&
7095 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
7096 sp<SwAudioOutputDescriptor> remainingOutput =
7097 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07007098 // As all active tracks on duplicated output will be deleted,
7099 // and as they were also referenced on the other output, the reference
7100 // count for their stream type must be adjusted accordingly on
7101 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01007102 const bool wasActive = remainingOutput->isActive();
7103 // Note: no-op on the closing output where all clients has already been set inactive
7104 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08007105 // stop() will be a no op if the output is still active but is needed in case all
7106 // active streams refcounts where cleared above
7107 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01007108 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08007109 }
Eric Laurente552edb2014-03-10 17:42:56 -07007110 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
7111 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
7112
7113 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01007114 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07007115 }
7116 }
7117
Eric Laurent05b90f82014-08-27 15:32:29 -07007118 nextAudioPortGeneration();
7119
François Gaffie1c878552018-11-22 16:53:21 +01007120 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007121 if (index >= 0) {
7122 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007123 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7124 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007125 mAudioPatches.removeItemsAt(index);
7126 mpClientInterface->onAudioPatchListUpdate();
7127 }
7128
Mikhail Naganov32ebca32019-03-22 15:42:52 -07007129 if (closingOutputWasActive) {
7130 closingOutput->stop();
7131 }
François Gaffie1c878552018-11-22 16:53:21 +01007132 closingOutput->close();
jiabin220eea12024-05-17 17:55:20 +00007133 if (closingOutput->isBitPerfect()) {
jiabin14b50cc2023-12-13 19:01:52 +00007134 for (const auto device : closingOutput->devices()) {
7135 device->setPreferredConfig(nullptr);
7136 }
7137 }
Eric Laurente552edb2014-03-10 17:42:56 -07007138
François Gaffie53615e22015-03-19 09:24:12 +01007139 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07007140 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01007141 if (closingOutput == mSpatializerOutput) {
7142 mSpatializerOutput.clear();
7143 }
Dean Wheatley3023b382018-08-09 07:42:40 +10007144
7145 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
7146 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01007147 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10007148 bool directOutputOpen = false;
7149 for (size_t i = 0; i < mOutputs.size(); i++) {
7150 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
7151 directOutputOpen = true;
7152 break;
7153 }
7154 }
7155 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11007156 ALOGV("no direct outputs open, reset MSD patches");
7157 // TODO: The MSD patches to be established here may differ to current MSD patches due to
7158 // how output devices for patching are resolved. Avoid by caching and reusing the
7159 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
7160 // devices to patch to. This may be complicated by the fact that devices may become
7161 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007162 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007163 }
7164 }
jiabin220eea12024-05-17 17:55:20 +00007165
7166 if (closingOutput->mPreferredAttrInfo != nullptr) {
7167 closingOutput->mPreferredAttrInfo->resetActiveClient();
7168 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007169}
7170
7171void AudioPolicyManager::closeInput(audio_io_handle_t input)
7172{
7173 ALOGV("closeInput(%d)", input);
7174
7175 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7176 if (inputDesc == NULL) {
7177 ALOGW("closeInput() unknown input %d", input);
7178 return;
7179 }
7180
Eric Laurent6a94d692014-05-20 11:18:06 -07007181 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007182
François Gaffie11d30102018-11-02 16:09:09 +01007183 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007184 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007185 if (index >= 0) {
7186 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007187 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7188 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007189 mAudioPatches.removeItemsAt(index);
7190 mpClientInterface->onAudioPatchListUpdate();
7191 }
7192
François Gaffie6ebbce02023-07-19 13:27:53 +02007193 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007194 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007195 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007196
François Gaffie11d30102018-11-02 16:09:09 +01007197 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7198 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007199 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007200 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007201 }
Eric Laurente552edb2014-03-10 17:42:56 -07007202}
7203
François Gaffie11d30102018-11-02 16:09:09 +01007204SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7205 const DeviceVector &devices,
7206 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007207{
7208 SortedVector<audio_io_handle_t> outputs;
7209
François Gaffie11d30102018-11-02 16:09:09 +01007210 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007211 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007212 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007213 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007214 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007215 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007216 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007217 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007218 outputs.add(openOutputs.keyAt(i));
7219 }
7220 }
7221 return outputs;
7222}
7223
Mikhail Naganov37977152018-07-11 15:54:44 -07007224void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7225{
7226 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7227 // output is suspended before any tracks are moved to it
7228 checkA2dpSuspend();
7229 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007230 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007231 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007232 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007233 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007234 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7235 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7236 // configuration changes will ultimately be rerouted correctly. We can still avoid
7237 // unnecessary rerouting by caching and reusing the arguments to
7238 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7239 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007240 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007241 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007242 // an event that changed routing likely occurred, inform upper layers
7243 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007244}
7245
François Gaffiec005e562018-11-06 15:04:49 +01007246bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7247 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007248{
François Gaffiec005e562018-11-06 15:04:49 +01007249 return mEngine->getProductStrategyForAttributes(lAttr) ==
7250 mEngine->getProductStrategyForAttributes(rAttr);
7251}
7252
Francois Gaffieff1eb522020-05-06 18:37:04 +02007253void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7254{
7255 for (size_t i = 0; i < mAudioSources.size(); i++) {
7256 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7257 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007258 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Eric Laurent963dbcc2024-06-20 12:34:15 +00007259 && !sourceDesc->isCallRx() && !sourceDesc->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007260 connectAudioSource(sourceDesc, 0 /*delayMs*/);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007261 }
7262 }
7263}
7264
7265void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7266{
7267 for (size_t i = 0; i < mAudioSources.size(); i++) {
7268 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7269 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7270 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7271 disconnectAudioSource(sourceDesc);
7272 }
7273 }
7274}
7275
François Gaffiec005e562018-11-06 15:04:49 +01007276void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7277{
7278 auto psId = mEngine->getProductStrategyForAttributes(attr);
7279
7280 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7281 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007282
François Gaffie11d30102018-11-02 16:09:09 +01007283 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7284 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007285
Eric Laurentc209fe42020-06-05 18:11:23 -07007286 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007287 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007288 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007289 // take into account dynamic audio policies related changes: if a client is now associated
7290 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent3ec55562024-08-22 15:08:57 +00007291 // invalidate clients on outputs that do not support all the newly selected devices for the
7292 // strategy
Eric Laurent56ed8842022-11-15 16:04:41 +01007293 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007294 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
Eric Laurent3ec55562024-08-22 15:08:57 +00007295 if (desc->isDuplicated() || desc->getClientCount() == 0) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007296 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007297 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007298
Eric Laurentc209fe42020-06-05 18:11:23 -07007299 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7300 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7301 continue;
7302 }
Eric Laurent3ec55562024-08-22 15:08:57 +00007303 if (!desc->supportsAllDevices(newDevices)) {
7304 invalidatedOutputs.push_back(desc);
7305 break;
7306 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007307 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007308 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007309 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7310 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7311 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurent3ec55562024-08-22 15:08:57 +00007312 if (status == OK) {
7313 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
7314 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
7315 maxLatency = desc->latency();
7316 }
7317 invalidatedOutputs.push_back(desc);
7318 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07007319 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007320 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007321 }
7322 }
7323
Eric Laurent56ed8842022-11-15 16:04:41 +01007324 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007325 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7326 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007327 for (audio_io_handle_t srcOut : srcOutputs) {
7328 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007329 if (desc == nullptr) continue;
7330
7331 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007332 maxLatency = desc->latency();
7333 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007334
Eric Laurent56ed8842022-11-15 16:04:41 +01007335 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007336 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007337 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007338 // a client on a non direct outputs has necessarily a linear PCM format
7339 // so we can call selectOutput() safely
7340 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7341 client->flags(),
7342 client->config().format,
7343 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007344 client->config().sample_rate,
7345 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007346 if (newOutput != srcOut) {
7347 invalidate = true;
7348 break;
7349 }
7350 } else {
7351 sp<IOProfile> profile = getProfileForOutput(newDevices,
7352 client->config().sample_rate,
7353 client->config().format,
7354 client->config().channel_mask,
7355 client->flags(),
7356 true /* directOnly */);
7357 if (profile != desc->mProfile) {
7358 invalidate = true;
7359 break;
7360 }
7361 }
7362 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007363 // mute strategy while moving tracks from one output to another
7364 if (invalidate) {
7365 invalidatedOutputs.push_back(desc);
7366 if (desc->isStrategyActive(psId)) {
7367 setStrategyMute(psId, true, desc);
7368 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7369 newDevices.types());
7370 }
Eric Laurente552edb2014-03-10 17:42:56 -07007371 }
François Gaffiec005e562018-11-06 15:04:49 +01007372 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Eric Laurent963dbcc2024-06-20 12:34:15 +00007373 if (source != nullptr && !source->isCallRx() && !source->isInternal()) {
David Li48b6a832024-07-01 13:14:10 +00007374 connectAudioSource(source, 0 /*delayMs*/);
Eric Laurentd60560a2015-04-10 11:31:20 -07007375 }
Eric Laurente552edb2014-03-10 17:42:56 -07007376 }
7377
Eric Laurent56ed8842022-11-15 16:04:41 +01007378 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7379 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7380 std::to_string(srcOutputs[0]).c_str(),
7381 std::to_string(dstOutputs[0]).c_str());
7382
François Gaffiec005e562018-11-06 15:04:49 +01007383 // Move effects associated to this stream from previous output to new output
7384 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007385 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007386 }
François Gaffiec005e562018-11-06 15:04:49 +01007387 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007388 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007389 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007390 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007391 desc->setTracksInvalidatedStatusByStrategy(psId);
7392 }
Eric Laurente552edb2014-03-10 17:42:56 -07007393 }
7394 }
7395}
7396
Eric Laurente0720872014-03-11 09:30:41 -07007397void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007398{
François Gaffiec005e562018-11-06 15:04:49 +01007399 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7400 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7401 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007402 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007403 }
Eric Laurente552edb2014-03-10 17:42:56 -07007404}
7405
Kevin Rocard153f92d2018-12-18 18:33:28 -08007406void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007407 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007408 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007409 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007410 for (size_t i = 0; i < mOutputs.size(); i++) {
7411 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7412 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007413 sp<AudioPolicyMix> primaryMix;
7414 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007415 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007416 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7417 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7418 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007419 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7420 for (auto &secondaryMix : secondaryMixes) {
7421 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7422 if (outputDesc != nullptr &&
7423 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7424 secondaryDescs.push_back(outputDesc);
7425 }
7426 }
7427
jiabinc44b3462022-12-08 12:52:31 -08007428 if (status != OK &&
7429 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7430 // When it failed to query secondary output, only invalidate the client that is not
7431 // MMAP. The reason is that MMAP stream will not support secondary output.
7432 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007433 } else if (!std::equal(
7434 client->getSecondaryOutputs().begin(),
7435 client->getSecondaryOutputs().end(),
7436 secondaryDescs.begin(), secondaryDescs.end())) {
Andy Hungced57302024-08-14 11:37:57 -07007437 if (client->flags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD
7438 || !audio_is_linear_pcm(client->config().format)) {
jiabina5281062021-11-23 00:10:23 +00007439 // If the format is not PCM, the tracks should be invalidated to get correct
7440 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007441 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007442 } else {
7443 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7444 std::vector<audio_io_handle_t> secondaryOutputIds;
7445 for (const auto &secondaryDesc: secondaryDescs) {
7446 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7447 weakSecondaryDescs.push_back(secondaryDesc);
7448 }
7449 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7450 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007451 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007452 }
7453 }
7454 }
jiabin10a03f12021-05-07 23:46:28 +00007455 if (!trackSecondaryOutputs.empty()) {
7456 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7457 }
jiabinc44b3462022-12-08 12:52:31 -08007458 if (!clientsToInvalidate.empty()) {
7459 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7460 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007461 }
7462}
7463
Eric Laurent2517af32020-11-25 15:31:27 +01007464bool AudioPolicyManager::isScoRequestedForComm() const {
7465 AudioDeviceTypeAddrVector devices;
7466 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7467 for (const auto &device : devices) {
7468 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7469 return true;
7470 }
7471 }
7472 return false;
7473}
7474
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007475bool AudioPolicyManager::isHearingAidUsedForComm() const {
7476 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7477 true /*fromCache*/);
7478 for (const auto &device : devices) {
7479 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7480 return true;
7481 }
7482 }
7483 return false;
7484}
7485
7486
Eric Laurente0720872014-03-11 09:30:41 -07007487void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007488{
François Gaffie53615e22015-03-19 09:24:12 +01007489 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007490 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007491 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007492 return;
7493 }
7494
Eric Laurent3a4311c2014-03-17 12:00:47 -07007495 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007496 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7497 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007498 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007499
7500 // if suspended, restore A2DP output if:
7501 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007502 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007503 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007504 //
Eric Laurentf732e072016-08-03 19:30:28 -07007505 // if not suspended, suspend A2DP output if:
7506 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007507 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007508 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007509 //
7510 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007511 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007512 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007513 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007514 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007515
7516 mpClientInterface->restoreOutput(a2dpOutput);
7517 mA2dpSuspended = false;
7518 }
7519 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007520 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007521 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007522 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007523 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007524
7525 mpClientInterface->suspendOutput(a2dpOutput);
7526 mA2dpSuspended = true;
7527 }
7528 }
7529}
7530
François Gaffie11d30102018-11-02 16:09:09 +01007531DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7532 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007533{
François Gaffiedb1755b2023-09-01 11:50:35 +02007534 if (outputDesc == nullptr) {
7535 return DeviceVector{};
7536 }
François Gaffie11d30102018-11-02 16:09:09 +01007537
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007538 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007539 if (index >= 0) {
7540 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007541 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007542 ALOGV("%s device %s forced by patch %d", __func__,
7543 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7544 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007545 }
7546 }
7547
Dean Wheatley514b4312020-06-17 21:45:00 +10007548 // Do not retrieve engine device for outputs through MSD
7549 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7550 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7551 return outputDesc->devices();
7552 }
7553
Eric Laurent97ac8712018-07-27 18:59:02 -07007554 // Honor explicit routing requests only if no client using default routing is active on this
7555 // input: a specific app can not force routing for other apps by setting a preferred device.
7556 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007557 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007558 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007559 if (device != nullptr) {
7560 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007561 }
7562
François Gaffiea807ef92018-11-05 10:44:33 +01007563 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7564 // of setForceUse / Default Bus device here
7565 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7566 if (device != nullptr) {
7567 return DeviceVector(device);
7568 }
7569
François Gaffiedb1755b2023-09-01 11:50:35 +02007570 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007571 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7572 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307573 auto hasStreamActive = [&](auto stream) {
7574 return hasStream(streams, stream) && isStreamActive(stream, 0);
7575 };
Eric Laurent484e9272018-06-07 17:29:23 -07007576
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307577 auto doGetOutputDevicesForVoice = [&]() {
7578 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007579 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307580 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007581 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7582 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307583 };
7584
7585 // With low-latency playing on speaker, music on WFD, when the first low-latency
7586 // output is stopped, getNewOutputDevices checks for a product strategy
7587 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007588 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307589 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7590 // stream is associated to the output descriptor.
7591 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7592 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7593 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7594 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007595 // Retrieval of devices for voice DL is done on primary output profile, cannot
7596 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007597 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007598 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7599 break;
7600 }
Eric Laurente552edb2014-03-10 17:42:56 -07007601 }
François Gaffiec005e562018-11-06 15:04:49 +01007602 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007603 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007604}
7605
François Gaffie11d30102018-11-02 16:09:09 +01007606sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7607 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007608{
François Gaffie11d30102018-11-02 16:09:09 +01007609 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007610
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007611 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007612 if (index >= 0) {
7613 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007614 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007615 ALOGV("getNewInputDevice() device %s forced by patch %d",
7616 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7617 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007618 }
7619 }
7620
Eric Laurent97ac8712018-07-27 18:59:02 -07007621 // Honor explicit routing requests only if no client using default routing is active on this
7622 // input: a specific app can not force routing for other apps by setting a preferred device.
7623 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007624 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7625 if (device != nullptr) {
7626 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007627 }
7628
Eric Laurentdc95a252018-04-12 12:46:56 -07007629 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007630 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007631 audio_attributes_t attributes;
7632 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007633 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007634 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7635 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007636 attributes = topClient->attributes();
7637 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007638 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007639 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007640 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7641 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007642 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007643 }
7644
Francois Gaffie716e1432019-01-14 16:58:59 +01007645 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7646 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007647 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007648 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007649 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007650 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007651
Eric Laurente552edb2014-03-10 17:42:56 -07007652 return device;
7653}
7654
Eric Laurent794fde22016-03-11 09:50:45 -08007655bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7656 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007657 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007658}
7659
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007660status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007661 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007662 if (devices == nullptr) {
7663 return BAD_VALUE;
7664 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007665
Andy Hung6d23c0f2022-02-16 09:37:15 -08007666 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007667 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7668 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007669 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007670 for (const auto& device : curDevices) {
7671 devices->push_back(device->getDeviceTypeAddr());
7672 }
7673 return NO_ERROR;
7674}
7675
Eric Laurente0720872014-03-11 09:30:41 -07007676void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007677 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007678 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007679 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007680 updateDevicesAndOutputs();
7681 break;
7682 default:
7683 break;
7684 }
7685}
7686
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007687uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007688
7689 // skip beacon mute management if a dedicated TTS output is available
7690 if (mTtsOutputAvailable) {
7691 return 0;
7692 }
7693
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007694 switch(event) {
7695 case STARTING_OUTPUT:
7696 mBeaconMuteRefCount++;
7697 break;
7698 case STOPPING_OUTPUT:
7699 if (mBeaconMuteRefCount > 0) {
7700 mBeaconMuteRefCount--;
7701 }
7702 break;
7703 case STARTING_BEACON:
7704 mBeaconPlayingRefCount++;
7705 break;
7706 case STOPPING_BEACON:
7707 if (mBeaconPlayingRefCount > 0) {
7708 mBeaconPlayingRefCount--;
7709 }
7710 break;
7711 }
7712
7713 if (mBeaconMuteRefCount > 0) {
7714 // any playback causes beacon to be muted
7715 return setBeaconMute(true);
7716 } else {
7717 // no other playback: unmute when beacon starts playing, mute when it stops
7718 return setBeaconMute(mBeaconPlayingRefCount == 0);
7719 }
7720}
7721
7722uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7723 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7724 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7725 // keep track of muted state to avoid repeating mute/unmute operations
7726 if (mBeaconMuted != mute) {
7727 // mute/unmute AUDIO_STREAM_TTS on all outputs
7728 ALOGV("\t muting %d", mute);
7729 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007730 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7731 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7732 ALOGV("\t no tts volume source available");
7733 return 0;
7734 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007735 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007736 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007737 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007738 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007739 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007740 maxLatency = latency;
7741 }
7742 }
7743 mBeaconMuted = mute;
7744 return maxLatency;
7745 }
7746 return 0;
7747}
7748
Eric Laurente0720872014-03-11 09:30:41 -07007749void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007750{
François Gaffiec005e562018-11-06 15:04:49 +01007751 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007752 mPreviousOutputs = mOutputs;
7753}
7754
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007755uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007756 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007757 uint32_t delayMs)
7758{
7759 // mute/unmute strategies using an incompatible device combination
7760 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7761 // if unmuting, unmute only after the specified delay
7762 if (outputDesc->isDuplicated()) {
7763 return 0;
7764 }
7765
7766 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007767 DeviceVector devices = outputDesc->devices();
7768 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007769
François Gaffiec005e562018-11-06 15:04:49 +01007770 auto productStrategies = mEngine->getOrderedProductStrategies();
7771 for (const auto &productStrategy : productStrategies) {
7772 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7773 DeviceVector curDevices =
7774 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7775 curDevices = curDevices.filter(outputDesc->supportedDevices());
7776 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007777 bool doMute = false;
7778
François Gaffiec005e562018-11-06 15:04:49 +01007779 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007780 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007781 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7782 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007783 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007784 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007785 }
Eric Laurent99401132014-05-07 19:48:15 -07007786 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007787 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007788 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007789 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007790 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007791 continue;
7792 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307793 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007794 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7795 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7796 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007797 if (mute) {
7798 // FIXME: should not need to double latency if volume could be applied
7799 // immediately by the audioflinger mixer. We must account for the delay
7800 // between now and the next time the audioflinger thread for this output
7801 // will process a buffer (which corresponds to one buffer size,
7802 // usually 1/2 or 1/4 of the latency).
7803 if (muteWaitMs < desc->latency() * 2) {
7804 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007805 }
7806 }
7807 }
7808 }
7809 }
7810 }
7811
Eric Laurent99401132014-05-07 19:48:15 -07007812 // temporary mute output if device selection changes to avoid volume bursts due to
7813 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007814 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007815 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007816
Eric Laurentdc462862016-07-19 12:29:53 -07007817 if (muteWaitMs < tempMuteWaitMs) {
7818 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007819 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007820
7821 // If recommended duration is defined, replace temporary mute duration to avoid
7822 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7823 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7824 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7825 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7826 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7827
François Gaffieaaac0fd2018-11-22 17:56:39 +01007828 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7829 // make sure that we do not start the temporary mute period too early in case of
7830 // delayed device change
7831 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7832 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007833 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007834 }
7835 }
7836
Eric Laurente552edb2014-03-10 17:42:56 -07007837 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7838 if (muteWaitMs > delayMs) {
7839 muteWaitMs -= delayMs;
7840 usleep(muteWaitMs * 1000);
7841 return muteWaitMs;
7842 }
7843 return 0;
7844}
7845
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307846uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7847 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007848 const DeviceVector &devices,
7849 bool force,
7850 int delayMs,
7851 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007852 bool requiresMuteCheck, bool requiresVolumeCheck,
7853 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007854{
jiabin3ff8d7d2022-12-13 06:27:44 +00007855 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307856 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7857 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7858 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007859 uint32_t muteWaitMs;
7860
7861 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307862 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007863 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307864 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007865 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007866 return muteWaitMs;
7867 }
Eric Laurente552edb2014-03-10 17:42:56 -07007868
7869 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007870 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007871 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007872 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007873
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307874 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7875 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007876
7877 if (!filteredDevices.isEmpty()) {
7878 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007879 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007880
7881 // if the outputs are not materially active, there is no need to mute.
7882 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007883 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007884 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307885 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7886 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007887 muteWaitMs = 0;
7888 }
Eric Laurente552edb2014-03-10 17:42:56 -07007889
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007890 bool outputRouted = outputDesc->isRouted();
7891
Eric Laurent79ea9582020-06-11 18:49:24 -07007892 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7893 // output profile or if new device is not supported AND previous device(s) is(are) still
7894 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007895 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307896 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7897 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007898 // restore previous device after evaluating strategy mute state
7899 outputDesc->setDevices(prevDevices);
7900 return muteWaitMs;
7901 }
7902
Eric Laurente552edb2014-03-10 17:42:56 -07007903 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007904 // the requested device is AUDIO_DEVICE_NONE
7905 // OR the requested device is the same as current device
7906 // AND force is not specified
7907 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007908 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007909 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307910 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7911 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7912 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007913 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307914 ALOGV("%s %s setting same device on routed output, force apply volumes",
7915 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007916 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7917 }
Eric Laurente552edb2014-03-10 17:42:56 -07007918 return muteWaitMs;
7919 }
7920
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307921 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7922 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007923
Eric Laurente552edb2014-03-10 17:42:56 -07007924 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007925 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007926 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007927 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007928 PatchBuilder patchBuilder;
7929 patchBuilder.addSource(outputDesc);
7930 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7931 for (const auto &filteredDevice : filteredDevices) {
7932 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007933 }
7934
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007935 // Add half reported latency to delayMs when muteWaitMs is null in order
7936 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007937 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7938 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7939 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007940 }
Eric Laurente552edb2014-03-10 17:42:56 -07007941
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007942 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7943 if (!skipMuteDelay) {
7944 // update stream volumes according to new device
7945 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7946 }
Eric Laurente552edb2014-03-10 17:42:56 -07007947
7948 return muteWaitMs;
7949}
7950
Eric Laurentc75307b2015-03-17 15:29:32 -07007951status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007952 int delayMs,
7953 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007954{
Eric Laurent6a94d692014-05-20 11:18:06 -07007955 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007956 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7957 return INVALID_OPERATION;
7958 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007959 if (patchHandle) {
7960 index = mAudioPatches.indexOfKey(*patchHandle);
7961 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007962 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007963 }
7964 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007965 return INVALID_OPERATION;
7966 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007967 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007968 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007969 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007970 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007971 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007972 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007973 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007974 return status;
7975}
7976
7977status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007978 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007979 bool force,
7980 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007981{
7982 status_t status = NO_ERROR;
7983
Eric Laurent1f2f2232014-06-02 12:01:23 -07007984 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007985 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7986 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007987
François Gaffie11d30102018-11-02 16:09:09 +01007988 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007989 PatchBuilder patchBuilder;
7990 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007991 // AUDIO_SOURCE_HOTWORD is for internal use only:
7992 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007993 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7994 auto result = usecase;
7995 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7996 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7997 }
7998 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007999 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01008000 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008001 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008002 }
8003 }
8004 return status;
8005}
8006
Eric Laurent6a94d692014-05-20 11:18:06 -07008007status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
8008 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07008009{
Eric Laurent1f2f2232014-06-02 12:01:23 -07008010 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07008011 ssize_t index;
8012 if (patchHandle) {
8013 index = mAudioPatches.indexOfKey(*patchHandle);
8014 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08008015 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008016 }
8017 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07008018 return INVALID_OPERATION;
8019 }
Eric Laurent6a94d692014-05-20 11:18:06 -07008020 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008021 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07008022 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07008023 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01008024 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07008025 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07008026 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07008027 return status;
8028}
8029
François Gaffie11d30102018-11-02 16:09:09 +01008030sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01008031 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07008032 audio_format_t& format,
8033 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01008034 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07008035{
8036 // Choose an input profile based on the requested capture parameters: select the first available
8037 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00008038 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07008039
Atneya Nair0f0a8032022-12-12 16:20:12 -08008040 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
8041 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
8042 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
8043
8044 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07008045
jiabin2fd710d2022-05-02 23:20:22 +00008046 for (;;) {
8047 sp<IOProfile> firstInexact = nullptr;
8048 uint32_t updatedSamplingRate = 0;
8049 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
8050 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
8051 for (const auto& hwModule : mHwModules) {
8052 for (const auto& profile : hwModule->getInputProfiles()) {
8053 // profile->log();
8054 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00008055 if (profile->getCompatibilityScore(
8056 DeviceVector(device),
8057 samplingRate,
8058 &updatedSamplingRate,
8059 format,
8060 &updatedFormat,
8061 channelMask,
8062 &updatedChannelMask,
8063 // FIXME ugly cast
8064 (audio_output_flags_t) flags,
8065 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
8066 samplingRate = updatedSamplingRate;
8067 format = updatedFormat;
8068 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00008069 return profile;
8070 }
jiabin66acc432024-02-06 00:57:36 +00008071 if (firstInexact == nullptr
8072 && profile->getCompatibilityScore(
8073 DeviceVector(device),
8074 samplingRate,
8075 &updatedSamplingRate,
8076 format,
8077 &updatedFormat,
8078 channelMask,
8079 &updatedChannelMask,
8080 // FIXME ugly cast
8081 (audio_output_flags_t) flags,
8082 false /*exactMatchRequiredForInputFlags*/)
8083 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00008084 firstInexact = profile;
8085 }
8086 }
8087 }
8088
8089 if (firstInexact != nullptr) {
8090 samplingRate = updatedSamplingRate;
8091 format = updatedFormat;
8092 channelMask = updatedChannelMask;
8093 return firstInexact;
8094 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
8095 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
8096 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
8097 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
8098 flags = AUDIO_INPUT_FLAG_NONE;
8099 } else { // fail
8100 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
8101 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
8102 samplingRate, format, channelMask, oriFlags);
8103 break;
Eric Laurente552edb2014-03-10 17:42:56 -07008104 }
8105 }
jiabin2fd710d2022-05-02 23:20:22 +00008106
8107 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07008108}
8109
Vlad Popa87e0e582024-05-20 18:49:20 -07008110float AudioPolicyManager::adjustDeviceAttenuationForAbsVolume(IVolumeCurves &curves,
8111 VolumeSource volumeSource,
8112 int index,
8113 const DeviceTypeSet &deviceTypes)
8114{
8115 audio_devices_t volumeDevice = Volume::getDeviceForVolume(deviceTypes);
8116 device_category deviceCategory = Volume::getDeviceCategory({volumeDevice});
8117 float volumeDb = curves.volIndexToDb(deviceCategory, index);
8118
8119 if (com_android_media_audio_abs_volume_index_fix()) {
8120 if (mAbsoluteVolumeDrivingStreams.find(volumeDevice) !=
8121 mAbsoluteVolumeDrivingStreams.end()) {
8122 audio_attributes_t attributesToDriveAbs = mAbsoluteVolumeDrivingStreams[volumeDevice];
8123 auto groupToDriveAbs = mEngine->getVolumeGroupForAttributes(attributesToDriveAbs);
8124 if (groupToDriveAbs == VOLUME_GROUP_NONE) {
8125 ALOGD("%s: no group matching with %s", __FUNCTION__,
8126 toString(attributesToDriveAbs).c_str());
8127 return volumeDb;
8128 }
8129
8130 float volumeDbMax = curves.volIndexToDb(deviceCategory, curves.getVolumeIndexMax());
8131 VolumeSource vsToDriveAbs = toVolumeSource(groupToDriveAbs);
8132 if (vsToDriveAbs == volumeSource) {
8133 // attenuation is applied by the abs volume controller
8134 return volumeDbMax;
8135 } else {
8136 IVolumeCurves &curvesAbs = getVolumeCurves(vsToDriveAbs);
8137 int indexAbs = curvesAbs.getVolumeIndex({volumeDevice});
8138 float volumeDbAbs = curvesAbs.volIndexToDb(deviceCategory, indexAbs);
8139 float volumeDbAbsMax = curvesAbs.volIndexToDb(deviceCategory,
8140 curvesAbs.getVolumeIndexMax());
8141 float newVolumeDb = fminf(volumeDb + volumeDbAbsMax - volumeDbAbs, volumeDbMax);
8142 ALOGV("%s: abs vol stream %d with attenuation %f is adjusting stream %d from "
8143 "attenuation %f to attenuation %f %f", __func__, vsToDriveAbs, volumeDbAbs,
8144 volumeSource, volumeDb, newVolumeDb, volumeDbMax);
8145 return newVolumeDb;
8146 }
8147 }
8148 return volumeDb;
8149 } else {
8150 return volumeDb;
8151 }
8152}
8153
François Gaffieaaac0fd2018-11-22 17:56:39 +01008154float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
8155 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01008156 int index,
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008157 const DeviceTypeSet& deviceTypes,
8158 bool computeInternalInteraction)
Eric Laurente552edb2014-03-10 17:42:56 -07008159{
Vlad Popa87e0e582024-05-20 18:49:20 -07008160 float volumeDb = adjustDeviceAttenuationForAbsVolume(curves, volumeSource, index, deviceTypes);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008161 ALOGV("%s volume source %d, index %d, devices %s, compute internal %b ", __func__,
8162 volumeSource, index, dumpDeviceTypes(deviceTypes).c_str(), computeInternalInteraction);
8163
8164 if (!computeInternalInteraction) {
8165 return volumeDb;
8166 }
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008167
8168 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
8169 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
8170 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
8171 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008172 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8173 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
8174 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
8175 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
8176 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008177 if (AUDIO_MODE_RINGTONE == mEngine->getPhoneState() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008178 mOutputs.isActive(ringVolumeSrc, 0)) {
8179 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008180 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes,
8181 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008182 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07008183 }
8184
Eric Laurentdcd4ab12018-06-29 17:45:13 -07008185 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01008186 if ((volumeSource != callVolumeSrc && (isInCall() ||
8187 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008188 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008189 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
8190 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008191 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
8192 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
8193 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008194 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008195 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07008196 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008197 const float maxVoiceVolDb =
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008198 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes,
8199 /* computeInternalInteraction= */ false)
Eric Laurent7731b5a2018-04-06 15:47:22 -07008200 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008201 // FIXME: Workaround for call screening applications until a proper audio mode is defined
8202 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
8203 // programmatically muted.
8204 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
8205 // 0. We don't want to cap volume when the system has programmatically muted the voice call
8206 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07008207 bool exemptFromCapping =
8208 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
8209 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07008210 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
8211 volumeSource, volumeDb);
8212 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008213 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
8214 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
8215 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07008216 }
8217 }
Eric Laurente552edb2014-03-10 17:42:56 -07008218 // if a headset is connected, apply the following rules to ring tones and notifications
8219 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07008220 // - always attenuate notifications volume by 6dB
8221 // - attenuate ring tones volume by 6dB unless music is not playing and
8222 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008223 // - if music is playing, always limit the volume to current music volume,
8224 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008225 if (!Intersection(deviceTypes,
8226 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8227 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008228 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8229 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008230 ((volumeSource == alarmVolumeSrc ||
8231 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008232 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8233 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8234 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008235 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8236 curves.canBeMuted()) {
8237
Eric Laurente552edb2014-03-10 17:42:56 -07008238 // when the phone is ringing we must consider that music could have been paused just before
8239 // by the music application and behave as if music was active if the last music track was
8240 // just stopped
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008241 if (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8242 || mLimitRingtoneVolume) {
François Gaffie43c73442018-11-08 08:21:55 +01008243 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008244 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008245 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8246 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008247 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008248 float musicVolDb = computeVolume(musicCurves,
8249 musicVolumeSrc,
8250 musicCurves.getVolumeIndex(musicDevice),
Oscar Azucenae763f7a2024-03-27 18:56:02 -07008251 musicDevice,
8252 /* computeInternalInteraction= */ false);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008253 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8254 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8255 if (volumeDb > minVolDb) {
8256 volumeDb = minVolDb;
8257 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008258 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008259 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8260 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008261 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8262 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8263 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8264 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008265 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008266 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008267 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8268 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008269 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8270 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008271 }
8272 }
jiabin9a3361e2019-10-01 09:38:30 -07008273 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008274 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008275 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008276 }
8277 }
8278
François Gaffie43c73442018-11-08 08:21:55 +01008279 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008280}
8281
Eric Laurent3839bc02018-07-10 18:33:34 -07008282int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008283 VolumeSource fromVolumeSource,
8284 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008285{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008286 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008287 return srcIndex;
8288 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008289 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8290 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008291 float minSrc = (float)srcCurves.getVolumeIndexMin();
8292 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8293 float minDst = (float)dstCurves.getVolumeIndexMin();
8294 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008295
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008296 // preserve mute request or correct range
8297 if (srcIndex < minSrc) {
8298 if (srcIndex == 0) {
8299 return 0;
8300 }
8301 srcIndex = minSrc;
8302 } else if (srcIndex > maxSrc) {
8303 srcIndex = maxSrc;
8304 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008305 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8306}
8307
François Gaffieaaac0fd2018-11-22 17:56:39 +01008308status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8309 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008310 int index,
8311 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008312 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008313 int delayMs,
8314 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008315{
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008316 // APM is single threaded, and single instance.
8317 static std::set<IVolumeCurves*> invalidCurvesReported;
8318
François Gaffieaaac0fd2018-11-22 17:56:39 +01008319 // do not change actual attributes volume if the attributes is muted
8320 if (outputDesc->isMuted(volumeSource)) {
8321 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8322 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008323 return NO_ERROR;
8324 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008325
Eric Laurent5baf07c2024-01-11 16:57:27 +00008326 bool isVoiceVolSrc;
8327 bool isBtScoVolSrc;
8328 if (!isVolumeConsistentForCalls(
8329 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008330 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008331 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008332 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008333 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008334
jiabin9a3361e2019-10-01 09:38:30 -07008335 if (deviceTypes.empty()) {
8336 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008337 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008338 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008339 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008340 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008341
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008342 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
Mikhail Naganov8b648e52024-09-06 11:22:13 -07008343 if (!invalidCurvesReported.count(&curves)) {
8344 invalidCurvesReported.insert(&curves);
8345 String8 dump;
8346 curves.dump(&dump);
8347 ALOGE("invalid volume index range in the curve:\n%s", dump.c_str());
8348 }
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008349 return BAD_VALUE;
8350 }
8351
jiabin9a3361e2019-10-01 09:38:30 -07008352 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8353 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008354 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008355 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008356 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8357 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008358 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008359 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008360 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008361 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8362 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008363
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008364 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008365 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8366 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8367 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008368 }
Eric Laurente552edb2014-03-10 17:42:56 -07008369 return NO_ERROR;
8370}
8371
Eric Laurent5baf07c2024-01-11 16:57:27 +00008372void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008373 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008374 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008375 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008376 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008377 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008378 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8379 } else {
8380 voiceVolume = index == 0 ? 0.0 : 1.0;
8381 }
8382 if (voiceVolume != mLastVoiceVolume) {
8383 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8384 mLastVoiceVolume = voiceVolume;
8385 }
8386}
8387
8388bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8389 const DeviceTypeSet& deviceTypes,
8390 bool& isVoiceVolSrc,
8391 bool& isBtScoVolSrc,
8392 const char* caller) {
8393 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8394 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8395 const bool isScoRequested = isScoRequestedForComm();
8396 const bool isHAUsed = isHearingAidUsedForComm();
8397
8398 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8399 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8400
8401 if ((callVolSrc != btScoVolSrc) &&
8402 ((isVoiceVolSrc && isScoRequested) ||
8403 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8404 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8405 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8406 volumeSource, isScoRequested ? " " : " not ");
8407 return false;
8408 }
8409 return true;
8410}
8411
Eric Laurentc75307b2015-03-17 15:29:32 -07008412void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008413 const DeviceTypeSet& deviceTypes,
8414 int delayMs,
8415 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008416{
jiabincd510522020-01-22 09:40:55 -08008417 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008418 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8419 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8420 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008421 curves.getVolumeIndex(deviceTypes),
8422 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008423 }
8424}
8425
François Gaffiec005e562018-11-06 15:04:49 +01008426void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8427 bool on,
8428 const sp<AudioOutputDescriptor>& outputDesc,
8429 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008430 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008431{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008432 std::vector<VolumeSource> sourcesToMute;
8433 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8434 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8435 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008436 VolumeSource source = toVolumeSource(attributes, false);
8437 if ((source != VOLUME_SOURCE_NONE) &&
8438 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8439 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008440 sourcesToMute.push_back(source);
8441 }
Eric Laurente552edb2014-03-10 17:42:56 -07008442 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008443 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008444 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008445 }
8446
Eric Laurente552edb2014-03-10 17:42:56 -07008447}
8448
François Gaffieaaac0fd2018-11-22 17:56:39 +01008449void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8450 bool on,
8451 const sp<AudioOutputDescriptor>& outputDesc,
8452 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008453 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008454{
jiabin9a3361e2019-10-01 09:38:30 -07008455 if (deviceTypes.empty()) {
8456 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008457 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008458 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008459 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008460 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008461 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008462 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008463 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8464 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008465 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008466 }
8467 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008468 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8469 // ignored
8470 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008471 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008472 if (!outputDesc->isMuted(volumeSource)) {
8473 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008474 return;
8475 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008476 if (outputDesc->decMuteCount(volumeSource) == 0) {
8477 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008478 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008479 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008480 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008481 delayMs);
8482 }
8483 }
8484}
8485
François Gaffie53615e22015-03-19 09:24:12 +01008486bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8487{
François Gaffiec005e562018-11-06 15:04:49 +01008488 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008489 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8490 return true;
8491 }
8492
8493 // has known usage?
8494 switch (paa->usage) {
8495 case AUDIO_USAGE_UNKNOWN:
8496 case AUDIO_USAGE_MEDIA:
8497 case AUDIO_USAGE_VOICE_COMMUNICATION:
8498 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8499 case AUDIO_USAGE_ALARM:
8500 case AUDIO_USAGE_NOTIFICATION:
8501 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8502 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8503 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8504 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8505 case AUDIO_USAGE_NOTIFICATION_EVENT:
8506 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8507 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8508 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8509 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008510 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008511 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008512 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008513 case AUDIO_USAGE_EMERGENCY:
8514 case AUDIO_USAGE_SAFETY:
8515 case AUDIO_USAGE_VEHICLE_STATUS:
8516 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008517 break;
8518 default:
8519 return false;
8520 }
8521 return true;
8522}
8523
François Gaffie2110e042015-03-24 08:41:51 +01008524audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8525{
8526 return mEngine->getForceUse(usage);
8527}
8528
Eric Laurent96d1dda2022-03-14 17:14:19 +01008529bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008530 return isStateInCall(mEngine->getPhoneState());
8531}
8532
Eric Laurent96d1dda2022-03-14 17:14:19 +01008533bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008534 return is_state_in_call(state);
8535}
8536
Eric Laurentf9cccec2022-11-16 19:12:00 +01008537bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008538 audio_mode_t mode = mEngine->getPhoneState();
8539 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008540 || (mode == AUDIO_MODE_CALL_SCREEN)
8541 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008542}
8543
Eric Laurentf9cccec2022-11-16 19:12:00 +01008544bool AudioPolicyManager::isInCallOrScreening() const {
8545 audio_mode_t mode = mEngine->getPhoneState();
8546 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8547}
8548
Eric Laurentd60560a2015-04-10 11:31:20 -07008549void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8550{
8551 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008552 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008553 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008554 sourceDesc->sinkDevice()->equals(deviceDesc))
Eric Laurent963dbcc2024-06-20 12:34:15 +00008555 && !sourceDesc->isCallRx()) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008556 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008557 }
8558 }
8559
8560 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8561 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8562 bool release = false;
8563 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8564 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8565 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8566 source->ext.device.type == deviceDesc->type()) {
8567 release = true;
8568 }
8569 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008570 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008571 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8572 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8573 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008574 sink->ext.device.type == deviceDesc->type() &&
8575 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8576 || strncmp(sink->ext.device.address, address,
8577 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008578 release = true;
8579 }
8580 }
8581 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008582 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8583 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008584 }
8585 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008586
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008587 mInputs.clearSessionRoutesForDevice(deviceDesc);
8588
Francois Gaffie716e1432019-01-14 16:58:59 +01008589 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008590}
8591
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008592void AudioPolicyManager::modifySurroundFormats(
8593 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008594 std::unordered_set<audio_format_t> enforcedSurround(
8595 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008596 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008597 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008598 allSurround.insert(pair.first);
8599 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8600 }
Phil Burk09bc4612016-02-24 15:58:15 -08008601
8602 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8603 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008604 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008605 // This is the resulting set of formats depending on the surround mode:
8606 // 'all surround' = allSurround
8607 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8608 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8609 // 'manual surround' = mManualSurroundFormats
8610 // AUTO: formats v 'enforced surround'
8611 // ALWAYS: formats v 'all surround' v 'enforced surround'
8612 // NEVER: formats ^ 'non-surround'
8613 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008614
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008615 std::unordered_set<audio_format_t> formatSet;
8616 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8617 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008618 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008619 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008620 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008621 formatSet.insert(*formatIter);
8622 }
8623 }
8624 } else {
8625 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8626 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008627 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008628
jiabin81772902018-04-02 17:52:27 -07008629 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008630 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008631 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8632 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8633 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008634 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008635 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8636 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8637 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008638 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008639 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008640 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008641 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008642 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008643 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008644}
8645
jiabin06e4bab2019-07-29 10:13:34 -07008646void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8647 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008648 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8649 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8650
8651 // If NEVER, then remove support for channelMasks > stereo.
8652 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008653 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8654 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008655 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008656 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008657 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008658 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008659 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008660 }
8661 }
jiabin81772902018-04-02 17:52:27 -07008662 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8663 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8664 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008665 bool supports5dot1 = false;
8666 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008667 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008668 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8669 supports5dot1 = true;
8670 break;
8671 }
8672 }
8673 // If not then add 5.1 support.
8674 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008675 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008676 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008677 }
Phil Burk09bc4612016-02-24 15:58:15 -08008678 }
8679}
8680
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008681void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008682 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008683 const sp<IOProfile>& profile) {
8684 if (!profile->hasDynamicAudioProfile()) {
8685 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008686 }
François Gaffie112b0af2015-11-19 16:13:25 +01008687
jiabin12537fc2023-10-12 17:56:08 +00008688 audio_port_v7 devicePort;
8689 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008690
jiabin12537fc2023-10-12 17:56:08 +00008691 audio_port_v7 mixPort;
8692 profile->toAudioPort(&mixPort);
8693 mixPort.ext.mix.handle = ioHandle;
8694
8695 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8696 if (status != NO_ERROR) {
8697 ALOGE("%s failed to query the attributes of the mix port", __func__);
8698 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008699 }
jiabin12537fc2023-10-12 17:56:08 +00008700
8701 std::set<audio_format_t> supportedFormats;
8702 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8703 supportedFormats.insert(mixPort.audio_profiles[i].format);
8704 }
8705 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8706 mReportedFormatsMap[devDesc] = formats;
8707
8708 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8709 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8710 modifySurroundFormats(devDesc, &formats);
8711 size_t modifiedNumProfiles = 0;
8712 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8713 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8714 formats.end()) {
8715 // Skip the format that is not present after modifying surround formats.
8716 continue;
8717 }
8718 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8719 sizeof(struct audio_profile));
8720 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8721 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8722 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8723 modifySurroundChannelMasks(&channels);
8724 std::copy(channels.begin(), channels.end(),
8725 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8726 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8727 }
8728 mixPort.num_audio_profiles = modifiedNumProfiles;
8729 }
8730 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008731}
Eric Laurentd60560a2015-04-10 11:31:20 -07008732
Mikhail Naganovdc769682018-05-04 15:34:08 -07008733status_t AudioPolicyManager::installPatch(const char *caller,
8734 audio_patch_handle_t *patchHandle,
8735 AudioIODescriptorInterface *ioDescriptor,
8736 const struct audio_patch *patch,
8737 int delayMs)
8738{
8739 ssize_t index = mAudioPatches.indexOfKey(
8740 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8741 *patchHandle : ioDescriptor->getPatchHandle());
8742 sp<AudioPatch> patchDesc;
8743 status_t status = installPatch(
8744 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8745 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008746 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008747 }
8748 return status;
8749}
8750
8751status_t AudioPolicyManager::installPatch(const char *caller,
8752 ssize_t index,
8753 audio_patch_handle_t *patchHandle,
8754 const struct audio_patch *patch,
8755 int delayMs,
8756 uid_t uid,
8757 sp<AudioPatch> *patchDescPtr)
8758{
8759 sp<AudioPatch> patchDesc;
8760 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8761 if (index >= 0) {
8762 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008763 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008764 }
8765
8766 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8767 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8768 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8769 if (status == NO_ERROR) {
8770 if (index < 0) {
8771 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008772 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008773 } else {
8774 patchDesc->mPatch = *patch;
8775 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008776 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008777 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008778 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008779 }
8780 nextAudioPortGeneration();
8781 mpClientInterface->onAudioPatchListUpdate();
8782 }
8783 if (patchDescPtr) *patchDescPtr = patchDesc;
8784 return status;
8785}
8786
jiabinbce0c1d2020-10-05 11:20:18 -07008787bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8788{
8789 const TrackClientVector activeClients = output->getActiveClients();
8790 if (activeClients.empty()) {
8791 return true;
8792 }
8793 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8794 if (index < 0) {
8795 ALOGE("%s, no audio patch found while there are active clients on output %d",
8796 __func__, output->getId());
8797 return false;
8798 }
8799 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8800 DeviceVector routedDevices;
8801 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8802 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8803 patchDesc->mPatch.sinks[i].id);
8804 if (device == nullptr) {
8805 ALOGE("%s, no audio device found with id(%d)",
8806 __func__, patchDesc->mPatch.sinks[i].id);
8807 return false;
8808 }
8809 routedDevices.add(device);
8810 }
8811 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008812 if (client->isInvalid()) {
8813 // No need to take care about invalidated clients.
8814 continue;
8815 }
jiabinbce0c1d2020-10-05 11:20:18 -07008816 sp<DeviceDescriptor> preferredDevice =
8817 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8818 if (mEngine->getOutputDevicesForAttributes(
8819 client->attributes(), preferredDevice, false) == routedDevices) {
8820 return false;
8821 }
8822 }
8823 return true;
8824}
8825
8826sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008827 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008828 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8829 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008830{
8831 for (const auto& device : devices) {
8832 // TODO: This should be checking if the profile supports the device combo.
8833 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008834 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8835 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008836 return nullptr;
8837 }
8838 }
8839 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8840 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008841 audio_attributes_t attributes = AUDIO_ATTRIBUTES_INITIALIZER;
jiabina84c3d32022-12-02 18:59:55 +00008842 status_t status = desc->open(halConfig, mixerConfig, devices,
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008843 AUDIO_STREAM_DEFAULT, flags, &output, attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008844 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008845 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008846 return nullptr;
8847 }
jiabin14b50cc2023-12-13 19:01:52 +00008848 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8849 auto portConfig = desc->getConfig();
8850 for (const auto& device : devices) {
8851 device->setPreferredConfig(&portConfig);
8852 }
8853 }
jiabinbce0c1d2020-10-05 11:20:18 -07008854
8855 // Here is where the out_set_parameters() for card & device gets called
8856 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8857 const audio_devices_t deviceType = device->type();
8858 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008859 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008860 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8861 mpClientInterface->setParameters(output, String8(param));
8862 free(param);
8863 }
jiabin12537fc2023-10-12 17:56:08 +00008864 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008865 if (!profile->hasValidAudioProfile()) {
8866 ALOGW("%s() missing param", __func__);
8867 desc->close();
8868 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008869 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8870 // Reopen the output with the best audio profile picked by APM when the profile supports
8871 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008872 desc->close();
8873 output = AUDIO_IO_HANDLE_NONE;
8874 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8875 profile->pickAudioProfile(
8876 config.sample_rate, config.channel_mask, config.format);
8877 config.offload_info.sample_rate = config.sample_rate;
8878 config.offload_info.channel_mask = config.channel_mask;
8879 config.offload_info.format = config.format;
8880
Haofan Wangb75aa6a2024-07-09 23:06:58 -07008881 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output,
8882 attributes);
jiabinbce0c1d2020-10-05 11:20:18 -07008883 if (status != NO_ERROR) {
8884 return nullptr;
8885 }
8886 }
8887
8888 addOutput(output, desc);
Eric Laurent0ca09402024-05-16 17:48:59 +00008889 setOutputDevices(__func__, desc,
8890 devices,
8891 true,
8892 0,
8893 NULL);
baek.kim -61c20122022-07-27 10:05:32 +00008894 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8895 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8896
jiabinbce0c1d2020-10-05 11:20:18 -07008897 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8898 sp<AudioPolicyMix> policyMix;
8899 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8900 policyMix->setOutput(desc);
8901 desc->mPolicyMix = policyMix;
8902 } else {
8903 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008904 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008905 }
8906
baek.kim -61c20122022-07-27 10:05:32 +00008907 } else if (hasPrimaryOutput() && speaker != nullptr
8908 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008909 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8910 // no duplicated output for:
8911 // - direct outputs
8912 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008913 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008914 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8915
8916 //TODO: configure audio effect output stage here
8917
8918 // open a duplicating output thread for the new output and the primary output
8919 sp<SwAudioOutputDescriptor> dupOutputDesc =
8920 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8921 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8922 if (status == NO_ERROR) {
8923 // add duplicated output descriptor
8924 addOutput(duplicatedOutput, dupOutputDesc);
8925 } else {
8926 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8927 mPrimaryOutput->mIoHandle, output);
8928 desc->close();
8929 removeOutput(output);
8930 nextAudioPortGeneration();
8931 return nullptr;
8932 }
8933 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008934 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8935 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8936 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008937 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008938 }
jiabinbce0c1d2020-10-05 11:20:18 -07008939 return desc;
8940}
8941
jiabinf1c73972022-04-14 16:28:52 -07008942status_t AudioPolicyManager::getDevicesForAttributes(
8943 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8944 // Devices are determined in the following precedence:
8945 //
8946 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8947 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8948 //
8949 // If no such dynamic policy then
8950 // 2) Devices containing an active client using setPreferredDevice
8951 // with same strategy as the attributes.
8952 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8953 //
8954 // If no corresponding active client with setPreferredDevice then
8955 // 3) Devices associated with the strategy determined by the attributes
8956 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8957 //
8958 // See related getOutputForAttrInt().
8959
8960 // check dynamic policies but only for primary descriptors (secondary not used for audible
8961 // audio routing, only used for duplication for playback capture)
8962 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008963 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008964 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008965 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8966 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8967 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008968 if (status != OK) {
8969 return status;
8970 }
8971
8972 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8973 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8974 // as they are unaffected by device/stream volume
8975 // (per SwAudioOutputDescriptor::isFixedVolume()).
8976 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8977 ) {
8978 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8979 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8980 devices.add(deviceDesc);
8981 } else {
8982 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8983 // which selects setPreferredDevice if active. This means forVolume call
8984 // will take an active setPreferredDevice, if such exists.
8985
8986 devices = mEngine->getOutputDevicesForAttributes(
8987 attr, nullptr /* preferredDevice */, false /* fromCache */);
8988 }
8989
8990 if (forVolume) {
8991 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8992 // for single volume control in AudioService (such relationship should exist if
8993 // SPEAKER_SAFE is present).
8994 //
8995 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8996 DeviceVector speakerSafeDevices =
8997 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8998 if (!speakerSafeDevices.isEmpty()) {
8999 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
9000 devices.remove(speakerSafeDevices);
9001 }
9002 }
9003
9004 return NO_ERROR;
9005}
9006
9007status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
9008 AudioProfileVector& audioProfiles,
9009 uint32_t flags,
9010 bool isInput) {
9011 for (const auto& hwModule : mHwModules) {
9012 // the MSD module checks for different conditions
9013 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
9014 continue;
9015 }
9016 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
9017 : hwModule->getOutputProfiles();
9018 for (const auto& profile : ioProfiles) {
9019 if (!profile->areAllDevicesSupported(devices) ||
9020 !profile->isCompatibleProfileForFlags(
9021 flags, false /*exactMatchRequiredForInputFlags*/)) {
9022 continue;
9023 }
9024 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9025 }
9026 }
9027
9028 if (!isInput) {
9029 // add the direct profiles from MSD if present and has audio patches to all the output(s)
9030 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
9031 if (msdModule != nullptr) {
9032 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
9033 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
9034 for (const auto &profile: msdModule->getOutputProfiles()) {
9035 if (!profile->asAudioPort()->isDirectOutput()) {
9036 continue;
9037 }
9038 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
9039 }
9040 } else {
9041 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
9042 }
9043 }
9044 }
9045
9046 return NO_ERROR;
9047}
9048
jiabin3ff8d7d2022-12-13 06:27:44 +00009049sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
9050 const audio_config_t *config,
9051 audio_output_flags_t flags,
9052 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00009053 closeOutput(outputDesc->mIoHandle);
9054 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
9055 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
9056 if (preferredOutput == nullptr) {
9057 ALOGE("%s failed to reopen output device=%d, caller=%s",
9058 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00009059 }
jiabin3ff8d7d2022-12-13 06:27:44 +00009060 return preferredOutput;
9061}
9062
9063void AudioPolicyManager::reopenOutputsWithDevices(
9064 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
9065 for (const auto& [output, devices] : outputsToReopen) {
9066 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
9067 closeOutput(output);
9068 openOutputWithProfileAndDevice(desc->mProfile, devices);
9069 }
jiabina84c3d32022-12-02 18:59:55 +00009070}
9071
jiabinc44b3462022-12-08 12:52:31 -08009072PortHandleVector AudioPolicyManager::getClientsForStream(
9073 audio_stream_type_t streamType) const {
9074 PortHandleVector clients;
9075 for (size_t i = 0; i < mOutputs.size(); ++i) {
9076 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
9077 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9078 }
9079 return clients;
9080}
9081
9082void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
9083 PortHandleVector clients;
9084 for (auto stream : streams) {
9085 PortHandleVector clientsForStream = getClientsForStream(stream);
9086 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
9087 }
9088 mpClientInterface->invalidateTracks(clients);
9089}
9090
jiabin220eea12024-05-17 17:55:20 +00009091void AudioPolicyManager::updateClientsInternalMute(
9092 const sp<android::SwAudioOutputDescriptor> &desc) {
9093 if (!desc->isBitPerfect() ||
9094 !com::android::media::audioserver::
9095 fix_concurrent_playback_behavior_with_bit_perfect_client()) {
9096 // This is only used for bit perfect output now.
9097 return;
9098 }
9099 sp<TrackClientDescriptor> bitPerfectClient = nullptr;
9100 bool bitPerfectClientInternalMute = false;
9101 std::vector<media::TrackInternalMuteInfo> clientsInternalMute;
9102 for (const sp<TrackClientDescriptor>& client : desc->getActiveClients()) {
9103 if ((client->flags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
9104 bitPerfectClient = client;
9105 continue;
9106 }
9107 bool muted = false;
9108 if (client->stream() == AUDIO_STREAM_SYSTEM) {
9109 // System sound is muted.
9110 muted = true;
9111 } else {
9112 bitPerfectClientInternalMute = true;
9113 }
9114 if (client->setInternalMute(muted)) {
9115 auto result = legacy2aidl_audio_port_handle_t_int32_t(client->portId());
9116 if (!result.ok()) {
9117 ALOGE("%s, failed to convert port id(%d) to aidl", __func__, client->portId());
9118 continue;
9119 }
9120 media::TrackInternalMuteInfo info;
9121 info.portId = result.value();
9122 info.muted = client->getInternalMute();
9123 clientsInternalMute.push_back(std::move(info));
9124 }
9125 }
9126 if (bitPerfectClient != nullptr &&
9127 bitPerfectClient->setInternalMute(bitPerfectClientInternalMute)) {
9128 auto result = legacy2aidl_audio_port_handle_t_int32_t(bitPerfectClient->portId());
9129 if (result.ok()) {
9130 media::TrackInternalMuteInfo info;
9131 info.portId = result.value();
9132 info.muted = bitPerfectClient->getInternalMute();
9133 clientsInternalMute.push_back(std::move(info));
9134 } else {
9135 ALOGE("%s, failed to convert port id(%d) of bit perfect client to aidl",
9136 __func__, bitPerfectClient->portId());
9137 }
9138 }
9139 if (!clientsInternalMute.empty()) {
9140 if (status_t status = mpClientInterface->setTracksInternalMute(clientsInternalMute);
9141 status != NO_ERROR) {
9142 ALOGE("%s, failed to update tracks internal mute, err=%d", __func__, status);
9143 }
9144 }
9145}
9146
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08009147} // namespace android