blob: d6338b5f64023b8b65eb0711b6729c563971465d [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 Tsai572e61d2024-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 Tsai572e61d2024-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 Tsai572e61d2024-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));
jiabin3ff8d7d2022-12-13 06:27:44 +0000347 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
348 // 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 Tsai572e61d2024-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);
587 for (size_t i = 0; i < mOutputs.size(); i++) {
588 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
589 // mute media strategies and delay device switch by the largest
590 // This avoid sending the music tail into the earpiece or headset.
591 setStrategyMute(musicStrategy, true, desc);
592 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
593 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
594 nullptr, true /*fromCache*/).types());
595 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800596 // Toggle the device state: UNAVAILABLE -> AVAILABLE
597 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100598 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800599 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800600 device_address, device_name,
601 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800602 if (status != NO_ERROR) {
603 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
604 status);
605 return status;
606 }
607
608 status = setDeviceConnectionState(device,
609 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800610 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800611 if (status != NO_ERROR) {
612 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
613 status);
614 return status;
615 }
616
617 return NO_ERROR;
618}
619
Pattydd807582021-11-04 21:01:03 +0800620status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
621 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800622{
Pattydd807582021-11-04 21:01:03 +0800623 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800624 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800625 std::unordered_set<audio_format_t> formatSet;
626 sp<HwModule> primaryModule =
627 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700628 if (primaryModule == nullptr) {
629 ALOGE("%s() unable to get primary module", __func__);
630 return NO_INIT;
631 }
Pattydd807582021-11-04 21:01:03 +0800632
633 DeviceTypeSet audioDeviceSet;
634
635 switch(device) {
636 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
637 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
638 break;
639 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800640 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
641 break;
642 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
643 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800644 break;
645 default:
646 ALOGE("%s() device type 0x%08x not supported", __func__, device);
647 return BAD_VALUE;
648 }
649
jiabin9a3361e2019-10-01 09:38:30 -0700650 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800651 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800652 for (const auto& device : declaredDevices) {
653 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800654 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800655 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800656 return status;
657}
658
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100659DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
660{
661 DeviceVector rxSinkdevices{};
662 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
663 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
664 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
665 auto rxSinkDevice = rxSinkdevices.itemAt(0);
666 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
667 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
668 // retrieve Rx Source device descriptor
669 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
670 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
671
672 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
673 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
674 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
675 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
676 return DeviceVector(rxSinkDevice);
677 }
678 }
679 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
680 // the device returned is not necessarily reachable via this output
681 // (filter later by setOutputDevices())
682 return getNewOutputDevices(mPrimaryOutput, fromCache);
683}
684
685status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
686{
François Gaffiedb1755b2023-09-01 11:50:35 +0200687 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100688 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
689 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
690 }
691 return INVALID_OPERATION;
692}
693
694status_t AudioPolicyManager::updateCallRoutingInternal(
695 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700696{
697 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100698 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700699 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200700 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700701 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100702 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700703 }
François Gaffie11d30102018-11-02 16:09:09 +0100704
Francois Gaffie716e1432019-01-14 16:58:59 +0100705 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100706 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200707
708 disconnectTelephonyAudioSource(mCallRxSourceClient);
709 disconnectTelephonyAudioSource(mCallTxSourceClient);
710
711 if (rxDevices.isEmpty()) {
712 ALOGW("%s() no selected output device", __func__);
713 return INVALID_OPERATION;
714 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000715 if (txSourceDevice == nullptr) {
716 ALOGE("%s() selected input device not available", __func__);
717 return INVALID_OPERATION;
718 }
François Gaffiec005e562018-11-06 15:04:49 +0100719
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100720 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100721 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700722
François Gaffie9eb18552018-11-05 10:33:26 +0100723 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700724 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100725 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700726 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100727 // retrieve Rx Source and Tx Sink device descriptors
728 sp<DeviceDescriptor> rxSourceDevice =
729 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
730 String8(),
731 AUDIO_FORMAT_DEFAULT);
732 sp<DeviceDescriptor> txSinkDevice =
733 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
734 String8(),
735 AUDIO_FORMAT_DEFAULT);
736
737 // RX and TX Telephony device are declared by Primary Audio HAL
738 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
739 (telephonyRxModule->getHalVersionMajor() >= 3)) {
740 if (rxSourceDevice == 0 || txSinkDevice == 0) {
741 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100742 ALOGE("%s() no telephony Tx and/or RX device", __func__);
743 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100744 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100745 // createAudioPatchInternal now supports both HW / SW bridging
746 createRxPatch = true;
747 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100748 } else {
749 // If the RX device is on the primary HW module, then use legacy routing method for
750 // voice calls via setOutputDevice() on primary output.
751 // Otherwise, create two audio patches for TX and RX path.
752 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
753 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700754 // If the TX device is also on the primary HW module, setOutputDevice() will take care
755 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100756 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
757 (txSinkDevice != 0);
758 }
759 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
760 // Otherwise, create two audio patches for TX and RX path.
761 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200762 if (!hasPrimaryOutput()) {
763 ALOGW("%s() no primary output available", __func__);
764 return INVALID_OPERATION;
765 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530766 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700767 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200768 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800769 // If the TX device is on the primary HW module but RX device is
770 // on other HW module, SinkMetaData of telephony input should handle it
771 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700772 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700773 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100774 // terminate active capture if on the same HW module as the call TX source device
775 // FIXME: would be better to refine to only inputs whose profile connects to the
776 // call TX device but this information is not in the audio patch and logic here must be
777 // symmetric to the one in startInput()
778 for (const auto& activeDesc : mInputs.getActiveInputs()) {
779 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
780 closeActiveClients(activeDesc);
781 }
782 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200783 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800784 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100785 if (waitMs != nullptr) {
786 *waitMs = muteWaitMs;
787 }
788 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800789}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700790
Mikhail Naganov100f0122018-11-29 11:22:16 -0800791bool AudioPolicyManager::isDeviceOfModule(
792 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
793 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
794 if (module != 0) {
795 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
796 .indexOf(devDesc) != NAME_NOT_FOUND
797 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
798 .indexOf(devDesc) != NAME_NOT_FOUND;
799 }
800 return false;
801}
802
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200803void AudioPolicyManager::connectTelephonyRxAudioSource()
804{
Francois Gaffie601801d2021-06-22 13:27:39 +0200805 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200806 const struct audio_port_config source = {
807 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
808 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
809 };
810 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100811
812 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
813 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
814 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
815 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200816 ALOGE_IF(mCallRxSourceClient == nullptr,
817 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200818}
819
Francois Gaffie601801d2021-06-22 13:27:39 +0200820void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200821{
Francois Gaffie601801d2021-06-22 13:27:39 +0200822 if (clientDesc == nullptr) {
823 return;
824 }
825 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
826 "%s error stopping audio source", __func__);
827 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200828}
829
830void AudioPolicyManager::connectTelephonyTxAudioSource(
831 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
832 uint32_t delayMs)
833{
Francois Gaffie601801d2021-06-22 13:27:39 +0200834 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200835 if (srcDevice == nullptr || sinkDevice == nullptr) {
836 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
837 return;
838 }
839 PatchBuilder patchBuilder;
840 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
841 ALOGV("%s between source %s and sink %s", __func__,
842 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200843 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200844 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
845
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200846 struct audio_port_config source = {};
847 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100848 mCallTxSourceClient = new SourceClientDescriptor(
849 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
850 mCommunnicationStrategy, toVolumeSource(aa), true);
851 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
852
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200853 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
854 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200855 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
856 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200857 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
858 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200859 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200860 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200861}
862
Eric Laurente0720872014-03-11 09:30:41 -0700863void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700864{
865 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100866 // store previous phone state for management of sonification strategy below
867 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100868 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100869
870 if (mEngine->setPhoneState(state) != NO_ERROR) {
871 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700872 return;
873 }
François Gaffie2110e042015-03-24 08:41:51 +0100874 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700875 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700876 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700877 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800878 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700879 }
880
François Gaffie2110e042015-03-24 08:41:51 +0100881 /**
882 * Switching to or from incall state or switching between telephony and VoIP lead to force
883 * routing command.
884 */
Eric Laurent74b71512019-11-06 17:21:57 -0800885 bool force = ((isStateInCall(oldState) != isStateInCall(state))
886 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700887
888 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700889 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700890
Eric Laurente552edb2014-03-10 17:42:56 -0700891 int delayMs = 0;
892 if (isStateInCall(state)) {
893 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100894 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
895 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700896 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700897 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700898 // mute media and sonification strategies and delay device switch by the largest
899 // latency of any output where either strategy is active.
900 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100901 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
902 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
903 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700904 (delayMs < (int)desc->latency()*2)) {
905 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700906 }
François Gaffiec005e562018-11-06 15:04:49 +0100907 setStrategyMute(musicStrategy, true, desc);
908 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
909 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
910 nullptr, true /*fromCache*/).types());
911 setStrategyMute(sonificationStrategy, true, desc);
912 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
913 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
914 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700915 }
916 }
917
François Gaffiedb1755b2023-09-01 11:50:35 +0200918 if (state == AUDIO_MODE_IN_CALL) {
919 (void)updateCallRouting(false /*fromCache*/, delayMs);
920 } else {
921 if (oldState == AUDIO_MODE_IN_CALL) {
922 disconnectTelephonyAudioSource(mCallRxSourceClient);
923 disconnectTelephonyAudioSource(mCallTxSourceClient);
924 }
925 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100926 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
927 // force routing command to audio hardware when ending call
928 // even if no device change is needed
929 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
930 rxDevices = mPrimaryOutput->devices();
931 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530932 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700933 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700934 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700935
jiabin3ff8d7d2022-12-13 06:27:44 +0000936 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700937 // reevaluate routing on all outputs in case tracks have been started during the call
938 for (size_t i = 0; i < mOutputs.size(); i++) {
939 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100940 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200941 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
942 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000943 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
944 // If the device is using preferred mixer attributes, the output need to reopen
945 // with default configuration when the new selected devices are different from
946 // current routing devices.
947 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
948 continue;
949 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530950 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200951 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700952 }
953 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000954 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700955
Eric Laurent96d1dda2022-03-14 17:14:19 +0100956 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
957
Eric Laurente552edb2014-03-10 17:42:56 -0700958 if (isStateInCall(state)) {
959 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700960 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800961 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700962 }
963
964 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100965 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
966 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700967}
968
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700969audio_mode_t AudioPolicyManager::getPhoneState() {
970 return mEngine->getPhoneState();
971}
972
Eric Laurente0720872014-03-11 09:30:41 -0700973void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100974 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700975{
François Gaffie2110e042015-03-24 08:41:51 +0100976 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700977 if (config == mEngine->getForceUse(usage)) {
978 return;
979 }
Eric Laurente552edb2014-03-10 17:42:56 -0700980
François Gaffie2110e042015-03-24 08:41:51 +0100981 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
982 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
983 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700984 }
François Gaffie2110e042015-03-24 08:41:51 +0100985 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
986 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
987 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700988
989 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700990 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800991
Eric Laurent22fcda22019-05-17 16:28:47 -0700992 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
993 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800994 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700995 }
996
Eric Laurentdc462862016-07-19 12:29:53 -0700997 //FIXME: workaround for truncated touch sounds
998 // to be removed when the problem is handled by system UI
999 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -07001000 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
1001 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
1002 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -07001003
1004 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +01001005 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -07001006}
1007
Eric Laurente0720872014-03-11 09:30:41 -07001008void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -07001009{
1010 ALOGV("setSystemProperty() property %s, value %s", property, value);
1011}
1012
Dorin Drimusecc9f422022-03-09 17:57:40 +01001013// Find an MSD output profile compatible with the parameters passed.
1014// When "directOnly" is set, restrict search to profiles for direct outputs.
1015sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
1016 const DeviceVector& devices,
1017 uint32_t samplingRate,
1018 audio_format_t format,
1019 audio_channel_mask_t channelMask,
1020 audio_output_flags_t flags,
1021 bool directOnly)
1022{
1023 flags = getRelevantFlags(flags, directOnly);
1024
1025 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1026 if (msdModule != nullptr) {
1027 // for the msd module check if there are patches to the output devices
1028 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1029 HwModuleCollection modules;
1030 modules.add(msdModule);
1031 return searchCompatibleProfileHwModules(
1032 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1033 flags, directOnly);
1034 }
1035 }
1036 return nullptr;
1037}
1038
Michael Chana94fbb22018-04-24 14:31:19 +10001039// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1040// search to profiles for direct outputs.
1041sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001042 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001043 uint32_t samplingRate,
1044 audio_format_t format,
1045 audio_channel_mask_t channelMask,
1046 audio_output_flags_t flags,
1047 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001048{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001049 flags = getRelevantFlags(flags, directOnly);
1050
1051 return searchCompatibleProfileHwModules(
1052 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1053}
1054
1055audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1056 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001057 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001058 // only retain flags that will drive the direct output profile selection
1059 // if explicitly requested
1060 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001061 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001062 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1063 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001064 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001065 return flags;
1066}
Eric Laurent861a6282015-05-18 15:40:16 -07001067
Dorin Drimusecc9f422022-03-09 17:57:40 +01001068sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1069 const HwModuleCollection& hwModules,
1070 const DeviceVector& devices,
1071 uint32_t samplingRate,
1072 audio_format_t format,
1073 audio_channel_mask_t channelMask,
1074 audio_output_flags_t flags,
1075 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001076 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001077 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001078 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00001079 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001080 samplingRate, NULL /*updatedSamplingRate*/,
1081 format, NULL /*updatedFormat*/,
1082 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001083 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001084 continue;
1085 }
1086 // reject profiles not corresponding to a device currently available
1087 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1088 continue;
1089 }
1090 // reject profiles if connected device does not support codec
1091 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1092 continue;
1093 }
1094 if (!directOnly) {
1095 return curProfile;
1096 }
1097
1098 // when searching for direct outputs, if several profiles are compatible, give priority
1099 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001100 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001101 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001102 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001103 }
1104 profile = curProfile;
1105 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1106 break;
1107 }
Eric Laurente552edb2014-03-10 17:42:56 -07001108 }
1109 }
Eric Laurent861a6282015-05-18 15:40:16 -07001110 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001111}
1112
Eric Laurentfa0f6742021-08-17 18:39:44 +02001113sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001114 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001115{
1116 for (const auto& hwModule : mHwModules) {
1117 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001118 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001119 continue;
1120 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001121 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001122 // reject profiles not corresponding to a device currently available
1123 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1124 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1125 continue;
1126 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001127 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1128 != devices.size()) {
1129 continue;
1130 }
1131 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001132 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1133 return curProfile;
1134 }
1135 }
1136 return nullptr;
1137}
1138
Eric Laurentf4e63452017-11-06 19:31:46 +00001139audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001140{
François Gaffiec005e562018-11-06 15:04:49 +01001141 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001142
1143 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1144 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1145 // format, flags, etc. This may result in some discrepancy for functions that utilize
1146 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1147 // and AudioSystem::getOutputSamplingRate().
1148
François Gaffie11d30102018-11-02 16:09:09 +01001149 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001150 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1151 if (stream == AUDIO_STREAM_MUSIC &&
1152 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1153 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1154 }
1155 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001156
François Gaffie11d30102018-11-02 16:09:09 +01001157 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1158 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001159 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001160}
1161
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001162status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1163 const audio_attributes_t *srcAttr,
1164 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001165{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001166 if (srcAttr != NULL) {
1167 if (!isValidAttributes(srcAttr)) {
1168 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1169 __func__,
1170 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1171 srcAttr->tags);
1172 return BAD_VALUE;
1173 }
1174 *dstAttr = *srcAttr;
1175 } else {
1176 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1177 ALOGE("%s: invalid stream type", __func__);
1178 return BAD_VALUE;
1179 }
François Gaffiec005e562018-11-06 15:04:49 +01001180 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001181 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001182
1183 // Only honor audibility enforced when required. The client will be
1184 // forced to reconnect if the forced usage changes.
1185 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001186 dstAttr->flags = static_cast<audio_flags_mask_t>(
1187 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001188 }
1189
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001190 return NO_ERROR;
1191}
1192
Kevin Rocard153f92d2018-12-18 18:33:28 -08001193status_t AudioPolicyManager::getOutputForAttrInt(
1194 audio_attributes_t *resultAttr,
1195 audio_io_handle_t *output,
1196 audio_session_t session,
1197 const audio_attributes_t *attr,
1198 audio_stream_type_t *stream,
1199 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001200 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001201 audio_output_flags_t *flags,
1202 audio_port_handle_t *selectedDeviceId,
1203 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001204 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001205 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001206 bool *isSpatialized,
1207 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001208{
François Gaffiec005e562018-11-06 15:04:49 +01001209 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001210 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001211 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001212 const sp<DeviceDescriptor> requestedDevice =
1213 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1214
Eric Laurent8a1095a2019-11-08 14:44:16 -08001215 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001216 *isSpatialized = false;
1217
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001218 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1219 if (status != NO_ERROR) {
1220 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001221 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001222 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001223 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001224 }
François Gaffiec005e562018-11-06 15:04:49 +01001225 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001226
François Gaffiec005e562018-11-06 15:04:49 +01001227 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1228 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001229
Oscar Azucena873d10f2023-01-12 18:34:42 -08001230 bool usePrimaryOutputFromPolicyMixes = false;
1231
Kevin Rocard153f92d2018-12-18 18:33:28 -08001232 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1233 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1234 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001235 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001236 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1237 .channel_mask = config->channel_mask,
1238 .format = config->format,
1239 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001240 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001241 mAvailableOutputDevices, requestedDevice, primaryMix,
1242 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001243 if (status != OK) {
1244 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001245 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001246
Kevin Rocard153f92d2018-12-18 18:33:28 -08001247 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001248 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1249 && !audio_is_linear_pcm(config->format)) {
1250 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001251 return BAD_VALUE;
1252 }
1253 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001254 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001255 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1256 primaryMix->mDeviceAddress,
1257 AUDIO_FORMAT_DEFAULT);
1258 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001259 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001260 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1261 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001262 // if a direct output can be opened to deliver the track's multi-channel content to the
1263 // output rather than being downmixed by the primary output, then use this direct
1264 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1265 // mix.
1266 bool tryDirectForChannelMask = policyDesc != nullptr
1267 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1268 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001269 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001270 audio_io_handle_t newOutput;
1271 status = openDirectOutput(
1272 *stream, session, config,
1273 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001274 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001275 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001276 policyDesc = mOutputs.valueFor(newOutput);
1277 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001278 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001279 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001280 policyDesc = nullptr;
1281 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001282 }
1283 if (policyDesc != nullptr) {
1284 policyDesc->mPolicyMix = primaryMix;
1285 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001286 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1287 : AUDIO_PORT_HANDLE_NONE;
1288 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1289 // Remove direct flag as it is not on a direct output.
1290 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1291 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001292
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001293 ALOGV("getOutputForAttr() returns output %d", *output);
1294 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1295 *outputType = API_OUT_MIX_PLAYBACK;
1296 } else {
1297 *outputType = API_OUTPUT_LEGACY;
1298 }
1299 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001300 } else {
1301 if (policyMixDevice != nullptr) {
1302 ALOGE("%s, try to use primary mix but no output found", __func__);
1303 return INVALID_OPERATION;
1304 }
1305 // Fallback to default engine selection as the selected primary mix device is not
1306 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001307 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001308 }
François Gaffiec005e562018-11-06 15:04:49 +01001309 // Virtual sources must always be dynamicaly or explicitly routed
1310 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1311 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1312 return BAD_VALUE;
1313 }
1314 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1315 // in order to let the choice of the order to future vendor engine
1316 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001317
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001318 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001319 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001320 }
1321
Nadav Barb2f18162018-07-18 13:01:53 +03001322 // Set incall music only if device was explicitly set, and fallback to the device which is
1323 // chosen by the engine if not.
1324 // FIXME: provide a more generic approach which is not device specific and move this back
1325 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001326 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001327 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001328 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001329 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001330 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001331 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001332 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001333 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001334 }
1335 }
1336
François Gaffiec005e562018-11-06 15:04:49 +01001337 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1338 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1339 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001340
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001341 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001342 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001343 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001344 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001345 ALOGV("%s() Using MSD devices %s instead of devices %s",
1346 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001347 } else {
1348 *output = AUDIO_IO_HANDLE_NONE;
1349 }
1350 }
1351 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001352 sp<PreferredMixerAttributesInfo> info = nullptr;
1353 if (outputDevices.size() == 1) {
1354 info = getPreferredMixerAttributesInfo(
1355 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001356 mEngine->getProductStrategyForAttributes(*resultAttr),
1357 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001358 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1359 // and it is currently active.
1360 if (info != nullptr && info->getUid() != uid &&
1361 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1362 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001363 info = nullptr;
1364 }
1365 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001366 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001367 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001368 // The client will be active if the client is currently preferred mixer owner and the
1369 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001370 *isBitPerfect = (info != nullptr
1371 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001372 && info->getUid() == uid
1373 && *output != AUDIO_IO_HANDLE_NONE
1374 // When bit-perfect output is selected for the preferred mixer attributes owner,
1375 // only need to consider the config matches.
1376 && mOutputs.valueFor(*output)->isConfigurationMatched(
1377 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001378 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001379 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001380 AudioProfileVector profiles;
1381 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1382 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001383 const auto channels = profiles[0]->getChannels();
1384 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1385 config->channel_mask = *channels.begin();
1386 }
1387 const auto sampleRates = profiles[0]->getSampleRates();
1388 if (!sampleRates.empty() &&
1389 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1390 config->sample_rate = *sampleRates.begin();
1391 }
jiabinf1c73972022-04-14 16:28:52 -07001392 config->format = profiles[0]->getFormat();
1393 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001394 return INVALID_OPERATION;
1395 }
Paul McLeanaa981192015-03-21 09:55:15 -07001396
François Gaffiec005e562018-11-06 15:04:49 +01001397 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001398 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001399 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001400 *selectedDeviceId = outputDevice->getId();
1401 break;
1402 }
1403 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001404
Eric Laurent8a1095a2019-11-08 14:44:16 -08001405 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1406 *outputType = API_OUTPUT_TELEPHONY_TX;
1407 } else {
1408 *outputType = API_OUTPUT_LEGACY;
1409 }
1410
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001411 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1412
1413 return NO_ERROR;
1414}
1415
1416status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1417 audio_io_handle_t *output,
1418 audio_session_t session,
1419 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001420 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001421 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001422 audio_output_flags_t *flags,
1423 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001424 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001425 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001426 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001427 bool *isSpatialized,
1428 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001429{
1430 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1431 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1432 return INVALID_OPERATION;
1433 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001434 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001435 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001436 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001437 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001438 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001439 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001440 const sp<DeviceDescriptor> requestedDevice =
1441 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1442
1443 // Prevent from storing invalid requested device id in clients
1444 const audio_port_handle_t sanitizedRequestedPortId =
1445 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1446 *selectedDeviceId = sanitizedRequestedPortId;
1447
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001448 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001449 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001450 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1451 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001452 if (status != NO_ERROR) {
1453 return status;
1454 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001455 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001456 if (secondaryOutputs != nullptr) {
1457 for (auto &secondaryMix : secondaryMixes) {
1458 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1459 if (outputDesc != nullptr &&
1460 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1461 secondaryOutputs->push_back(outputDesc->mIoHandle);
1462 weakSecondaryOutputDescs.push_back(outputDesc);
1463 }
1464 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001465 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001466
Eric Laurent8fc147b2018-07-22 19:13:55 -07001467 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001468 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001469 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001470 };
jiabin4ef93452019-09-10 14:29:54 -07001471 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001472
Eric Laurentc209fe42020-06-05 18:11:23 -07001473 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001474 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001475 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001476 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001477 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001478 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001479 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001480 std::move(weakSecondaryOutputDescs),
1481 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001482 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001483
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001484 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1485 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001486
Eric Laurente83b55d2014-11-14 10:06:21 -08001487 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001488}
1489
Eric Laurentc529cf62020-04-17 18:19:10 -07001490status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1491 audio_session_t session,
1492 const audio_config_t *config,
1493 audio_output_flags_t flags,
1494 const DeviceVector &devices,
1495 audio_io_handle_t *output) {
1496
1497 *output = AUDIO_IO_HANDLE_NONE;
1498
1499 // skip direct output selection if the request can obviously be attached to a mixed output
1500 // and not explicitly requested
1501 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1502 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1503 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1504 return NAME_NOT_FOUND;
1505 }
1506
1507 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1508 // This prevents creating an offloaded track and tearing it down immediately after start
1509 // when audioflinger detects there is an active non offloadable effect.
1510 // FIXME: We should check the audio session here but we do not have it in this context.
1511 // This may prevent offloading in rare situations where effects are left active by apps
1512 // in the background.
1513 sp<IOProfile> profile;
1514 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1515 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1516 profile = getProfileForOutput(
1517 devices, config->sample_rate, config->format, config->channel_mask,
1518 flags, true /* directOnly */);
1519 }
1520
1521 if (profile == nullptr) {
1522 return NAME_NOT_FOUND;
1523 }
1524
1525 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1526 for (size_t i = 0; i < mOutputs.size(); i++) {
1527 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1528 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1529 // reuse direct output if currently open by the same client
1530 // and configured with same parameters
1531 if ((config->sample_rate == desc->getSamplingRate()) &&
1532 (config->format == desc->getFormat()) &&
1533 (config->channel_mask == desc->getChannelMask()) &&
1534 (session == desc->mDirectClientSession)) {
1535 desc->mDirectOpenCount++;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301536 ALOGI("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001537 mOutputs.keyAt(i), session);
1538 *output = mOutputs.keyAt(i);
1539 return NO_ERROR;
1540 }
1541 }
1542 }
1543
1544 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001545 if (!com::android::media::audioserver::direct_track_reprioritization()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301546 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1547 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001548 return NAME_NOT_FOUND;
1549 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1550 // MMAP gracefully handles lack of an exclusive track resource by mixing
1551 // above the audio framework. For AAudio to know that the limit is reached,
1552 // return an error.
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301553 ALOGW("%s profile %s can't open new mmap output maxOpenCount reached", __func__,
1554 profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001555 return NAME_NOT_FOUND;
1556 } else {
1557 // Close outputs on this profile, if available, to free resources for this request
1558 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1559 const auto desc = mOutputs.valueAt(i);
1560 if (desc->mProfile == profile) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301561 ALOGV("%s closeOutput %d to prioritize session %d on profile %s", __func__,
1562 desc->mIoHandle, session, profile->getName().c_str());
Atneya Nairb16666a2023-12-11 20:18:33 -08001563 closeOutput(desc->mIoHandle);
1564 }
1565 }
1566 }
1567 }
1568
1569 // Unable to close streams to find free resources for this request
1570 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05301571 ALOGW("%s profile %s can't open new output maxOpenCount reached", __func__,
1572 profile->getName().c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07001573 return NAME_NOT_FOUND;
1574 }
1575
Atneya Nairb16666a2023-12-11 20:18:33 -08001576 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001577
Michael Chan6fb34492020-12-08 15:44:49 +11001578 // An MSD patch may be using the only output stream that can service this request. Release
1579 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001580 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001581
Eric Laurentf1f22e72021-07-13 14:04:14 +02001582 status_t status =
1583 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001584
1585 // only accept an output with the requested parameters
1586 if (status != NO_ERROR ||
1587 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1588 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1589 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1590 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1591 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1592 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1593 config->channel_mask, outputDesc->getChannelMask());
1594 if (*output != AUDIO_IO_HANDLE_NONE) {
1595 outputDesc->close();
1596 }
1597 // fall back to mixer output if possible when the direct output could not be open
1598 if (audio_is_linear_pcm(config->format) &&
1599 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1600 return NAME_NOT_FOUND;
1601 }
1602 *output = AUDIO_IO_HANDLE_NONE;
1603 return BAD_VALUE;
1604 }
1605 outputDesc->mDirectOpenCount = 1;
1606 outputDesc->mDirectClientSession = session;
1607
1608 addOutput(*output, outputDesc);
1609 mPreviousOutputs = mOutputs;
1610 ALOGV("%s returns new direct output %d", __func__, *output);
1611 mpClientInterface->onAudioPortListUpdate();
1612 return NO_ERROR;
1613}
1614
François Gaffie11d30102018-11-02 16:09:09 +01001615audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1616 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001617 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001618 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001619 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001620 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001621 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001622 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001623 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001624{
Andy Hungc88b0642018-04-27 15:42:35 -07001625 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001626
jiabine375d412019-02-26 12:54:53 -08001627 // Discard haptic channel mask when forcing muting haptic channels.
1628 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001629 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1630 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001631
Eric Laurente552edb2014-03-10 17:42:56 -07001632 // open a direct output if required by specified parameters
1633 //force direct flag if offload flag is set: offloading implies a direct output stream
1634 // and all common behaviors are driven by checking only the direct flag
1635 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001636 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1637 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001638 }
Nadav Bar766fb022018-01-07 12:18:03 +02001639 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1640 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001641 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001642
1643 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1644
Eric Laurente83b55d2014-11-14 10:06:21 -08001645 // only allow deep buffering for music stream type
1646 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001647 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001648 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001649 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001650 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1651 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001652 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001653 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001654 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001655 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001656 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001657 audio_is_linear_pcm(config->format) &&
1658 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001659 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001660 AUDIO_OUTPUT_FLAG_DIRECT);
1661 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001662 }
Eric Laurente552edb2014-03-10 17:42:56 -07001663
Carter Hsua3abb402021-10-26 11:11:20 +08001664 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1665 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1666 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1667 }
1668
Eric Laurentf9230d52024-01-26 18:49:09 +01001669 // Use the spatializer output if the content can be spatialized, no preferred mixer
Shunkai Yao57b93392024-04-26 04:12:21 +00001670 // was specified and offload or direct playback is not explicitly requested, and there is no
1671 // haptic channel included in playback
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001672 *isSpatialized = false;
Shunkai Yao57b93392024-04-26 04:12:21 +00001673 if (mSpatializerOutput != nullptr &&
1674 canBeSpatializedInt(attr, config, devices.toTypeAddrVector()) &&
1675 prefMixerConfigInfo == nullptr &&
1676 ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0) &&
1677 checkHapticCompatibilityOnSpatializerOutput(config, session)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001678 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001679 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001680 }
1681
Eric Laurentc529cf62020-04-17 18:19:10 -07001682 audio_config_t directConfig = *config;
1683 directConfig.channel_mask = channelMask;
1684 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1685 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001686 return output;
1687 }
1688
Eric Laurent14cbfca2016-03-17 09:42:16 -07001689 // A request for HW A/V sync cannot fallback to a mixed output because time
1690 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001691 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001692 return AUDIO_IO_HANDLE_NONE;
1693 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001694 // A request for Tuner cannot fallback to a mixed output
1695 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1696 return AUDIO_IO_HANDLE_NONE;
1697 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001698
Eric Laurente552edb2014-03-10 17:42:56 -07001699 // ignoring channel mask due to downmix capability in mixer
1700
1701 // open a non direct output
1702
1703 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001704 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001705 // get which output is suitable for the specified stream. The actual
1706 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001707 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001708 if (prefMixerConfigInfo != nullptr) {
1709 for (audio_io_handle_t outputHandle : outputs) {
1710 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1711 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1712 output = outputHandle;
1713 break;
1714 }
1715 }
1716 if (output == AUDIO_IO_HANDLE_NONE) {
1717 // No output open with the preferred profile. Open a new one.
1718 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1719 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1720 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1721 config.format = prefMixerConfigInfo->getConfigBase().format;
1722 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1723 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1724 &config, prefMixerConfigInfo->getFlags());
1725 if (preferredOutput == nullptr) {
1726 ALOGE("%s failed to open output with preferred mixer config", __func__);
1727 } else {
1728 output = preferredOutput->mIoHandle;
1729 }
1730 }
1731 } else {
1732 // at this stage we should ignore the DIRECT flag as no direct output could be
1733 // found earlier
1734 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1735 output = selectOutput(
1736 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1737 }
Eric Laurente552edb2014-03-10 17:42:56 -07001738 }
François Gaffie11d30102018-11-02 16:09:09 +01001739 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001740 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001741 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001742
Eric Laurente552edb2014-03-10 17:42:56 -07001743 return output;
1744}
1745
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001746sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001747 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1748 mAvailableInputDevices);
1749 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1750}
1751
1752DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1753 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1754 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001755}
1756
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001757const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001758 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001759 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1760 if (msdModule != 0) {
1761 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1762 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1763 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1764 const struct audio_port_config *source = &patch->mPatch.sources[j];
1765 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1766 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001767 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001768 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001769 }
1770 }
1771 }
1772 return msdPatches;
1773}
1774
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001775bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1776 ssize_t index = mAudioPatches.indexOfKey(handle);
1777 if (index < 0) {
1778 return false;
1779 }
1780 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1781 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1782 if (msdModule == nullptr) {
1783 return false;
1784 }
1785 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1786 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1787 return true;
1788 }
1789 index = getMsdOutputPatches().indexOfKey(handle);
1790 if (index < 0) {
1791 return false;
1792 }
1793 return true;
1794}
1795
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001796status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1797 const InputProfileCollection &inputProfiles,
1798 const OutputProfileCollection &outputProfiles,
1799 const sp<DeviceDescriptor> &sourceDevice,
1800 const sp<DeviceDescriptor> &sinkDevice,
1801 AudioProfileVector& sourceProfiles,
1802 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001803 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001804 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001805 return NO_INIT;
1806 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001807 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001808 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001809 return NO_INIT;
1810 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001811 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001812 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1813 inProfile->supportsDevice(sourceDevice)) {
1814 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001815 }
1816 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001817 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001818 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001819 outProfile->supportsDevice(sinkDevice)) {
1820 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001821 }
1822 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001823 return NO_ERROR;
1824}
1825
1826status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1827 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1828 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1829{
Dean Wheatley16809da2022-12-09 14:55:46 +11001830 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1831 static const std::vector<audio_format_t> formatsOrder = {{
1832 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001833 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1834 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001835 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1836 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1837 // preferred).
1838 std::vector<audio_channel_mask_t> masks = {{
1839 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1840 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1841 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1842 // insert index masks (higher counts most preferred) as preferred over position masks
1843 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1844 masks.insert(
1845 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1846 }
1847 return masks;
1848 }();
1849
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001850 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001851 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1852 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001853 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001854 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1855 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001856 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001857 }
1858 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1859 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1860 sinkConfig->format = bestSinkConfig.format;
1861 // For encoded streams force direct flag to prevent downstream mixing.
1862 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1863 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001864 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1865 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001866 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001867 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1868 // raw and IEC61937 framed streams.
1869 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1870 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1871 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001872 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1873 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001874 sourceConfig->channel_mask =
1875 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1876 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1877 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001878 sourceConfig->format = bestSinkConfig.format;
1879 // Copy input stream directly without any processing (e.g. resampling).
1880 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1881 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1882 if (hwAvSync) {
1883 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1884 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1885 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1886 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1887 }
1888 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1889 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1890 sinkConfig->config_mask |= config_mask;
1891 sourceConfig->config_mask |= config_mask;
1892 return NO_ERROR;
1893}
1894
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001895PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1896 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001897{
1898 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001899 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1900 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1901 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1902 if (deviceModule == nullptr) {
1903 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1904 return patchBuilder;
1905 }
1906 const InputProfileCollection inputProfiles = msdIsSource ?
1907 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1908 const OutputProfileCollection outputProfiles = msdIsSource ?
1909 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1910
1911 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1912 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1913 device : getMsdAudioOutDevices().itemAt(0);
1914 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1915
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001916 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1917 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001918 AudioProfileVector sourceProfiles;
1919 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001920 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1921 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001922 for (auto hwAvSync : { true, false }) {
1923 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1924 sourceProfiles, sinkProfiles) != NO_ERROR) {
1925 continue;
1926 }
1927 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1928 &sinkConfig) == NO_ERROR) {
1929 // Found a matching config. Re-create PatchBuilder with this config.
1930 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1931 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001932 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001933 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001934 " supporting PCM format conversion.", __func__);
1935 return patchBuilder;
1936}
1937
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001938status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001939 DeviceVector devices;
1940 if (outputDevices != nullptr && outputDevices->size() > 0) {
1941 devices.add(*outputDevices);
1942 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001943 // Use media strategy for unspecified output device. This should only
1944 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1945 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001946 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001947 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001948 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001949 }
Michael Chan6fb34492020-12-08 15:44:49 +11001950 std::vector<PatchBuilder> patchesToCreate;
1951 for (auto i = 0u; i < devices.size(); ++i) {
1952 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001953 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001954 }
1955 // Retain only the MSD patches associated with outputDevices request.
1956 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001957 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001958 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1959 auto retainedPatch = false;
1960 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1961 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1962 patchesToRemove.removeItemsAt(i);
1963 retainedPatch = true;
1964 break;
1965 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001966 }
Michael Chan6fb34492020-12-08 15:44:49 +11001967 if (retainedPatch) {
1968 it = patchesToCreate.erase(it);
1969 continue;
1970 }
1971 ++it;
1972 }
1973 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1974 return NO_ERROR;
1975 }
1976 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1977 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001978 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001979 }
Michael Chan6fb34492020-12-08 15:44:49 +11001980 status_t status = NO_ERROR;
1981 for (const auto &p : patchesToCreate) {
1982 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1983 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1984 char message[256];
1985 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1986 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1987 currStatus == NO_ERROR ? "Success" : "Error",
1988 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1989 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1990 if (currStatus == NO_ERROR) {
1991 ALOGD("%s", message);
1992 } else {
1993 ALOGE("%s", message);
1994 if (status == NO_ERROR) {
1995 status = currStatus;
1996 }
1997 }
1998 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001999 return status;
2000}
2001
Dean Wheatley8bee85a2021-02-10 16:02:23 +11002002void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
2003 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11002004 for (size_t i = 0; i < msdPatches.size(); i++) {
2005 const auto& patch = msdPatches[i];
2006 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2007 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2008 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
2009 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
2010 releaseAudioPatch(patch->getHandle(), mUidCached);
2011 break;
2012 }
2013 }
2014 }
2015}
2016
Dorin Drimus94d94412022-02-02 09:05:02 +01002017bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07002018 DeviceVector devicesToCheck =
2019 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01002020 AudioPatchCollection msdPatches = getMsdOutputPatches();
2021 for (size_t i = 0; i < msdPatches.size(); i++) {
2022 const auto& patch = msdPatches[i];
2023 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
2024 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
2025 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
2026 const auto& foundDevice = devicesToCheck.getDevice(
2027 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
2028 if (foundDevice != nullptr) {
2029 devicesToCheck.remove(foundDevice);
2030 if (devicesToCheck.isEmpty()) {
2031 return true;
2032 }
2033 }
2034 }
2035 }
2036 }
2037 return false;
2038}
2039
Eric Laurente0720872014-03-11 09:30:41 -07002040audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002041 audio_output_flags_t flags,
2042 audio_format_t format,
2043 audio_channel_mask_t channelMask,
2044 uint32_t samplingRate,
2045 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002046{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002047 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2048 "%s called with format %#x", __func__, format);
2049
jiabinebb6af42020-06-09 17:31:17 -07002050 // Return the output that haptic-generating attached to when 1) session id is specified,
2051 // 2) haptic-generating effect exists for given session id and 3) the output that
2052 // haptic-generating effect attached to is in given outputs.
2053 if (sessionId != AUDIO_SESSION_NONE) {
2054 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2055 sessionId, FX_IID_HAPTICGENERATOR);
2056 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2057 return hapticGeneratingOutput;
2058 }
2059 }
2060
Eric Laurent16c66dd2019-05-01 17:54:10 -07002061 // Flags disqualifying an output: the match must happen before calling selectOutput()
2062 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2063 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2064
2065 // Flags expressing a functional request: must be honored in priority over
2066 // other criteria
2067 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2068 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002069 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2070 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002071 // Flags expressing a performance request: have lower priority than serving
2072 // requested sampling rate or channel mask
2073 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2074 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2075 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2076
2077 const audio_output_flags_t functionalFlags =
2078 (audio_output_flags_t)(flags & kFunctionalFlags);
2079 const audio_output_flags_t performanceFlags =
2080 (audio_output_flags_t)(flags & kPerformanceFlags);
2081
2082 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2083
Eric Laurente552edb2014-03-10 17:42:56 -07002084 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002085 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002086 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002087 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002088 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002089 // with tiebreak preferring the minimum number of extra functional flags
2090 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002091 // 3: the output supporting the exact channel mask
2092 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002093 // 5: the output with the highest sampling rate if the requested sample rate is
2094 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002095 // 6: the output with the highest number of requested performance flags
2096 // 7: the output with the bit depth the closest to the requested one
2097 // 8: the primary output
2098 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002099
Eric Laurent16c66dd2019-05-01 17:54:10 -07002100 // matching criteria values in priority order for best matching output so far
2101 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002102
Shunkai Yaocb21feb2024-07-17 00:34:54 +00002103 const bool hasOrphanHaptic = mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002104 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2105 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2106 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002107
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002108 for (audio_io_handle_t output : outputs) {
2109 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002110 // matching criteria values in priority order for current output
2111 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002112
Eric Laurent16c66dd2019-05-01 17:54:10 -07002113 if (outputDesc->isDuplicated()) {
2114 continue;
2115 }
2116 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2117 continue;
2118 }
Eric Laurent8838a382014-09-08 16:44:28 -07002119
Eric Laurent16c66dd2019-05-01 17:54:10 -07002120 // If haptic channel is specified, use the haptic output if present.
2121 // When using haptic output, same audio format and sample rate are required.
2122 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002123 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Shunkai Yao808da212024-04-05 22:50:56 +00002124 // skip if haptic channel specified but output does not support it, or output support haptic
2125 // but there is no haptic channel requested AND no orphan haptic effect exist
2126 if ((hapticChannelCount != 0 && outputHapticChannelCount == 0) ||
2127 (hapticChannelCount == 0 && outputHapticChannelCount != 0 && !hasOrphanHaptic)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002128 continue;
2129 }
Shunkai Yao808da212024-04-05 22:50:56 +00002130 // In the case of audio-coupled-haptic playback, there is no format conversion and
2131 // resampling in the framework, same format/channel/sampleRate for client and the output
2132 // thread is required. In the case of HapticGenerator effect, do not require format
2133 // matching.
2134 if ((outputHapticChannelCount >= hapticChannelCount && format == outputDesc->getFormat() &&
2135 samplingRate == outputDesc->getSamplingRate()) ||
Shunkai Yao57b93392024-04-26 04:12:21 +00002136 (outputHapticChannelCount != 0 && hasOrphanHaptic)) {
Shunkai Yao808da212024-04-05 22:50:56 +00002137 currentMatchCriteria[0] = outputHapticChannelCount;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002138 }
2139
2140 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002141 const int matchingFunctionalFlags =
2142 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2143 const int totalFunctionalFlags =
2144 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2145 // Prefer matching functional flags, but subtract unnecessary functional flags.
2146 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002147
2148 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002149 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2150 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002151 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2152 channelCount <= outputChannelCount) {
2153 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002154 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2155 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002156 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002157 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002158 currentMatchCriteria[3] = outputChannelCount;
2159 }
2160
2161 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002162 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
Richard Folke Tullberg67c12fe2024-02-21 12:00:06 +01002163 int diff; // avoid unsigned integer overflow.
2164 __builtin_sub_overflow(outputDesc->getSamplingRate(), samplingRate, &diff);
2165
2166 // prefer the closest output sampling rate greater than or equal to target
2167 // if none exists, prefer the closest output sampling rate less than target.
2168 //
2169 // criteria is offset to make non-negative.
2170 currentMatchCriteria[4] = diff >= 0 ? -diff + 200'000'000 : diff + 100'000'000;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002171 }
2172
2173 // performance flags match
2174 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2175
2176 // format match
2177 if (format != AUDIO_FORMAT_INVALID) {
2178 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002179 PolicyAudioPort::kFormatDistanceMax -
2180 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002181 }
2182
2183 // primary output match
2184 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2185
2186 // compare match criteria by priority then value
2187 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2188 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2189 bestMatchCriteria = currentMatchCriteria;
2190 bestOutput = output;
2191
2192 std::stringstream result;
2193 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2194 std::ostream_iterator<int>(result, " "));
2195 ALOGV("%s new bestOutput %d criteria %s",
2196 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002197 }
2198 }
2199
Eric Laurent16c66dd2019-05-01 17:54:10 -07002200 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002201}
2202
Eric Laurent8fc147b2018-07-22 19:13:55 -07002203status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002204{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002205 ALOGV("%s portId %d", __FUNCTION__, portId);
2206
2207 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2208 if (outputDesc == 0) {
2209 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002210 return BAD_VALUE;
2211 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002212 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002213
Eric Laurent8fc147b2018-07-22 19:13:55 -07002214 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002215 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002216
Eric Laurent733ce942017-12-07 12:18:25 -08002217 status_t status = outputDesc->start();
2218 if (status != NO_ERROR) {
2219 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002220 }
2221
Eric Laurent97ac8712018-07-27 18:59:02 -07002222 uint32_t delayMs;
2223 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002224
2225 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002226 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002227 if (status == DEAD_OBJECT) {
2228 sp<SwAudioOutputDescriptor> desc =
2229 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2230 if (desc == nullptr) {
2231 // This is not common, it may indicate something wrong with the HAL.
2232 ALOGE("%s unable to open output with default config", __func__);
2233 return status;
2234 }
2235 desc->mUsePreferredMixerAttributes = true;
2236 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002237 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002238 }
jiabina84c3d32022-12-02 18:59:55 +00002239
2240 // If the client is the first one active on preferred mixer parameters, reopen the output
2241 // if the current mixer parameters doesn't match the preferred one.
2242 if (outputDesc->devices().size() == 1) {
2243 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2244 outputDesc->devices()[0]->getId(), client->strategy());
2245 if (info != nullptr && info->getUid() == client->uid()) {
2246 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2247 info->getConfigBase(), info->getFlags())) {
2248 stopSource(outputDesc, client);
2249 outputDesc->stop();
2250 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2251 config.channel_mask = info->getConfigBase().channel_mask;
2252 config.sample_rate = info->getConfigBase().sample_rate;
2253 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002254 sp<SwAudioOutputDescriptor> desc =
2255 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2256 if (desc == nullptr) {
2257 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002258 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002259 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002260 // Intentionally return error to let the client side resending request for
2261 // creating and starting.
2262 return DEAD_OBJECT;
2263 }
2264 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002265 if (info->getActiveClientCount() == 1 &&
2266 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2267 // If it is first bit-perfect client, reroute all clients that will be routed to
2268 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2269 PortHandleVector clientsToInvalidate;
2270 for (size_t i = 0; i < mOutputs.size(); i++) {
2271 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002272 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002273 continue;
2274 }
2275 for (const auto& c : mOutputs[i]->getClientIterable()) {
2276 clientsToInvalidate.push_back(c->portId());
2277 }
2278 }
2279 if (!clientsToInvalidate.empty()) {
2280 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2281 __func__);
2282 mpClientInterface->invalidateTracks(clientsToInvalidate);
2283 }
2284 }
jiabina84c3d32022-12-02 18:59:55 +00002285 }
2286 }
2287
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002288 if (client->hasPreferredDevice()) {
2289 // playback activity with preferred device impacts routing occurred, inform upper layers
2290 mpClientInterface->onRoutingUpdated();
2291 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002292 if (delayMs != 0) {
2293 usleep(delayMs * 1000);
2294 }
2295
2296 return status;
2297}
2298
Eric Laurent96d1dda2022-03-14 17:14:19 +01002299bool AudioPolicyManager::isLeUnicastActive() const {
2300 if (isInCall()) {
2301 return true;
2302 }
2303 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2304}
2305
2306bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2307 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2308 return false;
2309 }
2310 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2311 ALOGV("%s active %d", __func__, active);
2312 return active;
2313}
2314
Eric Laurent97ac8712018-07-27 18:59:02 -07002315status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2316 const sp<TrackClientDescriptor>& client,
2317 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002318{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002319 // cannot start playback of STREAM_TTS if any other output is being used
2320 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002321
2322 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002323 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002324 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002325 auto clientStrategy = client->strategy();
2326 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002327 if (stream == AUDIO_STREAM_TTS) {
2328 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002329 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002330 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002331 return INVALID_OPERATION;
2332 } else {
2333 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2334 }
2335 } else {
2336 // some playback other than beacon starts
2337 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2338 }
2339
Eric Laurent77305a62016-07-25 16:39:22 -07002340 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002341 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002342 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002343
François Gaffie11d30102018-11-02 16:09:09 +01002344 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002345 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002346 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002347 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002348 audio_devices_t newDeviceType;
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00002349 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002350 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002351 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002352 } else {
2353 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002354 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002355 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2356 AUDIO_FORMAT_DEFAULT);
2357 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2358 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002359 }
2360
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002361 // requiresMuteCheck is false when we can bypass mute strategy.
2362 // It covers a common case when there is no materially active audio
2363 // and muting would result in unnecessary delay and dropped audio.
2364 const uint32_t outputLatencyMs = outputDesc->latency();
2365 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002366 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002367
Eric Laurente552edb2014-03-10 17:42:56 -07002368 // increment usage count for this stream on the requested output:
2369 // NOTE that the usage count is the same for duplicated output and hardware output which is
2370 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002371 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002372
2373 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002374 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002375 // Preferred device may be exclusive, use only if no other active clients on this output
2376 devices = DeviceVector(
2377 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2378 } else {
2379 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2380 }
François Gaffie11d30102018-11-02 16:09:09 +01002381 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002382 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002383 }
2384 }
Eric Laurente552edb2014-03-10 17:42:56 -07002385
François Gaffiec005e562018-11-06 15:04:49 +01002386 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002387 selectOutputForMusicEffects();
2388 }
2389
François Gaffie1c878552018-11-22 16:53:21 +01002390 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002391 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002392 if (devices.isEmpty()) {
2393 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002394 }
François Gaffiec005e562018-11-06 15:04:49 +01002395 bool shouldWait =
2396 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2397 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2398 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002399 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002400 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002401 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002402 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002403 // An output has a shared device if
2404 // - managed by the same hw module
2405 // - supports the currently selected device
2406 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002407 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002408
Eric Laurent77305a62016-07-25 16:39:22 -07002409 // force a device change if any other output is:
2410 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002411 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002412 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002413 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002414 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002415 // change the device currently selected by the other output.
2416 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002417 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002418 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002419 force = true;
2420 }
2421 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002422 // a notification so that audio focus effect can propagate, or that a mute/unmute
2423 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002424 const uint32_t latencyMs = desc->latency();
2425 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2426
2427 if (shouldWait && isActive && (waitMs < latencyMs)) {
2428 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002429 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002430
2431 // Require mute check if another output is on a shared device
2432 // and currently active to have proper drain and avoid pops.
2433 // Note restoring AudioTracks onto this output needs to invoke
2434 // a volume ramp if there is no mute.
2435 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002436 }
2437 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002438
jiabin3ff8d7d2022-12-13 06:27:44 +00002439 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2440 // If the output is open with preferred mixer attributes, but the routed device is
2441 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2442 // changed.
2443 return DEAD_OBJECT;
2444 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002445 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302446 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2447 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002448
Eric Laurente552edb2014-03-10 17:42:56 -07002449 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002450 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002451 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002452 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002453 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002454 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002455 outputDesc->useHwGain() /*force*/)) {
2456 // request AudioService to reinitialize the volume curves asynchronously
2457 ALOGE("checkAndSetVolume failed, requesting volume range init");
2458 mpClientInterface->onVolumeRangeInitRequest();
2459 };
Eric Laurente552edb2014-03-10 17:42:56 -07002460
2461 // update the outputs if starting an output with a stream that can affect notification
2462 // routing
2463 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002464
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002465 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002466 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002467 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002468 }
Eric Laurentdc462862016-07-19 12:29:53 -07002469
2470 if (waitMs > muteWaitMs) {
2471 *delayMs = waitMs - muteWaitMs;
2472 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002473
2474 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2475 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2476 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2477 // change occurs after the MixerThread starts and causes a stream volume
2478 // glitch.
2479 //
2480 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002481 }
Eric Laurentdc462862016-07-19 12:29:53 -07002482
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002483 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002484 mEngine->getForceUse(
2485 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002486 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002487 }
2488
Eric Laurent97ac8712018-07-27 18:59:02 -07002489 // Automatically enable the remote submix input when output is started on a re routing mix
2490 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002491 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2492 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002493 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2494 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2495 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002496 "remote-submix",
2497 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002498 }
2499
Eric Laurent96d1dda2022-03-14 17:14:19 +01002500 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2501
Eric Laurente552edb2014-03-10 17:42:56 -07002502 return NO_ERROR;
2503}
2504
Eric Laurent96d1dda2022-03-14 17:14:19 +01002505void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2506 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2507 bool isUnicastActive = isLeUnicastActive();
2508
2509 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002510 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002511 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2512 for (size_t i = 0; i < mOutputs.size(); i++) {
2513 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2514 if (desc != ignoredOutput && desc->isActive()
2515 && ((isUnicastActive &&
2516 !desc->devices().
2517 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2518 || (wasUnicastActive &&
2519 !desc->devices().getDevicesFromTypes(
2520 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2521 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2522 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002523 if (desc->mUsePreferredMixerAttributes && force) {
2524 // If the device is using preferred mixer attributes, the output need to reopen
2525 // with default configuration when the new selected devices are different from
2526 // current routing devices.
2527 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2528 continue;
2529 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302530 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002531 // re-apply device specific volume if not done by setOutputDevice()
2532 if (!force) {
2533 applyStreamVolumes(desc, newDevices.types(), delayMs);
2534 }
2535 }
2536 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002537 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002538 }
2539}
2540
Eric Laurent8fc147b2018-07-22 19:13:55 -07002541status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002542{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002543 ALOGV("%s portId %d", __FUNCTION__, portId);
2544
2545 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2546 if (outputDesc == 0) {
2547 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002548 return BAD_VALUE;
2549 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002550 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002551
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002552 if (client->hasPreferredDevice(true)) {
2553 // playback activity with preferred device impacts routing occurred, inform upper layers
2554 mpClientInterface->onRoutingUpdated();
2555 }
2556
Eric Laurent97ac8712018-07-27 18:59:02 -07002557 ALOGV("stopOutput() output %d, stream %d, session %d",
2558 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002559
Eric Laurent97ac8712018-07-27 18:59:02 -07002560 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002561
Eric Laurent733ce942017-12-07 12:18:25 -08002562 if (status == NO_ERROR ) {
2563 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002564 } else {
2565 return status;
2566 }
2567
2568 if (outputDesc->devices().size() == 1) {
2569 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2570 outputDesc->devices()[0]->getId(), client->strategy());
2571 if (info != nullptr && info->getUid() == client->uid()) {
2572 info->decreaseActiveClient();
2573 if (info->getActiveClientCount() == 0) {
2574 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2575 }
2576 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002577 }
2578 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002579}
2580
Eric Laurent97ac8712018-07-27 18:59:02 -07002581status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2582 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002583{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002584 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002585 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002586 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002587 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002588
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002589 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2590
François Gaffie1c878552018-11-22 16:53:21 +01002591 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2592 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002593 // Automatically disable the remote submix input when output is stopped on a
2594 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002595 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002596 if (isSingleDeviceType(
2597 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002598 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002599 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002600 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2601 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002602 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002603 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002604 }
2605 }
2606 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002607 if (client->hasPreferredDevice(true) &&
2608 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002609 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002610 forceDeviceUpdate = true;
2611 }
2612
Eric Laurente552edb2014-03-10 17:42:56 -07002613 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002614 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002615
Eric Laurente552edb2014-03-10 17:42:56 -07002616 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002617 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002618 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002619 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002620
2621 // If the routing does not change, if an output is routed on a device using HwGain
2622 // (aka setAudioPortConfig) and there are still active clients following different
2623 // volume group(s), force reapply volume
2624 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2625 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2626
Eric Laurente552edb2014-03-10 17:42:56 -07002627 // delay the device switch by twice the latency because stopOutput() is executed when
2628 // the track stop() command is received and at that time the audio track buffer can
2629 // still contain data that needs to be drained. The latency only covers the audio HAL
2630 // and kernel buffers. Also the latency does not always include additional delay in the
2631 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302632 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002633 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002634
2635 // force restoring the device selection on other active outputs if it differs from the
2636 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002637 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002638 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002639 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002640 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002641 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002642 desc->isActive() &&
2643 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002644 (newDevices != desc->devices())) {
2645 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2646 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002647
jiabin3ff8d7d2022-12-13 06:27:44 +00002648 if (desc->mUsePreferredMixerAttributes && force) {
2649 // If the device is using preferred mixer attributes, the output need to
2650 // reopen with default configuration when the new selected devices are
2651 // different from current routing devices.
2652 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2653 continue;
2654 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302655 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002656
Eric Laurent57de36c2016-09-28 16:59:11 -07002657 // re-apply device specific volume if not done by setOutputDevice()
2658 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002659 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002660 }
Eric Laurente552edb2014-03-10 17:42:56 -07002661 }
2662 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002663 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002664 // update the outputs if stopping one with a stream that can affect notification routing
2665 handleNotificationRoutingForStream(stream);
2666 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002667
2668 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2669 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002670 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002671 }
2672
François Gaffiec005e562018-11-06 15:04:49 +01002673 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002674 selectOutputForMusicEffects();
2675 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002676
2677 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2678
Eric Laurente552edb2014-03-10 17:42:56 -07002679 return NO_ERROR;
2680 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002681 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002682 return INVALID_OPERATION;
2683 }
2684}
2685
jiabinbce0c1d2020-10-05 11:20:18 -07002686bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002687{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002688 ALOGV("%s portId %d", __FUNCTION__, portId);
2689
2690 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2691 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002692 // If an output descriptor is closed due to a device routing change,
2693 // then there are race conditions with releaseOutput from tracks
2694 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2695 // destroyed shortly thereafter.
2696 //
2697 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002698 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002699 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002700 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002701
2702 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002703
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302704 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2705 if (outputDesc->isClientActive(client)) {
2706 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2707 stopOutput(portId);
2708 }
2709
Eric Laurent8fc147b2018-07-22 19:13:55 -07002710 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2711 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002712 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002713 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002714 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002715 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002716 if (--outputDesc->mDirectOpenCount == 0) {
2717 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002718 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002719 }
2720 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302721
Andy Hung39efb7a2018-09-26 15:39:28 -07002722 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002723 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2724 // The output is pending reopened to query dynamic profiles and
2725 // there is no active clients
2726 closeOutput(outputDesc->mIoHandle);
2727 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2728 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2729 if (newOutputDesc == nullptr) {
2730 ALOGE("%s failed to open output", __func__);
2731 }
2732 return true;
2733 }
2734 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002735}
2736
Eric Laurentcaf7f482014-11-25 17:50:47 -08002737status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2738 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002739 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002740 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002741 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002742 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002743 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002744 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002745 input_type_t *inputType,
2746 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002747{
François Gaffiec005e562018-11-06 15:04:49 +01002748 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002749 "flags %#x attributes=%s requested device ID %d",
2750 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2751 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002752
Eric Laurentad2e7b92017-09-14 20:06:42 -07002753 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002754 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002755 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002756 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002757 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002758 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002759 sp<RecordClientDescriptor> clientDesc;
2760 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002761 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002762 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002763
2764 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2765 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2766 return INVALID_OPERATION;
2767 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002768
Francois Gaffie716e1432019-01-14 16:58:59 +01002769 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2770 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002771 }
2772
Paul McLean466dc8e2015-04-17 13:15:36 -06002773 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002774 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002775 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002776
Eric Laurentad2e7b92017-09-14 20:06:42 -07002777 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2778 // possible
2779 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2780 *input != AUDIO_IO_HANDLE_NONE) {
2781 ssize_t index = mInputs.indexOfKey(*input);
2782 if (index < 0) {
2783 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2784 status = BAD_VALUE;
2785 goto error;
2786 }
2787 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002788 RecordClientVector clients = inputDesc->getClientsForSession(session);
2789 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002790 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2791 status = BAD_VALUE;
2792 goto error;
2793 }
2794 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2795 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002796 // corresponds to a new client and is only permitted from the same UID.
2797 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002798 if (clients.size() > 1) {
2799 for (const auto& client : clients) {
2800 // The client map is ordered by key values (portId) and portIds are allocated
2801 // incrementaly. So the first client in this list is the one opened by audio flinger
2802 // when the mmap stream is created and should be ignored as it does not correspond
2803 // to an actual client
2804 if (client == *clients.cbegin()) {
2805 continue;
2806 }
2807 if (uid != client->uid() && !client->isSilenced()) {
2808 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2809 uid, client->portId(), client->uid());
2810 status = INVALID_OPERATION;
2811 goto error;
2812 }
Eric Laurent331679c2018-04-16 17:03:16 -07002813 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002814 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002815 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002816 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002817
Eric Laurentfecbceb2021-02-09 14:46:43 +01002818 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002819 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002820 }
2821
2822 *input = AUDIO_IO_HANDLE_NONE;
2823 *inputType = API_INPUT_INVALID;
2824
Francois Gaffie716e1432019-01-14 16:58:59 +01002825 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002826 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002827 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002828 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002829 ALOGW("%s could not find input mix for attr %s",
2830 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002831 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002832 }
jiabinc1de2df2019-05-07 14:26:40 -07002833 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2834 String8(attr->tags + strlen("addr=")),
2835 AUDIO_FORMAT_DEFAULT);
2836 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002837 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002838 __func__, attributes.source, attributes.tags);
2839 status = BAD_VALUE;
2840 goto error;
2841 }
2842
Kevin Rocard25f9b052019-02-27 15:08:54 -08002843 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2844 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2845 } else {
2846 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2847 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002848 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002849 if (explicitRoutingDevice != nullptr) {
2850 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002851 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002852 // Prevent from storing invalid requested device id in clients
2853 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002854 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002855 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2856 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002857 }
François Gaffie11d30102018-11-02 16:09:09 +01002858 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002859 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002860 status = BAD_VALUE;
2861 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002862 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002863 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2864 *inputType = API_INPUT_MIX_CAPTURE;
2865 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002866 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2867 // there is an external policy, but this input is attached to a mix of recorders,
2868 // meaning it receives audio injected into the framework, so the recorder doesn't
2869 // know about it and is therefore considered "legacy"
2870 *inputType = API_INPUT_LEGACY;
2871 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002872 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002873 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002874 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002875 } else {
2876 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002877 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002878
Eric Laurent599c7582015-12-07 18:05:55 -08002879 }
2880
François Gaffiec005e562018-11-06 15:04:49 +01002881 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002882 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002883 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002884 AudioProfileVector profiles;
2885 status_t ret = getProfilesForDevices(
2886 DeviceVector(device), profiles, flags, true /*isInput*/);
2887 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002888 const auto channels = profiles[0]->getChannels();
2889 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2890 config->channel_mask = *channels.begin();
2891 }
2892 const auto sampleRates = profiles[0]->getSampleRates();
2893 if (!sampleRates.empty() &&
2894 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2895 config->sample_rate = *sampleRates.begin();
2896 }
jiabinf1c73972022-04-14 16:28:52 -07002897 config->format = profiles[0]->getFormat();
2898 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002899 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002900 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002901
Eric Laurent8f42ea12018-08-08 09:08:25 -07002902exit:
2903
François Gaffiec005e562018-11-06 15:04:49 +01002904 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2905 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002906
Francois Gaffie716e1432019-01-14 16:58:59 +01002907 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002908 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002909 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002910
Mikhail Naganov2996f672019-04-18 12:29:59 -07002911 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002912 requestedDeviceId, attributes.source, flags,
2913 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002914 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002915 // Move (if found) effect for the client session to its input
2916 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002917 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002918
2919 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2920 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002921
Eric Laurent599c7582015-12-07 18:05:55 -08002922 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002923
2924error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002925 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002926}
2927
2928
François Gaffie11d30102018-11-02 16:09:09 +01002929audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002930 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002931 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002932 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002933 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002934 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002935{
2936 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002937 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002938 bool isSoundTrigger = false;
2939
François Gaffiec005e562018-11-06 15:04:49 +01002940 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002941 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2942 if (index >= 0) {
2943 input = mSoundTriggerSessions.valueFor(session);
2944 isSoundTrigger = true;
2945 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2946 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2947 } else {
2948 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002949 }
François Gaffiec005e562018-11-06 15:04:49 +01002950 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002951 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002952 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002953 }
2954
Carter Hsua3abb402021-10-26 11:11:20 +08002955 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2956 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2957 }
2958
Eric Laurentfe231122017-11-17 17:48:06 -08002959 // sampling rate and flags may be updated by getInputProfile
2960 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2961 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002962 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002963 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002964 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002965 // find a compatible input profile (not necessarily identical in parameters)
2966 sp<IOProfile> profile = getInputProfile(
2967 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2968 if (profile == nullptr) {
2969 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002970 }
jiabin2fd710d2022-05-02 23:20:22 +00002971
Glenn Kasten05ddca52016-02-11 08:17:12 -08002972 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002973 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002974 if (samplingRate == 0) {
2975 samplingRate = profileSamplingRate;
2976 }
Eric Laurente552edb2014-03-10 17:42:56 -07002977
Eric Laurent322b4d22015-04-03 15:57:54 -07002978 if (profile->getModuleHandle() == 0) {
2979 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002980 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002981 }
2982
Eric Laurentec376dc2021-04-08 20:41:22 +02002983 // Reuse an already opened input if a client with the same session ID already exists
2984 // on that input
2985 for (size_t i = 0; i < mInputs.size(); i++) {
2986 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2987 if (desc->mProfile != profile) {
2988 continue;
2989 }
2990 RecordClientVector clients = desc->clientsList();
2991 for (const auto &client : clients) {
2992 if (session == client->session()) {
2993 return desc->mIoHandle;
2994 }
2995 }
2996 }
2997
Eric Laurent3974e3b2017-12-07 17:58:43 -08002998 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002999 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003000 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08003001 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08003002 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08003003 continue;
3004 }
3005 // if sound trigger, reuse input if used by other sound trigger on same session
3006 // else
3007 // reuse input if active client app is not in IDLE state
3008 //
3009 RecordClientVector clients = desc->clientsList();
3010 bool doClose = false;
3011 for (const auto& client : clients) {
3012 if (isSoundTrigger != client->isSoundTrigger()) {
3013 continue;
3014 }
3015 if (client->isSoundTrigger()) {
3016 if (session == client->session()) {
3017 return desc->mIoHandle;
3018 }
3019 continue;
3020 }
3021 if (client->active() && client->appState() != APP_STATE_IDLE) {
3022 return desc->mIoHandle;
3023 }
3024 doClose = true;
3025 }
3026 if (doClose) {
3027 closeInput(desc->mIoHandle);
3028 } else {
3029 i++;
3030 }
3031 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003032 }
3033
Eric Laurentfe231122017-11-17 17:48:06 -08003034 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07003035
Eric Laurentfe231122017-11-17 17:48:06 -08003036 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
3037 lConfig.sample_rate = profileSamplingRate;
3038 lConfig.channel_mask = profileChannelMask;
3039 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07003040
François Gaffie11d30102018-11-02 16:09:09 +01003041 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07003042
3043 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08003044 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08003045 (profileSamplingRate != lConfig.sample_rate) ||
3046 !audio_formats_match(profileFormat, lConfig.format) ||
3047 (profileChannelMask != lConfig.channel_mask)) {
3048 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08003049 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08003050 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003051 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003052 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003053 }
Eric Laurent599c7582015-12-07 18:05:55 -08003054 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003055 }
3056
Eric Laurentc722f302014-12-10 11:21:49 -08003057 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003058
Eric Laurent599c7582015-12-07 18:05:55 -08003059 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003060 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003061
Eric Laurent599c7582015-12-07 18:05:55 -08003062 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003063}
3064
Eric Laurent4eb58f12018-12-07 16:41:02 -08003065status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003066{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003067 ALOGV("%s portId %d", __FUNCTION__, portId);
3068
3069 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3070 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003071 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003072 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003073 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003074 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003075 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003076 if (client->active()) {
3077 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3078 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003079 }
3080
Eric Laurent8f42ea12018-08-08 09:08:25 -07003081 audio_session_t session = client->session();
3082
Eric Laurent4eb58f12018-12-07 16:41:02 -08003083 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003084
Eric Laurent4eb58f12018-12-07 16:41:02 -08003085 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003086
Eric Laurent4eb58f12018-12-07 16:41:02 -08003087 status_t status = inputDesc->start();
3088 if (status != NO_ERROR) {
3089 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003090 }
Eric Laurente552edb2014-03-10 17:42:56 -07003091
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003092 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003093 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003094 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003095
Eric Laurent8f42ea12018-08-08 09:08:25 -07003096 // indicate active capture to sound trigger service if starting capture from a mic on
3097 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003098 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003099 if (device != nullptr) {
3100 status = setInputDevice(input, device, true /* force */);
3101 } else {
3102 ALOGW("%s no new input device can be found for descriptor %d",
3103 __FUNCTION__, inputDesc->getId());
3104 status = BAD_VALUE;
3105 }
Eric Laurente552edb2014-03-10 17:42:56 -07003106
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003107 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003108 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003109 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003110 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003111 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3112 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003113 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003114 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003115
François Gaffie11d30102018-11-02 16:09:09 +01003116 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3117 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003118 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003119 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003120 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003121
Eric Laurent8f42ea12018-08-08 09:08:25 -07003122 // automatically enable the remote submix output when input is started if not
3123 // used by a policy mix of type MIX_TYPE_RECORDERS
3124 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003125 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003126 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003127 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003128 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003129 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3130 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003131 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003132 if (address != "") {
3133 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3134 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003135 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003136 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003137 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003138 } else if (status != NO_ERROR) {
3139 // Restore client activity state.
3140 inputDesc->setClientActive(client, false);
3141 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003142 }
3143
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003144 ALOGV("%s input %d source = %d status = %d exit",
3145 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003146
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003147 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003148}
3149
Eric Laurent8fc147b2018-07-22 19:13:55 -07003150status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003151{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003152 ALOGV("%s portId %d", __FUNCTION__, portId);
3153
3154 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3155 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003156 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003157 return BAD_VALUE;
3158 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003159 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003160 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003161 if (!client->active()) {
3162 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003163 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003164 }
Carter Hsue6139d52021-07-08 10:30:20 +08003165 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003166 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003167
Eric Laurent8f42ea12018-08-08 09:08:25 -07003168 inputDesc->stop();
3169 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003170 auto current_source = inputDesc->source();
3171 setInputDevice(input, getNewInputDevice(inputDesc),
3172 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003173 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003174 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003175 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003176 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003177 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3178 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003179 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003180 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003181
3182 // automatically disable the remote submix output when input is stopped if not
3183 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003184 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003185 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003186 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003187 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003188 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3189 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003190 }
3191 if (address != "") {
3192 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3193 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003194 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003195 }
3196 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003197 resetInputDevice(input);
3198
3199 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3200 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003201 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3202 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003203 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003204 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003205 }
3206 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003207 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003208 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003209}
3210
Eric Laurent8fc147b2018-07-22 19:13:55 -07003211void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003212{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003213 ALOGV("%s portId %d", __FUNCTION__, portId);
3214
3215 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3216 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003217 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003218 return;
3219 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003220 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003221 audio_io_handle_t input = inputDesc->mIoHandle;
3222
Eric Laurent8f42ea12018-08-08 09:08:25 -07003223 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003224
Andy Hung39efb7a2018-09-26 15:39:28 -07003225 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003226 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003227 if (inputDesc->getClientCount() > 0) {
3228 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003229 return;
3230 }
3231
Eric Laurent05b90f82014-08-27 15:32:29 -07003232 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003233 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003234 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003235}
3236
Eric Laurent8f42ea12018-08-08 09:08:25 -07003237void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003238{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003239 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003240
3241 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003242 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003243 }
3244}
3245
Eric Laurent8f42ea12018-08-08 09:08:25 -07003246void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3247{
3248 stopInput(portId);
3249 releaseInput(portId);
3250}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003251
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003252bool AudioPolicyManager::checkCloseInput(const sp<AudioInputDescriptor>& input) {
3253 if (input->clientsList().size() == 0
3254 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
3255 return true;
3256 }
3257 for (const auto& client : input->clientsList()) {
3258 sp<DeviceDescriptor> device =
3259 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3260 client->session());
3261 if (!input->supportedDevices().contains(device)) {
3262 return true;
3263 }
3264 }
3265 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3266 return false;
3267}
3268
Eric Laurent0dd51852019-04-19 18:18:58 -07003269void AudioPolicyManager::checkCloseInputs() {
3270 // After connecting or disconnecting an input device, close input if:
3271 // - it has no client (was just opened to check profile) OR
3272 // - none of its supported devices are connected anymore OR
3273 // - one of its clients cannot be routed to one of its supported
3274 // devices anymore. Otherwise update device selection
3275 std::vector<audio_io_handle_t> inputsToClose;
3276 for (size_t i = 0; i < mInputs.size(); i++) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07003277 if (checkCloseInput(mInputs.valueAt(i))) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003278 inputsToClose.push_back(mInputs.keyAt(i));
Eric Laurent0dd51852019-04-19 18:18:58 -07003279 }
3280 }
Eric Laurent0dd51852019-04-19 18:18:58 -07003281 for (const audio_io_handle_t handle : inputsToClose) {
3282 ALOGV("%s closing input %d", __func__, handle);
3283 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003284 }
Eric Laurentd4692962014-05-05 18:13:44 -07003285}
3286
François Gaffie251c7f02018-11-07 10:41:08 +01003287void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003288{
3289 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003290 if (indexMin < 0 || indexMax < 0) {
3291 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3292 return;
3293 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003294 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003295
3296 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003297 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3298 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003299 continue;
3300 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003301 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003302 }
Eric Laurente552edb2014-03-10 17:42:56 -07003303}
3304
Eric Laurente0720872014-03-11 09:30:41 -07003305status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003306 int index,
3307 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003308{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003309 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003310 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3311 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3312 return NO_ERROR;
3313 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303314 ALOGV("%s: stream %s attributes=%s, index %d , device 0x%X", __func__,
3315 toString(stream).c_str(), toString(attributes).c_str(), index, device);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003316 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003317}
3318
Eric Laurente0720872014-03-11 09:30:41 -07003319status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003320 int *index,
3321 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003322{
François Gaffiec005e562018-11-06 15:04:49 +01003323 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3324 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003325 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003326 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003327 deviceTypes = mEngine->getOutputDevicesForStream(
3328 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003329 }
jiabin9a3361e2019-10-01 09:38:30 -07003330 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003331}
3332
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003333status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003334 int index,
3335 audio_devices_t device)
3336{
3337 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003338 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3339 if (group == VOLUME_GROUP_NONE) {
3340 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003341 return BAD_VALUE;
3342 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003343 ALOGV("%s: group %d matching with %s index %d",
3344 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003345 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003346 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003347 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003348 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3349 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3350 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3351 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003352 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3353
3354 status = setVolumeCurveIndex(index, device, curves);
3355 if (status != NO_ERROR) {
3356 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3357 return status;
3358 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003359
jiabin9a3361e2019-10-01 09:38:30 -07003360 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003361 auto curCurvAttrs = curves.getAttributes();
3362 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3363 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003364 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003365 } else if (!curves.getStreamTypes().empty()) {
3366 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003367 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003368 } else {
3369 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3370 return BAD_VALUE;
3371 }
jiabin9a3361e2019-10-01 09:38:30 -07003372 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3373 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003374
François Gaffiecfe17322018-11-07 13:41:29 +01003375 // update volume on all outputs and streams matching the following:
3376 // - The requested stream (or a stream matching for volume control) is active on the output
3377 // - The device (or devices) selected by the engine for this stream includes
3378 // the requested device
3379 // - For non default requested device, currently selected device on the output is either the
3380 // requested device or one of the devices selected by the engine for this stream
3381 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3382 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003383 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003384 for (size_t i = 0; i < mOutputs.size(); i++) {
3385 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003386 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003387
jiabin9a3361e2019-10-01 09:38:30 -07003388 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3389 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003390 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003391
3392 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003393 continue;
3394 }
3395 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3396 curDevices.find(device) == curDevices.end()) {
3397 continue;
3398 }
3399 bool applyVolume = false;
3400 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3401 curSrcDevices.insert(device);
3402 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003403 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3404 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003405 } else {
3406 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3407 }
3408 if (!applyVolume) {
3409 continue; // next output
3410 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003411 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3412 // If a higher priority strategy is active, and the output is routed to a device with a
3413 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003414 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003415 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003416 // If the volume source is active with higher priority source, ensure at least Sw Muted
3417 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003418 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3419 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3420 false /*preferredDevice*/);
3421 if (activeClients.empty()) {
3422 continue;
3423 }
3424 bool isPreempted = false;
3425 bool isHigherPriority = productStrategy < strategy;
3426 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003427 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003428 ALOGV("%s: Strategy=%d (\nrequester:\n"
3429 " group %d, volumeGroup=%d attributes=%s)\n"
3430 " higher priority source active:\n"
3431 " volumeGroup=%d attributes=%s) \n"
3432 " on output %zu, bailing out", __func__, productStrategy,
3433 group, group, toString(attributes).c_str(),
3434 client->volumeSource(), toString(client->attributes()).c_str(), i);
3435 applyVolume = false;
3436 isPreempted = true;
3437 break;
3438 }
3439 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003440 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003441 applyVolume = true;
3442 }
3443 }
3444 if (isPreempted || applyVolume) {
3445 break;
3446 }
3447 }
3448 if (!applyVolume) {
3449 continue; // next output
3450 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003451 }
François Gaffieed91f582020-01-31 10:35:37 +01003452 //FIXME: workaround for truncated touch sounds
3453 // delayed volume change for system stream to be removed when the problem is
3454 // handled by system UI
3455 status_t volStatus = checkAndSetVolume(
3456 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003457 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003458 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3459 if (volStatus != NO_ERROR) {
3460 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003461 }
3462 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00003463
3464 // update voice volume if the an active call route exists
3465 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3466 && (curSrcDevices.find(
3467 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3468 != curSrcDevices.end())) {
3469 bool isVoiceVolSrc;
3470 bool isBtScoVolSrc;
3471 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3472 isVoiceVolSrc, isBtScoVolSrc, __func__)
3473 && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08003474 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
3475 !audio_is_ble_out_device(mCallRxSourceClient->sinkDevice()->type());
3476 setVoiceVolume(index, curves, voiceVolumeManagedByHost, 0);
Eric Laurent5baf07c2024-01-11 16:57:27 +00003477 }
3478 }
3479
François Gaffiecfe17322018-11-07 13:41:29 +01003480 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3481 return status;
3482}
3483
François Gaffieaaac0fd2018-11-22 17:56:39 +01003484status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003485 audio_devices_t device,
3486 IVolumeCurves &volumeCurves)
3487{
3488 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3489 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003490 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3491 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003492 (index > volumeCurves.getVolumeIndexMax())) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05303493 ALOGE("%s: wrong index %d min=%d max=%d, device 0x%X", __FUNCTION__, index,
3494 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax(), device);
François Gaffiecfe17322018-11-07 13:41:29 +01003495 return BAD_VALUE;
3496 }
3497 if (!audio_is_output_device(device)) {
3498 return BAD_VALUE;
3499 }
3500
3501 // Force max volume if stream cannot be muted
3502 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3503
François Gaffieaaac0fd2018-11-22 17:56:39 +01003504 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003505 volumeCurves.addCurrentVolumeIndex(device, index);
3506 return NO_ERROR;
3507}
3508
3509status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3510 int &index,
3511 audio_devices_t device)
3512{
3513 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3514 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003515 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003516 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003517 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003518 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003519 }
jiabin9a3361e2019-10-01 09:38:30 -07003520 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003521}
3522
3523status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3524 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003525 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003526{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003527 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003528 return BAD_VALUE;
3529 }
jiabin9a3361e2019-10-01 09:38:30 -07003530 index = curves.getVolumeIndex(deviceTypes);
3531 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003532 return NO_ERROR;
3533}
3534
3535status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3536 int &index)
3537{
3538 index = getVolumeCurves(attr).getVolumeIndexMin();
3539 return NO_ERROR;
3540}
3541
3542status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3543 int &index)
3544{
3545 index = getVolumeCurves(attr).getVolumeIndexMax();
3546 return NO_ERROR;
3547}
3548
Eric Laurent36829f92017-04-07 19:04:42 -07003549audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003550{
3551 // select one output among several suitable for global effects.
3552 // The priority is as follows:
3553 // 1: An offloaded output. If the effect ends up not being offloadable,
3554 // AudioFlinger will invalidate the track and the offloaded output
3555 // will be closed causing the effect to be moved to a PCM output.
3556 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003557 // 3: The primary output
3558 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003559
François Gaffiec005e562018-11-06 15:04:49 +01003560 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3561 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003562 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003563
Eric Laurent36829f92017-04-07 19:04:42 -07003564 if (outputs.size() == 0) {
3565 return AUDIO_IO_HANDLE_NONE;
3566 }
Eric Laurente552edb2014-03-10 17:42:56 -07003567
Eric Laurent36829f92017-04-07 19:04:42 -07003568 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3569 bool activeOnly = true;
3570
3571 while (output == AUDIO_IO_HANDLE_NONE) {
3572 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3573 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3574 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3575
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003576 for (audio_io_handle_t output : outputs) {
3577 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003578 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003579 continue;
3580 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003581 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3582 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003583 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003584 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003585 }
3586 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003587 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003588 }
3589 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003590 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003591 }
3592 }
3593 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3594 output = outputOffloaded;
3595 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3596 output = outputDeepBuffer;
3597 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3598 output = outputPrimary;
3599 } else {
3600 output = outputs[0];
3601 }
3602 activeOnly = false;
3603 }
3604
3605 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003606 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3607 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003608 mMusicEffectOutput = output;
3609 }
3610
3611 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003612 return output;
3613}
3614
Eric Laurent36829f92017-04-07 19:04:42 -07003615audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3616{
3617 return selectOutputForMusicEffects();
3618}
3619
Eric Laurente0720872014-03-11 09:30:41 -07003620status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003621 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003622 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003623 int session,
3624 int id)
3625{
Shunkai Yao2fa06c12024-03-19 04:31:47 +00003626 if (session != AUDIO_SESSION_DEVICE && io != AUDIO_IO_HANDLE_NONE) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003627 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003628 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003629 index = mInputs.indexOfKey(io);
3630 if (index < 0) {
3631 ALOGW("registerEffect() unknown io %d", io);
3632 return INVALID_OPERATION;
3633 }
Eric Laurente552edb2014-03-10 17:42:56 -07003634 }
3635 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003636 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3637 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3638 || strategy == PRODUCT_STRATEGY_NONE));
3639 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003640}
3641
Eric Laurentc241b0d2018-11-28 09:08:49 -08003642status_t AudioPolicyManager::unregisterEffect(int id)
3643{
3644 if (mEffects.getEffect(id) == nullptr) {
3645 return INVALID_OPERATION;
3646 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003647 if (mEffects.isEffectEnabled(id)) {
3648 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3649 setEffectEnabled(id, false);
3650 }
3651 return mEffects.unregisterEffect(id);
3652}
3653
3654status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3655{
3656 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3657 if (effect == nullptr) {
3658 return INVALID_OPERATION;
3659 }
3660
3661 status_t status = mEffects.setEffectEnabled(id, enabled);
3662 if (status == NO_ERROR) {
3663 mInputs.trackEffectEnabled(effect, enabled);
3664 }
3665 return status;
3666}
3667
Eric Laurent6c796322019-04-09 14:13:17 -07003668
3669status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3670{
3671 mEffects.moveEffects(ids, io);
3672 return NO_ERROR;
3673}
3674
Eric Laurentc75307b2015-03-17 15:29:32 -07003675bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3676{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003677 auto vs = toVolumeSource(stream, false);
3678 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003679}
3680
3681bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3682{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003683 auto vs = toVolumeSource(stream, false);
3684 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003685}
3686
Eric Laurente0720872014-03-11 09:30:41 -07003687bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003688{
3689 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003690 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003691 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003692 return true;
3693 }
3694 }
3695 return false;
3696}
3697
Eric Laurent275e8e92014-11-30 15:14:47 -08003698// Register a list of custom mixes with their attributes and format.
3699// When a mix is registered, corresponding input and output profiles are
3700// added to the remote submix hw module. The profile contains only the
3701// parameters (sampling rate, format...) specified by the mix.
3702// The corresponding input remote submix device is also connected.
3703//
3704// When a remote submix device is connected, the address is checked to select the
3705// appropriate profile and the corresponding input or output stream is opened.
3706//
3707// When capture starts, getInputForAttr() will:
3708// - 1 look for a mix matching the address passed in attribtutes tags if any
3709// - 2 if none found, getDeviceForInputSource() will:
3710// - 2.1 look for a mix matching the attributes source
3711// - 2.2 if none found, default to device selection by policy rules
3712// At this time, the corresponding output remote submix device is also connected
3713// and active playback use cases can be transferred to this mix if needed when reconnecting
3714// after AudioTracks are invalidated
3715//
3716// When playback starts, getOutputForAttr() will:
3717// - 1 look for a mix matching the address passed in attribtutes tags if any
3718// - 2 if none found, look for a mix matching the attributes usage
3719// - 3 if none found, default to device and output selection by policy rules.
3720
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003721status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003722{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003723 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3724 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003725 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003726 sp<HwModule> rSubmixModule;
Marvin Raminabd9b892023-11-17 16:36:27 +01003727 Vector<AudioMix> registeredMixes;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003728 // examine each mix's route type
3729 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003730 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003731 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3732 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3733 ALOGE("Unsupported Policy Mix %zu of %zu: "
3734 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3735 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003736 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003737 break;
3738 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003739 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3740 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003741 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003742 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3743 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003744 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003745 rSubmixModule = mHwModules.getModuleFromName(
3746 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3747 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003748 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003749 i);
3750 res = INVALID_OPERATION;
3751 break;
3752 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003753 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003754
Eric Laurent97ac8712018-07-27 18:59:02 -07003755 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003756 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003757 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003758 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003759 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3760 } else {
3761 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3762 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003763 }
François Gaffie036e1e92015-03-19 10:16:24 +01003764
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003765 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003766 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003767 res = INVALID_OPERATION;
3768 break;
3769 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003770 audio_config_t outputConfig = mix.mFormat;
3771 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003772 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3773 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003774 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3775 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003776 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003777 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3778 audio_is_linear_pcm(outputConfig.format)
3779 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003780 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003781 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3782 audio_is_linear_pcm(inputConfig.format)
3783 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003784
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003785 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003786 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003787 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003788 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003789 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003790 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003791 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003792 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3793 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003794 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003795 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003796 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003797
3798 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3799 mix.mDeviceType, mix.mDeviceAddress,
3800 String8(), AUDIO_FORMAT_DEFAULT);
3801 if (device == nullptr) {
3802 res = INVALID_OPERATION;
3803 break;
3804 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003805
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003806 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003807 // First try to find an already opened output supporting the device
3808 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003809 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003810
Eric Laurentc529cf62020-04-17 18:19:10 -07003811 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003812 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003813 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003814 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003815 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003816 } else {
3817 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003818 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003819 }
3820 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003821 // If no output found, try to find a direct output profile supporting the device
3822 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3823 sp<HwModule> module = mHwModules[i];
3824 for (size_t j = 0;
3825 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3826 j++) {
3827 sp<IOProfile> profile = module->getOutputProfiles()[j];
3828 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3829 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3830 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003831 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003832 res = INVALID_OPERATION;
3833 } else {
3834 foundOutput = true;
3835 }
3836 }
3837 }
3838 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003839 if (res != NO_ERROR) {
3840 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003841 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003842 res = INVALID_OPERATION;
3843 break;
3844 } else if (!foundOutput) {
3845 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003846 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003847 res = INVALID_OPERATION;
3848 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003849 } else {
3850 checkOutputs = true;
Marvin Raminabd9b892023-11-17 16:36:27 +01003851 registeredMixes.add(mix);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003852 }
Eric Laurentc722f302014-12-10 11:21:49 -08003853 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003854 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003855 if (res != NO_ERROR) {
Marvin Raminabd9b892023-11-17 16:36:27 +01003856 if (audio_flags::audio_mix_ownership()) {
3857 // Only unregister mixes that were actually registered to not accidentally unregister
3858 // mixes that already existed previously.
3859 unregisterPolicyMixes(registeredMixes);
3860 registeredMixes.clear();
3861 } else {
3862 unregisterPolicyMixes(mixes);
3863 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003864 } else if (checkOutputs) {
3865 checkForDeviceAndOutputChanges();
3866 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003867 }
3868 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003869}
3870
3871status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3872{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003873 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Marvin Raminabd9b892023-11-17 16:36:27 +01003874 status_t endResult = NO_ERROR;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003875 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003876 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003877 sp<HwModule> rSubmixModule;
3878 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003879 for (const auto& mix : mixes) {
3880 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003881
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003882 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003883 rSubmixModule = mHwModules.getModuleFromName(
3884 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3885 if (rSubmixModule == 0) {
3886 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003887 endResult = INVALID_OPERATION;
Mikhail Naganovd4120142017-12-06 15:49:22 -08003888 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003889 }
3890 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003891
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003892 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003893
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003894 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003895 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003896 endResult = INVALID_OPERATION;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003897 continue;
3898 }
3899
Kevin Rocard04ed0462019-05-02 17:53:24 -07003900 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003901 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003902 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3903 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003904 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003905 AUDIO_FORMAT_DEFAULT);
3906 if (res != OK) {
3907 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00003908 "with type %d, address %s", device, address.c_str());
Marvin Raminabd9b892023-11-17 16:36:27 +01003909 endResult = INVALID_OPERATION;
Kevin Rocard04ed0462019-05-02 17:53:24 -07003910 }
3911 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003912 }
jiabin5740f082019-08-19 15:08:30 -07003913 rSubmixModule->removeOutputProfile(address.c_str());
3914 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003915
Kevin Rocard153f92d2018-12-18 18:33:28 -08003916 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003917 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003918 res = INVALID_OPERATION;
Marvin Raminabd9b892023-11-17 16:36:27 +01003919 endResult = INVALID_OPERATION;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003920 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003921 } else {
3922 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003923 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003924 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003925 }
Marvin Raminabd9b892023-11-17 16:36:27 +01003926 if (audio_flags::audio_mix_ownership()) {
3927 res = endResult;
3928 if (res == NO_ERROR && checkOutputs) {
3929 checkForDeviceAndOutputChanges();
3930 updateCallAndOutputRouting();
3931 }
3932 } else {
3933 if (res == NO_ERROR && checkOutputs) {
3934 checkForDeviceAndOutputChanges();
3935 updateCallAndOutputRouting();
3936 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003937 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003938 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003939}
3940
Marvin Raminbdefaf02023-11-01 09:10:32 +01003941status_t AudioPolicyManager::getRegisteredPolicyMixes(std::vector<AudioMix>& _aidl_return) {
3942 if (!audio_flags::audio_mix_test_api()) {
3943 return INVALID_OPERATION;
3944 }
3945
3946 _aidl_return.clear();
3947 _aidl_return.reserve(mPolicyMixes.size());
3948 for (const auto &policyMix: mPolicyMixes) {
3949 _aidl_return.emplace_back(policyMix->mCriteria, policyMix->mMixType,
3950 policyMix->mFormat, policyMix->mRouteFlags, policyMix->mDeviceAddress,
3951 policyMix->mCbFlags);
3952 _aidl_return.back().mDeviceType = policyMix->mDeviceType;
Marvin Raminabd9b892023-11-17 16:36:27 +01003953 _aidl_return.back().mToken = policyMix->mToken;
Marvin Raminbdefaf02023-11-01 09:10:32 +01003954 }
3955
3956 ALOGVV("%s() returning %zu registered mixes", __func__, _aidl_return->size());
3957 return OK;
3958}
3959
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003960status_t AudioPolicyManager::updatePolicyMix(
3961 const AudioMix& mix,
3962 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3963 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3964 if (res == NO_ERROR) {
3965 checkForDeviceAndOutputChanges();
3966 updateCallAndOutputRouting();
3967 }
3968 return res;
3969}
3970
Mikhail Naganov100f0122018-11-29 11:22:16 -08003971void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3972{
3973 size_t i = 0;
3974 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3975 for (const auto& fmt : mManualSurroundFormats) {
3976 if (i++ != 0) dst->append(", ");
3977 std::string sfmt;
3978 FormatConverter::toString(fmt, sfmt);
3979 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3980 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3981 }
3982}
3983
Eric Laurentc529cf62020-04-17 18:19:10 -07003984// Returns true if all devices types match the predicate and are supported by one HW module
3985bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003986 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003987 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003988 const char *context,
3989 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003990 for (size_t i = 0; i < devices.size(); i++) {
3991 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003992 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003993 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003994 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003995 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003996 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003997 return false;
3998 }
3999 }
4000 return true;
4001}
4002
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004003void AudioPolicyManager::changeOutputDevicesMuteState(
4004 const AudioDeviceTypeAddrVector& devices) {
4005 ALOGVV("%s() num devices %zu", __func__, devices.size());
4006
4007 std::vector<sp<SwAudioOutputDescriptor>> outputs =
4008 getSoftwareOutputsForDevices(devices);
4009
4010 for (size_t i = 0; i < outputs.size(); i++) {
4011 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
4012 DeviceVector prevDevices = outputDesc->devices();
4013 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
4014 }
4015}
4016
4017std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
4018 const AudioDeviceTypeAddrVector& devices) const
4019{
4020 std::vector<sp<SwAudioOutputDescriptor>> outputs;
4021 DeviceVector deviceDescriptors;
4022 for (size_t j = 0; j < devices.size(); j++) {
4023 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
4024 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
4025 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
4026 ALOGE("%s: device type %#x address %s not supported or not an output device",
4027 __func__, devices[j].mType, devices[j].getAddress());
4028 continue;
4029 }
4030 deviceDescriptors.add(desc);
4031 }
4032 for (size_t i = 0; i < mOutputs.size(); i++) {
4033 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
4034 continue;
4035 }
4036 outputs.push_back(mOutputs.valueAt(i));
4037 }
4038 return outputs;
4039}
4040
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004041status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07004042 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004043 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004044 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4045 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004046 }
4047 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07004048 if (res != NO_ERROR) {
4049 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
4050 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004051 }
Eric Laurentc529cf62020-04-17 18:19:10 -07004052
4053 checkForDeviceAndOutputChanges();
4054 updateCallAndOutputRouting();
4055
4056 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004057}
4058
4059status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
4060 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004061 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
4062 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07004063 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07004064 __FUNCTION__, uid);
4065 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004066 }
4067
Eric Laurentc529cf62020-04-17 18:19:10 -07004068 checkForDeviceAndOutputChanges();
4069 updateCallAndOutputRouting();
4070
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08004071 return res;
4072}
4073
Eric Laurent2517af32020-11-25 15:31:27 +01004074
jiabin0a488932020-08-07 17:32:40 -07004075status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
4076 device_role_t role,
4077 const AudioDeviceTypeAddrVector &devices) {
4078 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4079 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07004080
Eric Laurentc529cf62020-04-17 18:19:10 -07004081 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004082 return BAD_VALUE;
4083 }
jiabin0a488932020-08-07 17:32:40 -07004084 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004085 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07004086 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
4087 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004088 return status;
4089 }
4090
4091 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004092
4093 bool forceVolumeReeval = false;
4094 // FIXME: workaround for truncated touch sounds
4095 // to be removed when the problem is handled by system UI
4096 uint32_t delayMs = 0;
4097 if (strategy == mCommunnicationStrategy) {
4098 forceVolumeReeval = true;
4099 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4100 updateInputRouting();
4101 }
4102 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004103
4104 return NO_ERROR;
4105}
4106
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004107void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4108 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004109{
4110 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004111 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004112 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004113 // Only apply special touch sound delay once
4114 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004115 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004116 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004117 for (size_t i = 0; i < mOutputs.size(); i++) {
4118 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4119 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004120 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4121 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004122 // As done in setDeviceConnectionState, we could also fix default device issue by
4123 // preventing the force re-routing in case of default dev that distinguishes on address.
4124 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004125 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004126 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4127 // If the device is using preferred mixer attributes, the output need to reopen
4128 // with default configuration when the new selected devices are different from
4129 // current routing devices.
4130 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4131 continue;
4132 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304133
4134 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4135 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004136 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004137 // Only apply special touch sound delay once
4138 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004139 }
4140 if (forceVolumeReeval && !newDevices.isEmpty()) {
4141 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4142 }
4143 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004144 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004145 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004146}
4147
Eric Laurent2517af32020-11-25 15:31:27 +01004148void AudioPolicyManager::updateInputRouting() {
4149 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304150 // Skip for hotword recording as the input device switch
4151 // is handled within sound trigger HAL
4152 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4153 continue;
4154 }
Eric Laurent2517af32020-11-25 15:31:27 +01004155 auto newDevice = getNewInputDevice(activeDesc);
4156 // Force new input selection if the new device can not be reached via current input
4157 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4158 setInputDevice(activeDesc->mIoHandle, newDevice);
4159 } else {
4160 closeInput(activeDesc->mIoHandle);
4161 }
4162 }
4163}
4164
Paul Wang5d7cdb52022-11-22 09:45:06 +00004165status_t
4166AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4167 device_role_t role,
4168 const AudioDeviceTypeAddrVector &devices) {
4169 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4170 dumpAudioDeviceTypeAddrVector(devices).c_str());
4171
Eric Laurent78fedbf2023-03-09 14:40:44 +01004172 if (!areAllDevicesSupported(
4173 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004174 return BAD_VALUE;
4175 }
4176 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4177 if (status != NO_ERROR) {
4178 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4179 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4180 return status;
4181 }
4182
4183 checkForDeviceAndOutputChanges();
4184
4185 bool forceVolumeReeval = false;
4186 // TODO(b/263479999): workaround for truncated touch sounds
4187 // to be removed when the problem is handled by system UI
4188 uint32_t delayMs = 0;
4189 if (strategy == mCommunnicationStrategy) {
4190 forceVolumeReeval = true;
4191 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4192 updateInputRouting();
4193 }
4194 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4195
4196 return NO_ERROR;
4197}
4198
4199status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4200 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004201{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004202 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004203
Paul Wang5d7cdb52022-11-22 09:45:06 +00004204 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004205 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004206 ALOGW_IF(status != NAME_NOT_FOUND,
4207 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004208 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004209 return status;
4210 }
4211
4212 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004213
4214 bool forceVolumeReeval = false;
4215 // FIXME: workaround for truncated touch sounds
4216 // to be removed when the problem is handled by system UI
4217 uint32_t delayMs = 0;
4218 if (strategy == mCommunnicationStrategy) {
4219 forceVolumeReeval = true;
4220 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4221 updateInputRouting();
4222 }
4223 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004224
4225 return NO_ERROR;
4226}
4227
jiabin0a488932020-08-07 17:32:40 -07004228status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4229 device_role_t role,
4230 AudioDeviceTypeAddrVector &devices) {
4231 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004232}
4233
Jiabin Huang3b98d322020-09-03 17:54:16 +00004234status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4235 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4236 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4237 dumpAudioDeviceTypeAddrVector(devices).c_str());
4238
Mikhail Naganov55773032020-10-01 15:08:13 -07004239 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004240 return BAD_VALUE;
4241 }
4242 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4243 ALOGW_IF(status != NO_ERROR,
4244 "Engine could not set preferred devices %s for audio source %d role %d",
4245 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4246
4247 return status;
4248}
4249
4250status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4251 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4252 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4253 dumpAudioDeviceTypeAddrVector(devices).c_str());
4254
Mikhail Naganov55773032020-10-01 15:08:13 -07004255 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004256 return BAD_VALUE;
4257 }
4258 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4259 ALOGW_IF(status != NO_ERROR,
4260 "Engine could not add preferred devices %s for audio source %d role %d",
4261 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4262
Eric Laurent2517af32020-11-25 15:31:27 +01004263 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004264 return status;
4265}
4266
4267status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4268 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4269{
4270 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4271 dumpAudioDeviceTypeAddrVector(devices).c_str());
4272
Eric Laurent78fedbf2023-03-09 14:40:44 +01004273 if (!areAllDevicesSupported(
4274 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004275 return BAD_VALUE;
4276 }
4277
4278 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4279 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004280 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004281 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004282 if (status == NO_ERROR) {
4283 updateInputRouting();
4284 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004285 return status;
4286}
4287
4288status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4289 device_role_t role) {
4290 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4291
4292 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004293 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004294 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004295 if (status == NO_ERROR) {
4296 updateInputRouting();
4297 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004298 return status;
4299}
4300
4301status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4302 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4303 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4304}
4305
Oscar Azucena90e77632019-11-27 17:12:28 -08004306status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004307 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004308 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004309 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4310 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004311 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004312 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4313 if (status != NO_ERROR) {
4314 ALOGE("%s() could not set device affinity for userId %d",
4315 __FUNCTION__, userId);
4316 return status;
4317 }
4318
4319 // reevaluate outputs for all devices
4320 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004321 changeOutputDevicesMuteState(devices);
4322 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4323 true /* skipDelays */);
4324 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004325
4326 return NO_ERROR;
4327}
4328
4329status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004330 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004331 AudioDeviceTypeAddrVector devices;
4332 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004333 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4334 if (status != NO_ERROR) {
4335 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4336 __FUNCTION__, userId);
4337 return status;
4338 }
4339
4340 // reevaluate outputs for all devices
4341 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004342 changeOutputDevicesMuteState(devices);
4343 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4344 true /* skipDelays */);
4345 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004346
4347 return NO_ERROR;
4348}
4349
Andy Hungc29d82b2018-10-05 12:23:17 -07004350void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004351{
Andy Hungc29d82b2018-10-05 12:23:17 -07004352 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004353 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004354 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004355 std::string stateLiteral;
4356 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004357 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004358 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4359 "communications", "media", "record", "dock", "system",
4360 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4361 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4362 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004363 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4364 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4365 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4366 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4367 dst->append(" (MANUAL: ");
4368 dumpManualSurroundFormats(dst);
4369 dst->append(")");
4370 }
4371 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004372 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004373 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4374 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004375 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004376 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004377
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004378 dst->append("\n");
4379 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4380 dst->append("\n");
4381 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004382 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004383 mOutputs.dump(dst);
4384 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004385 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004386 mAudioPatches.dump(dst);
4387 mPolicyMixes.dump(dst);
4388 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004389
Kevin Rocardb99cc752019-03-21 20:52:24 -07004390 dst->appendFormat(" AllowedCapturePolicies:\n");
4391 for (auto& policy : mAllowedCapturePolicies) {
4392 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4393 }
4394
jiabina84c3d32022-12-02 18:59:55 +00004395 dst->appendFormat(" Preferred mixer audio configuration:\n");
4396 for (const auto it : mPreferredMixerAttrInfos) {
4397 dst->appendFormat(" - device port id: %d\n", it.first);
4398 for (const auto preferredMixerInfoIt : it.second) {
4399 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4400 preferredMixerInfoIt.second->dump(dst);
4401 }
4402 }
4403
François Gaffiec005e562018-11-06 15:04:49 +01004404 dst->appendFormat("\nPolicy Engine dump:\n");
4405 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004406}
4407
4408status_t AudioPolicyManager::dump(int fd)
4409{
4410 String8 result;
4411 dump(&result);
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00004412 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004413 return NO_ERROR;
4414}
4415
Kevin Rocardb99cc752019-03-21 20:52:24 -07004416status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4417{
4418 mAllowedCapturePolicies[uid] = capturePolicy;
4419 return NO_ERROR;
4420}
4421
Eric Laurente552edb2014-03-10 17:42:56 -07004422// This function checks for the parameters which can be offloaded.
4423// This can be enhanced depending on the capability of the DSP and policy
4424// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004425audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004426{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004427 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004428 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004429 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004430 offloadInfo.format,
4431 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4432 offloadInfo.has_video);
4433
jiabin2b9d5a12021-12-10 01:06:29 +00004434 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004435 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004436 }
4437
4438 // See if there is a profile to support this.
4439 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004440 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004441 offloadInfo.sample_rate,
4442 offloadInfo.format,
4443 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004444 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4445 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004446 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4447 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4448 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004449 if (profile == nullptr) {
4450 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4451 }
4452 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4453 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4454 }
4455 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004456}
4457
Michael Chana94fbb22018-04-24 14:31:19 +10004458bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4459 const audio_attributes_t& attributes) {
4460 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004461 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004462 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4463 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004464 config.sample_rate,
4465 config.format,
4466 config.channel_mask,
4467 output_flags,
4468 true /* directOnly */);
4469 ALOGV("%s() profile %sfound with name: %s, "
4470 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4471 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004472 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004473 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004474
4475 // also try the MSD module if compatible profile not found
4476 if (profile == nullptr) {
4477 profile = getMsdProfileForOutput(outputDevices,
4478 config.sample_rate,
4479 config.format,
4480 config.channel_mask,
4481 output_flags,
4482 true /* directOnly */);
4483 ALOGV("%s() MSD profile %sfound with name: %s, "
4484 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4485 __FUNCTION__, profile != 0 ? "" : "NOT ",
4486 (profile != 0 ? profile->getTagName().c_str() : "null"),
4487 config.sample_rate, config.format, config.channel_mask, output_flags);
4488 }
4489 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004490}
4491
jiabin2b9d5a12021-12-10 01:06:29 +00004492bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4493 bool durationIgnored) {
4494 if (mMasterMono) {
4495 return false; // no offloading if mono is set.
4496 }
4497
4498 // Check if offload has been disabled
4499 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4500 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4501 return false;
4502 }
4503
4504 // Check if stream type is music, then only allow offload as of now.
4505 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4506 {
4507 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4508 return false;
4509 }
4510
4511 //TODO: enable audio offloading with video when ready
4512 const bool allowOffloadWithVideo =
4513 property_get_bool("audio.offload.video", false /* default_value */);
4514 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4515 ALOGV("%s: has_video == true, returning false", __func__);
4516 return false;
4517 }
4518
4519 //If duration is less than minimum value defined in property, return false
4520 const int min_duration_secs = property_get_int32(
4521 "audio.offload.min.duration.secs", -1 /* default_value */);
4522 if (!durationIgnored) {
4523 if (min_duration_secs >= 0) {
4524 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4525 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4526 __func__, min_duration_secs);
4527 return false;
4528 }
4529 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4530 ALOGV("%s: Offload denied by duration < default min(=%u)",
4531 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4532 return false;
4533 }
4534 }
4535
4536 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4537 // creating an offloaded track and tearing it down immediately after start when audioflinger
4538 // detects there is an active non offloadable effect.
4539 // FIXME: We should check the audio session here but we do not have it in this context.
4540 // This may prevent offloading in rare situations where effects are left active by apps
4541 // in the background.
4542 if (mEffects.isNonOffloadableEffectEnabled()) {
4543 return false;
4544 }
4545
4546 return true;
4547}
4548
4549audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4550 const audio_config_t *config) {
4551 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4552 offloadInfo.format = config->format;
4553 offloadInfo.sample_rate = config->sample_rate;
4554 offloadInfo.channel_mask = config->channel_mask;
4555 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4556 offloadInfo.has_video = false;
4557 offloadInfo.is_streaming = false;
4558 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4559
4560 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4561 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4562 audio_flags_to_audio_output_flags(attr->flags, &flags);
4563 // only retain flags that will drive compressed offload or passthrough
4564 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4565 if (offloadPossible) {
4566 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4567 }
4568 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4569
Dorin Drimusfae3c642022-03-17 18:36:30 +01004570 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004571 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004572 DeviceVector outputDevices = engineOutputDevices;
4573 // the MSD module checks for different conditions and output devices
4574 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4575 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4576 continue;
4577 }
4578 outputDevices = getMsdAudioOutDevices();
4579 }
jiabin2b9d5a12021-12-10 01:06:29 +00004580 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabin66acc432024-02-06 00:57:36 +00004581 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004582 config->sample_rate, nullptr /*updatedSamplingRate*/,
4583 config->format, nullptr /*updatedFormat*/,
4584 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004585 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004586 continue;
4587 }
4588 // reject profiles not corresponding to a device currently available
4589 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4590 continue;
4591 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004592 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4593 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004594 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004595 != AUDIO_DIRECT_NOT_SUPPORTED) {
4596 // Already reports offload gapless supported. No need to report offload support.
4597 continue;
4598 }
4599 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4600 != AUDIO_OUTPUT_FLAG_NONE) {
4601 // If offload gapless is reported, no need to report offload support.
4602 directMode = (audio_direct_mode_t) ((directMode &
4603 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4604 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4605 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004606 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004607 }
4608 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004609 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004610 }
4611 }
4612 }
4613 return directMode;
4614}
4615
Dorin Drimusf2196d82022-01-03 12:11:18 +01004616status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4617 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004618 if (mEffects.isNonOffloadableEffectEnabled()) {
4619 return OK;
4620 }
jiabinf1c73972022-04-14 16:28:52 -07004621 DeviceVector devices;
4622 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004623 if (status != OK) {
4624 return status;
4625 }
4626 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4627 if (devices.empty()) {
4628 return OK; // no output devices for the attributes
4629 }
jiabinf1c73972022-04-14 16:28:52 -07004630 return getProfilesForDevices(devices, audioProfilesVector,
4631 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004632}
4633
jiabina84c3d32022-12-02 18:59:55 +00004634status_t AudioPolicyManager::getSupportedMixerAttributes(
4635 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4636 ALOGV("%s, portId=%d", __func__, portId);
4637 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4638 if (deviceDescriptor == nullptr) {
4639 ALOGE("%s the requested device is currently unavailable", __func__);
4640 return BAD_VALUE;
4641 }
jiabin96daffc2023-05-11 17:51:55 +00004642 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4643 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4644 deviceDescriptor->type());
4645 return BAD_VALUE;
4646 }
jiabina84c3d32022-12-02 18:59:55 +00004647 for (const auto& hwModule : mHwModules) {
4648 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4649 if (curProfile->supportsDevice(deviceDescriptor)) {
4650 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4651 }
4652 }
4653 }
4654 return NO_ERROR;
4655}
4656
4657status_t AudioPolicyManager::setPreferredMixerAttributes(
4658 const audio_attributes_t *attr,
4659 audio_port_handle_t portId,
4660 uid_t uid,
4661 const audio_mixer_attributes_t *mixerAttributes) {
4662 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4663 "mixerBehavior=%d}, uid=%d, portId=%u",
4664 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4665 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4666 mixerAttributes->mixer_behavior, uid, portId);
4667 if (attr->usage != AUDIO_USAGE_MEDIA) {
4668 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4669 return BAD_VALUE;
4670 }
4671 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4672 if (deviceDescriptor == nullptr) {
4673 ALOGE("%s the requested device is currently unavailable", __func__);
4674 return BAD_VALUE;
4675 }
4676 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4677 ALOGE("%s(%d), type=%d, is not a usb output device",
4678 __func__, portId, deviceDescriptor->type());
4679 return BAD_VALUE;
4680 }
4681
4682 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4683 audio_flags_to_audio_output_flags(attr->flags, &flags);
4684 flags = (audio_output_flags_t) (flags |
4685 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4686 sp<IOProfile> profile = nullptr;
4687 DeviceVector devices(deviceDescriptor);
4688 for (const auto& hwModule : mHwModules) {
4689 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4690 if (curProfile->hasDynamicAudioProfile()
jiabin66acc432024-02-06 00:57:36 +00004691 && curProfile->getCompatibilityScore(
4692 devices,
4693 mixerAttributes->config.sample_rate,
4694 nullptr /*updatedSamplingRate*/,
4695 mixerAttributes->config.format,
4696 nullptr /*updatedFormat*/,
4697 mixerAttributes->config.channel_mask,
4698 nullptr /*updatedChannelMask*/,
4699 flags,
4700 false /*exactMatchRequiredForInputFlags*/)
4701 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004702 profile = curProfile;
4703 break;
4704 }
4705 }
4706 }
4707 if (profile == nullptr) {
4708 ALOGE("%s, there is no compatible profile found", __func__);
4709 return BAD_VALUE;
4710 }
4711
4712 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4713 sp<PreferredMixerAttributesInfo>::make(
4714 uid, portId, profile, flags, *mixerAttributes);
4715 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4716 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4717
4718 // If 1) there is any client from the preferred mixer configuration owner that is currently
4719 // active and matches the strategy and 2) current output is on the preferred device and the
4720 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4721 // configuration.
4722 std::vector<audio_io_handle_t> outputsToReopen;
4723 for (size_t i = 0; i < mOutputs.size(); i++) {
4724 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004725 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4726 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4727 output->mUsePreferredMixerAttributes = true;
4728 } else {
4729 for (const auto &client: output->getActiveClients()) {
4730 if (client->uid() == uid && client->strategy() == strategy) {
4731 client->setIsInvalid();
4732 outputsToReopen.push_back(output->mIoHandle);
4733 }
jiabina84c3d32022-12-02 18:59:55 +00004734 }
4735 }
4736 }
4737 }
4738 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4739 config.sample_rate = mixerAttributes->config.sample_rate;
4740 config.channel_mask = mixerAttributes->config.channel_mask;
4741 config.format = mixerAttributes->config.format;
4742 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004743 sp<SwAudioOutputDescriptor> desc =
4744 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4745 if (desc == nullptr) {
4746 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4747 continue;
4748 }
4749 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004750 }
4751
4752 return NO_ERROR;
4753}
4754
4755sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004756 audio_port_handle_t devicePortId,
4757 product_strategy_t strategy,
4758 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004759 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4760 if (it == mPreferredMixerAttrInfos.end()) {
4761 return nullptr;
4762 }
jiabind9a58d32023-06-01 17:57:30 +00004763 if (activeBitPerfectPreferred) {
4764 for (auto [strategy, info] : it->second) {
4765 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4766 && info->getActiveClientCount() != 0) {
4767 return info;
4768 }
4769 }
jiabina84c3d32022-12-02 18:59:55 +00004770 }
jiabind9a58d32023-06-01 17:57:30 +00004771 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4772 return strategyMatchedMixerAttrInfoIt == it->second.end()
4773 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004774}
4775
4776status_t AudioPolicyManager::getPreferredMixerAttributes(
4777 const audio_attributes_t *attr,
4778 audio_port_handle_t portId,
4779 audio_mixer_attributes_t* mixerAttributes) {
4780 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4781 portId, mEngine->getProductStrategyForAttributes(*attr));
4782 if (info == nullptr) {
4783 return NAME_NOT_FOUND;
4784 }
4785 *mixerAttributes = info->getMixerAttributes();
4786 return NO_ERROR;
4787}
4788
4789status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4790 audio_port_handle_t portId,
4791 uid_t uid) {
4792 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4793 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4794 if (preferredMixerAttrInfo == nullptr) {
4795 return NAME_NOT_FOUND;
4796 }
4797 if (preferredMixerAttrInfo->getUid() != uid) {
4798 ALOGE("%s, requested uid=%d, owned uid=%d",
4799 __func__, uid, preferredMixerAttrInfo->getUid());
4800 return PERMISSION_DENIED;
4801 }
4802 mPreferredMixerAttrInfos[portId].erase(strategy);
4803 if (mPreferredMixerAttrInfos[portId].empty()) {
4804 mPreferredMixerAttrInfos.erase(portId);
4805 }
4806
4807 // Reconfig existing output
4808 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4809 for (size_t i = 0; i < mOutputs.size(); i++) {
4810 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4811 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4812 }
4813 }
4814 for (const auto output : potentialOutputsToReopen) {
4815 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4816 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4817 preferredMixerAttrInfo->getFlags())) {
4818 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4819 }
4820 }
4821 return NO_ERROR;
4822}
4823
Eric Laurent6a94d692014-05-20 11:18:06 -07004824status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4825 audio_port_type_t type,
4826 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004827 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004828 unsigned int *generation)
4829{
jiabin19cdba52020-11-24 11:28:58 -08004830 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4831 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004832 return BAD_VALUE;
4833 }
4834 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004835 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004836 *num_ports = 0;
4837 }
4838
4839 size_t portsWritten = 0;
4840 size_t portsMax = *num_ports;
4841 *num_ports = 0;
4842 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004843 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4844 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004845 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004846 for (const auto& dev : mAvailableOutputDevices) {
4847 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004848 continue;
4849 }
4850 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004851 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004852 }
4853 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004854 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004855 }
4856 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004857 for (const auto& dev : mAvailableInputDevices) {
4858 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004859 continue;
4860 }
4861 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004862 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004863 }
4864 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004865 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004866 }
4867 }
4868 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4869 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4870 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4871 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4872 }
4873 *num_ports += mInputs.size();
4874 }
4875 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004876 size_t numOutputs = 0;
4877 for (size_t i = 0; i < mOutputs.size(); i++) {
4878 if (!mOutputs[i]->isDuplicated()) {
4879 numOutputs++;
4880 if (portsWritten < portsMax) {
4881 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4882 }
4883 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004884 }
Eric Laurent84c70242014-06-23 08:46:27 -07004885 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004886 }
4887 }
jiabina84c3d32022-12-02 18:59:55 +00004888
Eric Laurent6a94d692014-05-20 11:18:06 -07004889 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004890 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004891 return NO_ERROR;
4892}
4893
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004894status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4895 std::vector<media::AudioPortFw>* _aidl_return) {
4896 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4897 audio_port_v7 port;
4898 dev->toAudioPort(&port);
4899 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4900 _aidl_return->push_back(std::move(aidlPort));
4901 return OK;
4902 };
4903
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004904 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004905 for (const auto& dev : module->getDeclaredDevices()) {
4906 if (role == media::AudioPortRole::NONE ||
4907 ((role == media::AudioPortRole::SOURCE)
4908 == audio_is_input_device(dev->type()))) {
4909 RETURN_STATUS_IF_ERROR(pushPort(dev));
4910 }
4911 }
4912 }
4913 return OK;
4914}
4915
jiabin19cdba52020-11-24 11:28:58 -08004916status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004917{
Eric Laurent99fcae42018-05-17 16:59:18 -07004918 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4919 return BAD_VALUE;
4920 }
4921 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4922 if (dev != 0) {
4923 dev->toAudioPort(port);
4924 return NO_ERROR;
4925 }
4926 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4927 if (dev != 0) {
4928 dev->toAudioPort(port);
4929 return NO_ERROR;
4930 }
4931 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4932 if (out != 0) {
4933 out->toAudioPort(port);
4934 return NO_ERROR;
4935 }
4936 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4937 if (in != 0) {
4938 in->toAudioPort(port);
4939 return NO_ERROR;
4940 }
4941 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004942}
4943
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004944status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4945 audio_patch_handle_t *handle,
4946 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004947{
François Gaffieafd4cea2019-11-18 15:50:22 +01004948 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004949 if (handle == NULL || patch == NULL) {
4950 return BAD_VALUE;
4951 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004952 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004953 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004954 return BAD_VALUE;
4955 }
4956 // only one source per audio patch supported for now
4957 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004958 return INVALID_OPERATION;
4959 }
Eric Laurent874c42872014-08-08 15:13:39 -07004960 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004961 return INVALID_OPERATION;
4962 }
Eric Laurent874c42872014-08-08 15:13:39 -07004963 for (size_t i = 0; i < patch->num_sinks; i++) {
4964 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4965 return INVALID_OPERATION;
4966 }
4967 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004968
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004969 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4970 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4971 if (srcDevice == nullptr || sinkDevice == nullptr) {
4972 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4973 return BAD_VALUE;
4974 }
4975 ALOGV("%s between source %s and sink %s", __func__,
4976 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4977 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4978 // Default attributes, default volume priority, not to infer with non raw audio patches.
4979 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4980 const struct audio_port_config *source = &patch->sources[0];
4981 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004982 new SourceClientDescriptor(
4983 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4984 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4985 true);
4986 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004987
4988 status_t status =
4989 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4990
4991 if (status != NO_ERROR) {
4992 return INVALID_OPERATION;
4993 }
4994 mAudioSources.add(portId, sourceDesc);
4995 return NO_ERROR;
4996}
4997
4998status_t AudioPolicyManager::connectAudioSourceToSink(
4999 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
5000 const struct audio_patch *patch,
5001 audio_patch_handle_t &handle,
5002 uid_t uid, uint32_t delayMs)
5003{
5004 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
5005 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
5006 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
5007 return INVALID_OPERATION;
5008 }
5009 sourceDesc->connect(handle, sinkDevice);
5010 if (isMsdPatch(handle)) {
5011 return NO_ERROR;
5012 }
5013 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
5014 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5015 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
5016 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
5017 ALOGW("%s source portId has already been attached to outputDesc", __func__);
5018 goto FailurePatchAdded;
5019 }
5020 status = swOutput->start();
5021 if (status != NO_ERROR) {
5022 goto FailureSourceAdded;
5023 }
5024 swOutput->addClient(sourceDesc);
5025 status = startSource(swOutput, sourceDesc, &delayMs);
5026 if (status != NO_ERROR) {
5027 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
5028 goto FailureSourceActive;
5029 }
5030 if (delayMs != 0) {
5031 usleep(delayMs * 1000);
5032 }
5033 return NO_ERROR;
5034
5035FailureSourceActive:
5036 swOutput->stop();
5037 releaseOutput(sourceDesc->portId());
5038FailureSourceAdded:
5039 sourceDesc->setSwOutput(nullptr);
5040FailurePatchAdded:
5041 releaseAudioPatchInternal(handle);
5042 return INVALID_OPERATION;
5043}
5044
5045status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
5046 audio_patch_handle_t *handle,
5047 uid_t uid, uint32_t delayMs,
5048 const sp<SourceClientDescriptor>& sourceDesc)
5049{
5050 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07005051 sp<AudioPatch> patchDesc;
5052 ssize_t index = mAudioPatches.indexOfKey(*handle);
5053
François Gaffieafd4cea2019-11-18 15:50:22 +01005054 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
5055 patch->sources[0].role,
5056 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005057#if LOG_NDEBUG == 0
5058 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005059 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
5060 patch->sinks[i].role,
5061 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07005062 }
5063#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07005064
5065 if (index >= 0) {
5066 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005067 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
5068 __func__, mUidCached, patchDesc->getUid(), uid);
5069 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005070 return INVALID_OPERATION;
5071 }
5072 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07005073 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07005074 }
5075
5076 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005077 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005078 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005079 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005080 return BAD_VALUE;
5081 }
Eric Laurent84c70242014-06-23 08:46:27 -07005082 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
5083 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005084 if (patchDesc != 0) {
5085 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005086 ALOGV("%s source id differs for patch current id %d new id %d",
5087 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005088 return BAD_VALUE;
5089 }
5090 }
Eric Laurent874c42872014-08-08 15:13:39 -07005091 DeviceVector devices;
5092 for (size_t i = 0; i < patch->num_sinks; i++) {
5093 // Only support mix to devices connection
5094 // TODO add support for mix to mix connection
5095 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005096 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005097 return INVALID_OPERATION;
5098 }
5099 sp<DeviceDescriptor> devDesc =
5100 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5101 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005102 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005103 return BAD_VALUE;
5104 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005105
jiabin66acc432024-02-06 00:57:36 +00005106 if (outputDesc->mProfile->getCompatibilityScore(
5107 DeviceVector(devDesc),
5108 patch->sources[0].sample_rate,
5109 nullptr, // updatedSamplingRate
5110 patch->sources[0].format,
5111 nullptr, // updatedFormat
5112 patch->sources[0].channel_mask,
5113 nullptr, // updatedChannelMask
5114 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005115 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005116 return INVALID_OPERATION;
5117 }
5118 devices.add(devDesc);
5119 }
5120 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005121 return INVALID_OPERATION;
5122 }
Eric Laurent874c42872014-08-08 15:13:39 -07005123
Eric Laurent6a94d692014-05-20 11:18:06 -07005124 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005125 ALOGV("%s setting device %s on output %d",
5126 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305127 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005128 index = mAudioPatches.indexOfKey(*handle);
5129 if (index >= 0) {
5130 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005131 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005132 }
5133 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005134 patchDesc->setUid(uid);
5135 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005136 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005137 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005138 return INVALID_OPERATION;
5139 }
5140 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5141 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5142 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005143 // only one sink supported when connecting an input device to a mix
5144 if (patch->num_sinks > 1) {
5145 return INVALID_OPERATION;
5146 }
François Gaffie53615e22015-03-19 09:24:12 +01005147 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005148 if (inputDesc == NULL) {
5149 return BAD_VALUE;
5150 }
5151 if (patchDesc != 0) {
5152 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5153 return BAD_VALUE;
5154 }
5155 }
François Gaffie11d30102018-11-02 16:09:09 +01005156 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005157 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005158 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005159 return BAD_VALUE;
5160 }
5161
jiabin66acc432024-02-06 00:57:36 +00005162 if (inputDesc->mProfile->getCompatibilityScore(
5163 DeviceVector(device),
5164 patch->sinks[0].sample_rate,
5165 nullptr, /*updatedSampleRate*/
5166 patch->sinks[0].format,
5167 nullptr, /*updatedFormat*/
5168 patch->sinks[0].channel_mask,
5169 nullptr, /*updatedChannelMask*/
5170 // FIXME for the parameter type,
5171 // and the NONE
5172 (audio_output_flags_t)
5173 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005174 return INVALID_OPERATION;
5175 }
5176 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005177 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005178 device->toString().c_str(), inputDesc->mIoHandle);
5179 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005180 index = mAudioPatches.indexOfKey(*handle);
5181 if (index >= 0) {
5182 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005183 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005184 }
5185 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005186 patchDesc->setUid(uid);
5187 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005188 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005189 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005190 return INVALID_OPERATION;
5191 }
5192 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5193 // device to device connection
5194 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005195 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005196 return BAD_VALUE;
5197 }
5198 }
François Gaffie11d30102018-11-02 16:09:09 +01005199 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005200 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005201 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005202 return BAD_VALUE;
5203 }
Eric Laurent874c42872014-08-08 15:13:39 -07005204
Eric Laurent6a94d692014-05-20 11:18:06 -07005205 //update source and sink with our own data as the data passed in the patch may
5206 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005207 PatchBuilder patchBuilder;
5208 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005209
5210 // if first sink is to MSD, establish single MSD patch
5211 if (getMsdAudioOutDevices().contains(
5212 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5213 ALOGV("%s patching to MSD", __FUNCTION__);
5214 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5215 goto installPatch;
5216 }
5217
François Gaffieafd4cea2019-11-18 15:50:22 +01005218 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5219 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005220
Eric Laurent874c42872014-08-08 15:13:39 -07005221 for (size_t i = 0; i < patch->num_sinks; i++) {
5222 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005223 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005224 return INVALID_OPERATION;
5225 }
François Gaffie11d30102018-11-02 16:09:09 +01005226 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005227 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005228 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005229 return BAD_VALUE;
5230 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005231 audio_port_config sinkPortConfig = {};
5232 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5233 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005234
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005235 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5236 // volume management purpose (tracking activity)
5237 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5238 // in config XML to reach the sink so that is can be declared as available.
5239 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005240 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005241 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005242 // take care of dynamic routing for SwOutput selection,
5243 audio_attributes_t attributes = sourceDesc->attributes();
5244 audio_stream_type_t stream = sourceDesc->stream();
5245 audio_attributes_t resultAttr;
5246 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5247 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005248 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5249 config.channel_mask =
5250 (audio_channel_mask_get_representation(sourceMask)
5251 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5252 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005253 config.format = sourceDesc->config().format;
5254 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5255 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5256 bool isRequestedDeviceForExclusiveUse = false;
5257 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005258 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005259 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005260 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5261 &stream, sourceDesc->uid(), &config, &flags,
5262 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005263 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005264 if (output == AUDIO_IO_HANDLE_NONE) {
5265 ALOGV("%s no output for device %s",
5266 __FUNCTION__, sinkDevice->toString().c_str());
5267 return INVALID_OPERATION;
5268 }
5269 outputDesc = mOutputs.valueFor(output);
5270 if (outputDesc->isDuplicated()) {
5271 ALOGE("%s output is duplicated", __func__);
5272 return INVALID_OPERATION;
5273 }
François Gaffie7e39df22022-04-26 12:48:49 +02005274 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5275 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005276 } else {
5277 // Same for "raw patches" aka created from createAudioPatch API
5278 SortedVector<audio_io_handle_t> outputs =
5279 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5280 // if the sink device is reachable via an opened output stream, request to
5281 // go via this output stream by adding a second source to the patch
5282 // description
5283 output = selectOutput(outputs);
5284 if (output == AUDIO_IO_HANDLE_NONE) {
5285 ALOGE("%s no output available for internal patch sink", __func__);
5286 return INVALID_OPERATION;
5287 }
5288 outputDesc = mOutputs.valueFor(output);
5289 if (outputDesc->isDuplicated()) {
5290 ALOGV("%s output for device %s is duplicated",
5291 __func__, sinkDevice->toString().c_str());
5292 return INVALID_OPERATION;
5293 }
François Gaffie7e39df22022-04-26 12:48:49 +02005294 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005295 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005296 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005297 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005298 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005299 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005300 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5301 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005302 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5303 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005304 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005305 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005306 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005307 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005308 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005309 return INVALID_OPERATION;
5310 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005311 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005312 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005313 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005314 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005315 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005316 srcMixPortConfig.ext.mix.usecase.stream =
5317 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005318 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5319 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005320 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005321 }
Eric Laurent83b88082014-06-20 18:31:16 -07005322 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005323 }
5324 // TODO: check from routing capabilities in config file and other conflicting patches
5325
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005326installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005327 status_t status = installPatch(
5328 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005329 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005330 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005331 return INVALID_OPERATION;
5332 }
5333 } else {
5334 return BAD_VALUE;
5335 }
5336 } else {
5337 return BAD_VALUE;
5338 }
5339 return NO_ERROR;
5340}
5341
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005342status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005343{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005344 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005345 ssize_t index = mAudioPatches.indexOfKey(handle);
5346
5347 if (index < 0) {
5348 return BAD_VALUE;
5349 }
5350 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005351 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5352 __func__, mUidCached, patchDesc->getUid(), uid);
5353 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005354 return INVALID_OPERATION;
5355 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005356 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5357 for (size_t i = 0; i < mAudioSources.size(); i++) {
5358 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5359 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5360 portId = sourceDesc->portId();
5361 break;
5362 }
5363 }
5364 return portId != AUDIO_PORT_HANDLE_NONE ?
5365 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005366}
Eric Laurent6a94d692014-05-20 11:18:06 -07005367
François Gaffieafd4cea2019-11-18 15:50:22 +01005368status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005369 uint32_t delayMs,
5370 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005371{
5372 ALOGV("%s patch %d", __func__, handle);
5373 if (mAudioPatches.indexOfKey(handle) < 0) {
5374 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5375 return BAD_VALUE;
5376 }
5377 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005378 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005379 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005380 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005381 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005382 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005383 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005384 return BAD_VALUE;
5385 }
5386
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305387 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005388 getNewOutputDevices(outputDesc, true /*fromCache*/),
5389 true,
5390 0,
5391 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005392 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5393 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005394 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005395 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005396 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005397 return BAD_VALUE;
5398 }
5399 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005400 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005401 true,
5402 NULL);
5403 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005404 status_t status =
5405 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5406 ALOGV("%s patch panel returned %d patchHandle %d",
5407 __func__, status, patchDesc->getAfHandle());
5408 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005409 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005410 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005411 // SW or HW Bridge
5412 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5413 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005414 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005415 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5416 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5417 outputDesc = sourceDesc->swOutput().promote();
5418 }
5419 if (outputDesc == nullptr) {
5420 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5421 // releaseOutput has already called closeOutput in case of direct output
5422 return NO_ERROR;
5423 }
François Gaffie7e39df22022-04-26 12:48:49 +02005424 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005425 // While using a HwBridge, force reconsidering device only if not reusing an existing
5426 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005427 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005428 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5429 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5430 // Reconsider device only for cases:
5431 // 1 / Active Output
5432 // 2 / Inactive Output previously hosting HwBridge
5433 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5434 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5435 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305436 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005437 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5438 outputDesc->devices(),
5439 force,
5440 0,
5441 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005442 } else {
5443 return BAD_VALUE;
5444 }
5445 } else {
5446 return BAD_VALUE;
5447 }
5448 return NO_ERROR;
5449}
5450
5451status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5452 struct audio_patch *patches,
5453 unsigned int *generation)
5454{
François Gaffie53615e22015-03-19 09:24:12 +01005455 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005456 return BAD_VALUE;
5457 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005458 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005459 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005460}
5461
Eric Laurente1715a42014-05-20 11:30:42 -07005462status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005463{
Eric Laurente1715a42014-05-20 11:30:42 -07005464 ALOGV("setAudioPortConfig()");
5465
5466 if (config == NULL) {
5467 return BAD_VALUE;
5468 }
5469 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5470 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005471 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5472 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005473 }
5474
Eric Laurenta121f902014-06-03 13:32:54 -07005475 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005476 if (config->type == AUDIO_PORT_TYPE_MIX) {
5477 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005478 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005479 if (outputDesc == NULL) {
5480 return BAD_VALUE;
5481 }
Eric Laurent84c70242014-06-23 08:46:27 -07005482 ALOG_ASSERT(!outputDesc->isDuplicated(),
5483 "setAudioPortConfig() called on duplicated output %d",
5484 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005485 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005486 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005487 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005488 if (inputDesc == NULL) {
5489 return BAD_VALUE;
5490 }
Eric Laurenta121f902014-06-03 13:32:54 -07005491 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005492 } else {
5493 return BAD_VALUE;
5494 }
5495 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5496 sp<DeviceDescriptor> deviceDesc;
5497 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5498 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5499 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5500 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5501 } else {
5502 return BAD_VALUE;
5503 }
5504 if (deviceDesc == NULL) {
5505 return BAD_VALUE;
5506 }
Eric Laurenta121f902014-06-03 13:32:54 -07005507 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005508 } else {
5509 return BAD_VALUE;
5510 }
5511
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005512 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005513 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5514 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005515 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005516 audioPortConfig->toAudioPortConfig(&newConfig, config);
5517 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005518 }
Eric Laurenta121f902014-06-03 13:32:54 -07005519 if (status != NO_ERROR) {
5520 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005521 }
Eric Laurente1715a42014-05-20 11:30:42 -07005522
5523 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005524}
5525
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005526void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5527{
Eric Laurentd60560a2015-04-10 11:31:20 -07005528 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005529 clearAudioPatches(uid);
5530 clearSessionRoutes(uid);
5531}
5532
Eric Laurent6a94d692014-05-20 11:18:06 -07005533void AudioPolicyManager::clearAudioPatches(uid_t uid)
5534{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005535 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005536 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005537 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005538 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005539 }
5540 }
5541}
5542
François Gaffiec005e562018-11-06 15:04:49 +01005543void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005544{
François Gaffiec005e562018-11-06 15:04:49 +01005545 // Take the first attributes following the product strategy as it is used to retrieve the routed
5546 // device. All attributes wihin a strategy follows the same "routing strategy"
5547 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5548 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005549 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005550 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005551 for (size_t j = 0; j < mOutputs.size(); j++) {
5552 if (mOutputs.keyAt(j) == ouptutToSkip) {
5553 continue;
5554 }
5555 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005556 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005557 continue;
5558 }
5559 // If the default device for this strategy is on another output mix,
5560 // invalidate all tracks in this strategy to force re connection.
5561 // Otherwise select new device on the output mix.
5562 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005563 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005564 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005565 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5566 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5567 // If the device is using preferred mixer attributes, the output need to reopen
5568 // with default configuration when the new selected devices are different from
5569 // current routing devices.
5570 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5571 continue;
5572 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305573 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005574 }
5575 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005576 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005577}
5578
5579void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5580{
5581 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005582 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005583 for (size_t i = 0; i < mOutputs.size(); i++) {
5584 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005585 for (const auto& client : outputDesc->getClientIterable()) {
5586 if (client->hasPreferredDevice() && client->uid() == uid) {
5587 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005588 auto clientStrategy = client->strategy();
5589 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5590 end(affectedStrategies)) {
5591 continue;
5592 }
5593 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005594 }
5595 }
5596 }
5597 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005598 for (const auto& strategy : affectedStrategies) {
5599 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005600 }
5601
5602 // remove input routes associated with this uid
5603 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005604 for (size_t i = 0; i < mInputs.size(); i++) {
5605 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005606 for (const auto& client : inputDesc->getClientIterable()) {
5607 if (client->hasPreferredDevice() && client->uid() == uid) {
5608 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5609 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005610 }
5611 }
5612 }
5613 // reroute inputs if necessary
5614 SortedVector<audio_io_handle_t> inputsToClose;
5615 for (size_t i = 0; i < mInputs.size(); i++) {
5616 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005617 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005618 inputsToClose.add(inputDesc->mIoHandle);
5619 }
5620 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005621 for (const auto& input : inputsToClose) {
5622 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005623 }
5624}
5625
Eric Laurentd60560a2015-04-10 11:31:20 -07005626void AudioPolicyManager::clearAudioSources(uid_t uid)
5627{
5628 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005629 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5630 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005631 stopAudioSource(mAudioSources.keyAt(i));
5632 }
5633 }
5634}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005635
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005636status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5637 audio_io_handle_t *ioHandle,
5638 audio_devices_t *device)
5639{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005640 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5641 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005642 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005643 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5644 if (deviceDesc == nullptr) {
5645 return INVALID_OPERATION;
5646 }
5647 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005648
François Gaffiedf372692015-03-19 10:43:27 +01005649 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005650}
5651
Eric Laurentd60560a2015-04-10 11:31:20 -07005652status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005653 const audio_attributes_t *attributes,
5654 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005655 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005656{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005657 ALOGV("%s", __FUNCTION__);
5658 *portId = AUDIO_PORT_HANDLE_NONE;
5659
5660 if (source == NULL || attributes == NULL || portId == NULL) {
5661 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5662 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005663 return BAD_VALUE;
5664 }
5665
Eric Laurentd60560a2015-04-10 11:31:20 -07005666 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5667 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005668 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5669 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005670 return INVALID_OPERATION;
5671 }
5672
François Gaffie11d30102018-11-02 16:09:09 +01005673 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005674 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005675 String8(source->ext.device.address),
5676 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005677 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005678 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005679 return BAD_VALUE;
5680 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005681
jiabin4ef93452019-09-10 14:29:54 -07005682 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005683
François Gaffieaaac0fd2018-11-22 17:56:39 +01005684 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005685 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005686 mEngine->getStreamTypeForAttributes(*attributes),
5687 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005688 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005689
5690 status_t status = connectAudioSource(sourceDesc);
5691 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005692 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005693 }
5694 return status;
5695}
5696
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005697status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005698{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005699 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005700
5701 // make sure we only have one patch per source.
5702 disconnectAudioSource(sourceDesc);
5703
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005704 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005705 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5706 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5707 sourceDesc->srcDevice()->type(),
5708 String8(sourceDesc->srcDevice()->address().c_str()),
5709 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005710 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005711 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005712 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005713 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005714 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5715 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5716 return INVALID_OPERATION;
5717 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005718 PatchBuilder patchBuilder;
5719 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5720 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005721
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005722 return connectAudioSourceToSink(
5723 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005724}
5725
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005726status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005727{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005728 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5729 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005730 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005731 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005732 return BAD_VALUE;
5733 }
5734 status_t status = disconnectAudioSource(sourceDesc);
5735
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005736 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005737 return status;
5738}
5739
Andy Hung2ddee192015-12-18 17:34:44 -08005740status_t AudioPolicyManager::setMasterMono(bool mono)
5741{
5742 if (mMasterMono == mono) {
5743 return NO_ERROR;
5744 }
5745 mMasterMono = mono;
5746 // if enabling mono we close all offloaded devices, which will invalidate the
5747 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5748 // for recreating the new AudioTrack as non-offloaded PCM.
5749 //
5750 // If disabling mono, we leave all tracks as is: we don't know which clients
5751 // and tracks are able to be recreated as offloaded. The next "song" should
5752 // play back offloaded.
5753 if (mMasterMono) {
5754 Vector<audio_io_handle_t> offloaded;
5755 for (size_t i = 0; i < mOutputs.size(); ++i) {
5756 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5757 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5758 offloaded.push(desc->mIoHandle);
5759 }
5760 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005761 for (const auto& handle : offloaded) {
5762 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005763 }
5764 }
5765 // update master mono for all remaining outputs
5766 for (size_t i = 0; i < mOutputs.size(); ++i) {
5767 updateMono(mOutputs.keyAt(i));
5768 }
5769 return NO_ERROR;
5770}
5771
5772status_t AudioPolicyManager::getMasterMono(bool *mono)
5773{
5774 *mono = mMasterMono;
5775 return NO_ERROR;
5776}
5777
Eric Laurentac9cef52017-06-09 15:46:26 -07005778float AudioPolicyManager::getStreamVolumeDB(
5779 audio_stream_type_t stream, int index, audio_devices_t device)
5780{
jiabin9a3361e2019-10-01 09:38:30 -07005781 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005782}
5783
jiabin81772902018-04-02 17:52:27 -07005784status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5785 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005786 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005787{
Kriti Dang6537def2021-03-02 13:46:59 +01005788 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5789 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005790 return BAD_VALUE;
5791 }
Kriti Dang6537def2021-03-02 13:46:59 +01005792 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5793 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005794
5795 size_t formatsWritten = 0;
5796 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005797
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005798 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005799 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5800 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005801 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005802 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005803 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005804 bool formatEnabled = true;
5805 switch (forceUse) {
5806 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005807 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005808 break;
5809 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5810 formatEnabled = false;
5811 break;
5812 default: // AUTO or ALWAYS => true
5813 break;
jiabin81772902018-04-02 17:52:27 -07005814 }
5815 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5816 }
jiabin81772902018-04-02 17:52:27 -07005817 }
5818 return NO_ERROR;
5819}
5820
Kriti Dang6537def2021-03-02 13:46:59 +01005821status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5822 audio_format_t *surroundFormats) {
5823 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5824 return BAD_VALUE;
5825 }
5826 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5827 __func__, *numSurroundFormats, surroundFormats);
5828
5829 size_t formatsWritten = 0;
5830 size_t formatsMax = *numSurroundFormats;
5831 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5832
5833 // Return formats from all device profiles that have already been resolved by
5834 // checkOutputsForDevice().
5835 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5836 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5837 audio_devices_t deviceType = device->type();
5838 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5839 // returns formats reported by HDMI devices.
5840 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5841 continue;
5842 }
5843 // Formats reported by sink devices
5844 std::unordered_set<audio_format_t> formatset;
5845 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5846 formatset.insert(it->second.begin(), it->second.end());
5847 }
5848
5849 // Formats hard-coded in the in policy configuration file (if any).
5850 FormatVector encodedFormats = device->encodedFormats();
5851 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5852 // Filter the formats which are supported by the vendor hardware.
5853 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005854 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005855 formats.insert(*it);
5856 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005857 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005858 if (pair.second.count(*it) != 0) {
5859 formats.insert(pair.first);
5860 break;
5861 }
5862 }
5863 }
5864 }
5865 }
5866 *numSurroundFormats = formats.size();
5867 for (const auto& format: formats) {
5868 if (formatsWritten < formatsMax) {
5869 surroundFormats[formatsWritten++] = format;
5870 }
5871 }
5872 return NO_ERROR;
5873}
5874
jiabin81772902018-04-02 17:52:27 -07005875status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5876{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005877 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005878 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5879 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005880 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005881 return BAD_VALUE;
5882 }
5883
Mikhail Naganov100f0122018-11-29 11:22:16 -08005884 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5885 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005886 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005887 return INVALID_OPERATION;
5888 }
5889
Mikhail Naganov100f0122018-11-29 11:22:16 -08005890 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005891 return NO_ERROR;
5892 }
5893
Mikhail Naganov100f0122018-11-29 11:22:16 -08005894 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005895 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005896 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005897 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005898 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005899 }
5900 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005901 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005902 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005903 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005904 }
5905 }
5906
5907 sp<SwAudioOutputDescriptor> outputDesc;
5908 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005909 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5910 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005911 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5912 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005913 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005914 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005915 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5916 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5917 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005918 name.c_str(),
5919 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005920 if (status != NO_ERROR) {
5921 continue;
5922 }
5923 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5924 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5925 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005926 name.c_str(),
5927 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005928 profileUpdated |= (status == NO_ERROR);
5929 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005930 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005931 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005932 AUDIO_DEVICE_IN_HDMI);
5933 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5934 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005935 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005936 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005937 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5938 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5939 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005940 name.c_str(),
5941 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005942 if (status != NO_ERROR) {
5943 continue;
5944 }
5945 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5946 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5947 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005948 name.c_str(),
5949 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005950 profileUpdated |= (status == NO_ERROR);
5951 }
5952
jiabin81772902018-04-02 17:52:27 -07005953 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005954 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005955 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005956 }
5957
5958 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5959}
5960
Eric Laurent5ada82e2019-08-29 17:53:54 -07005961void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005962{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005963 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005964 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005965 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005966 }
5967}
5968
jiabin6012f912018-11-02 17:06:30 -07005969bool AudioPolicyManager::isHapticPlaybackSupported()
5970{
5971 for (const auto& hwModule : mHwModules) {
5972 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5973 for (const auto &outProfile : outputProfiles) {
5974 struct audio_port audioPort;
5975 outProfile->toAudioPort(&audioPort);
5976 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5977 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5978 return true;
5979 }
5980 }
5981 }
5982 }
5983 return false;
5984}
5985
Carter Hsu325a8eb2022-01-19 19:56:51 +08005986bool AudioPolicyManager::isUltrasoundSupported()
5987{
5988 bool hasUltrasoundOutput = false;
5989 bool hasUltrasoundInput = false;
5990 for (const auto& hwModule : mHwModules) {
5991 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5992 if (!hasUltrasoundOutput) {
5993 for (const auto &outProfile : outputProfiles) {
5994 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5995 hasUltrasoundOutput = true;
5996 break;
5997 }
5998 }
5999 }
6000
6001 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6002 if (!hasUltrasoundInput) {
6003 for (const auto &inputProfile : inputProfiles) {
6004 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
6005 hasUltrasoundInput = true;
6006 break;
6007 }
6008 }
6009 }
6010
6011 if (hasUltrasoundOutput && hasUltrasoundInput)
6012 return true;
6013 }
6014 return false;
6015}
6016
Atneya Nair698f5ef2022-12-15 16:15:09 -08006017bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
6018{
6019 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
6020 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
6021 for (const auto& hwModule : mHwModules) {
6022 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
6023 for (const auto &inputProfile : inputProfiles) {
6024 if ((inputProfile->getFlags() & mask) == mask) {
6025 return true;
6026 }
6027 }
6028 }
6029 return false;
6030}
6031
Eric Laurent8340e672019-11-06 11:01:08 -08006032bool AudioPolicyManager::isCallScreenModeSupported()
6033{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006034 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08006035}
6036
6037
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006038status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07006039{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006040 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006041 if (!sourceDesc->isConnected()) {
6042 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
6043 return NO_ERROR;
6044 }
François Gaffieafd4cea2019-11-18 15:50:22 +01006045 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
6046 if (swOutput != 0) {
6047 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08006048 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01006049 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006050 }
jiabinbce0c1d2020-10-05 11:20:18 -07006051 if (releaseOutput(sourceDesc->portId())) {
6052 // The output descriptor is reopened to query dynamic profiles. In that case, there is
6053 // no need to release audio patch here but just return NO_ERROR.
6054 return NO_ERROR;
6055 }
Eric Laurentd60560a2015-04-10 11:31:20 -07006056 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006057 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07006058 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006059 // close Hwoutput and remove from mHwOutputs
6060 } else {
6061 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
6062 }
6063 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006064 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02006065 sourceDesc->disconnect();
6066 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07006067}
6068
François Gaffiec005e562018-11-06 15:04:49 +01006069sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
6070 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07006071{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006072 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07006073 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006074 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07006075 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01006076 if (followsSameRouting(attr, sourceDesc->attributes()) &&
6077 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07006078 source = sourceDesc;
6079 break;
6080 }
6081 }
6082 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07006083}
6084
Eric Laurentb4f42a92022-01-17 17:37:31 +01006085bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006086 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006087 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006088{
6089 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
6090 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02006091 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006092 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006093 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6094 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6095 return false;
6096 }
6097 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6098 return false;
6099 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006100 }
6101
Eric Laurentd332bc82023-08-04 11:45:23 +02006102 // The caller can have the audio config criteria ignored by either passing a null ptr or
6103 // the AUDIO_CONFIG_INITIALIZER value.
6104 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006105 // some positional channel masks and PCM format and for stereo if low latency performance
6106 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006107
6108 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006109 static const bool stereo_spatialization_enabled =
6110 property_get_bool("ro.audio.stereo_spatialization_enabled", false);
Andy Hung481bfe32023-12-18 14:00:29 -08006111 const bool channel_mask_spatialized =
Nikhil Bhanu8f4ea772024-01-31 17:15:52 -08006112 (stereo_spatialization_enabled && com_android_media_audio_stereo_spatialization())
Andy Hung481bfe32023-12-18 14:00:29 -08006113 ? audio_channel_mask_contains_stereo(config->channel_mask)
6114 : audio_is_channel_mask_spatialized(config->channel_mask);
6115 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006116 return false;
6117 }
6118 if (!audio_is_linear_pcm(config->format)) {
6119 return false;
6120 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006121 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6122 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6123 return false;
6124 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006125 }
6126
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006127 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006128 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006129 if (profile == nullptr) {
6130 return false;
6131 }
6132
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006133 return true;
6134}
6135
Shunkai Yao57b93392024-04-26 04:12:21 +00006136// The Spatializer output is compatible with Haptic use cases if:
6137// 1. the Spatializer output thread supports Haptic, and format/sampleRate are same
6138// with client if client haptic channel bits were set, or
6139// 2. the Spatializer output thread does not support Haptic, and client did not ask haptic by
6140// including the haptic bits or creating the HapticGenerator effect for same session.
6141bool AudioPolicyManager::checkHapticCompatibilityOnSpatializerOutput(
6142 const audio_config_t* config, audio_session_t sessionId) const {
6143 const auto clientHapticChannel =
6144 audio_channel_count_from_out_mask(config->channel_mask & AUDIO_CHANNEL_HAPTIC_ALL);
6145 const auto threadOutputHapticChannel = audio_channel_count_from_out_mask(
6146 mSpatializerOutput->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
6147
6148 if (threadOutputHapticChannel) {
6149 // check format and sampleRate match if client haptic channel mask exist
6150 if (clientHapticChannel) {
6151 return mSpatializerOutput->getFormat() == config->format &&
6152 mSpatializerOutput->getSamplingRate() == config->sample_rate;
6153 }
6154 return true;
6155 } else {
6156 // in the case of the Spatializer output channel mask does not have haptic channel bits, it
6157 // means haptic use cases (either the client channelmask includes haptic bits, or created a
6158 // HapticGenerator effect for this session) are not supported.
6159 return clientHapticChannel == 0 &&
Shunkai Yaocb21feb2024-07-17 00:34:54 +00006160 !mEffects.hasOrphansForSession(sessionId, FX_IID_HAPTICGENERATOR);
Shunkai Yao57b93392024-04-26 04:12:21 +00006161 }
6162}
6163
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006164void AudioPolicyManager::checkVirtualizerClientRoutes() {
6165 std::set<audio_stream_type_t> streamsToInvalidate;
6166 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006167 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6168 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006169 audio_attributes_t attr = client->attributes();
6170 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6171 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6172 audio_config_base_t clientConfig = client->config();
6173 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006174 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006175 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006176 streamsToInvalidate.insert(client->stream());
6177 }
6178 }
6179 }
6180
jiabinc44b3462022-12-08 12:52:31 -08006181 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006182}
6183
Eric Laurente191d1b2022-04-15 11:59:25 +02006184
6185bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6186 const sp<SwAudioOutputDescriptor>& outputDesc) {
6187 if (outputDesc->isDuplicated()) {
6188 return false;
6189 }
6190 DeviceVector devices = outputDesc->supportedDevices();
6191 for (size_t i = 0; i < mOutputs.size(); i++) {
6192 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6193 if (desc == outputDesc || desc->isDuplicated()) {
6194 continue;
6195 }
6196 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6197 if (!sharedDevices.isEmpty()
6198 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6199 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6200 return false;
6201 }
6202 }
6203 return true;
6204}
6205
6206
Eric Laurentfa0f6742021-08-17 18:39:44 +02006207status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006208 const audio_attributes_t *attr,
6209 audio_io_handle_t *output) {
6210 *output = AUDIO_IO_HANDLE_NONE;
6211
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006212 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6213 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6214 audio_config_t *configPtr = nullptr;
6215 audio_config_t config;
6216 if (mixerConfig != nullptr) {
6217 config = audio_config_initializer(mixerConfig);
6218 configPtr = &config;
6219 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006220 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006221 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006222 return BAD_VALUE;
6223 }
6224
6225 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006226 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006227 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006228 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006229 return BAD_VALUE;
6230 }
6231
Eric Laurente191d1b2022-04-15 11:59:25 +02006232 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006233 for (size_t i = 0; i < mOutputs.size(); i++) {
6234 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006235 if (!desc->isDuplicated()
6236 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6237 spatializerOutputs.push_back(desc);
6238 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006239 }
6240 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006241 mSpatializerOutput.clear();
6242 bool outputsChanged = false;
6243 for (const auto& desc : spatializerOutputs) {
6244 if (desc->mProfile == profile
6245 && (configPtr == nullptr
6246 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6247 mSpatializerOutput = desc;
6248 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6249 } else {
6250 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6251 " and devices %s", __func__, desc->mIoHandle,
6252 configPtr != nullptr ? configPtr->channel_mask : 0,
6253 devices.toString().c_str());
6254 closeOutput(desc->mIoHandle);
6255 outputsChanged = true;
6256 }
Eric Laurent39095982021-08-24 18:29:27 +02006257 }
6258
Eric Laurente191d1b2022-04-15 11:59:25 +02006259 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006260 sp<SwAudioOutputDescriptor> desc =
6261 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006262 if (desc != nullptr) {
6263 mSpatializerOutput = desc;
6264 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006265 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006266 }
6267
6268 checkVirtualizerClientRoutes();
6269
Eric Laurente191d1b2022-04-15 11:59:25 +02006270 if (outputsChanged) {
6271 mPreviousOutputs = mOutputs;
6272 mpClientInterface->onAudioPortListUpdate();
6273 }
6274
6275 if (mSpatializerOutput == nullptr) {
6276 ALOGV("%s could not open spatializer output with requested config", __func__);
6277 return BAD_VALUE;
6278 }
Eric Laurent39095982021-08-24 18:29:27 +02006279 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006280 ALOGV("%s returning new spatializer output %d", __func__, *output);
6281 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006282}
6283
Eric Laurentfa0f6742021-08-17 18:39:44 +02006284status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6285 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006286 return INVALID_OPERATION;
6287 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006288 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006289 return BAD_VALUE;
6290 }
Eric Laurent39095982021-08-24 18:29:27 +02006291
Eric Laurente191d1b2022-04-15 11:59:25 +02006292 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6293 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6294 closeOutput(mSpatializerOutput->mIoHandle);
6295 //from now on mSpatializerOutput is null
6296 checkVirtualizerClientRoutes();
6297 }
Eric Laurent39095982021-08-24 18:29:27 +02006298
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006299 return NO_ERROR;
6300}
6301
Eric Laurente552edb2014-03-10 17:42:56 -07006302// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006303// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006304// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006305uint32_t AudioPolicyManager::nextAudioPortGeneration()
6306{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006307 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006308}
6309
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006310AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006311 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006312 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006313 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006314 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006315 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006316 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006317 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006318 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006319 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006320 mAudioPortGeneration(1),
6321 mBeaconMuteRefCount(0),
6322 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006323 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006324 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006325 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006326 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006327{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006328}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006329
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006330status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006331 if (mEngine == nullptr) {
6332 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006333 }
6334 mEngine->setObserver(this);
6335 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006336 if (status != NO_ERROR) {
6337 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6338 return status;
6339 }
François Gaffie2110e042015-03-24 08:41:51 +01006340
jiabin29230182023-04-04 21:02:36 +00006341 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6342 // at the end of this function.
6343 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006344 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6345 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6346
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006347 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006348 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006349 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006350
Eric Laurent3a4311c2014-03-17 12:00:47 -07006351 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006352 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6353 defaultOutputDevice == nullptr ||
6354 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6355 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6356 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006357 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006358 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006359 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006360
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006361 // Silence ALOGV statements
6362 property_set("log.tag." LOG_TAG, "D");
6363
Eric Laurente552edb2014-03-10 17:42:56 -07006364 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006365 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006366}
6367
Eric Laurente0720872014-03-11 09:30:41 -07006368AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006369{
Eric Laurente552edb2014-03-10 17:42:56 -07006370 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006371 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006372 }
6373 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006374 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006375 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006376 mAvailableOutputDevices.clear();
6377 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006378 mOutputs.clear();
6379 mInputs.clear();
6380 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006381 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006382 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006383}
6384
Eric Laurente0720872014-03-11 09:30:41 -07006385status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006386{
Eric Laurent87ffa392015-05-22 10:32:38 -07006387 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006388}
6389
Eric Laurente552edb2014-03-10 17:42:56 -07006390// ---
6391
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006392void AudioPolicyManager::onNewAudioModulesAvailable()
6393{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006394 DeviceVector newDevices;
6395 onNewAudioModulesAvailableInt(&newDevices);
6396 if (!newDevices.empty()) {
6397 nextAudioPortGeneration();
6398 mpClientInterface->onAudioPortListUpdate();
6399 }
6400}
6401
6402void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6403{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006404 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006405 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6406 continue;
6407 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006408 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006409 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6410 handle != AUDIO_MODULE_HANDLE_NONE) {
6411 hwModule->setHandle(handle);
6412 } else {
6413 ALOGW("could not load HW module %s", hwModule->getName());
6414 continue;
6415 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006416 }
6417 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006418 // open all output streams needed to access attached devices.
6419 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006420 // This also validates mAvailableOutputDevices list
6421 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6422 if (!outProfile->canOpenNewIo()) {
6423 ALOGE("Invalid Output profile max open count %u for profile %s",
6424 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6425 continue;
6426 }
6427 if (!outProfile->hasSupportedDevices()) {
6428 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6429 continue;
6430 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006431 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6432 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006433 mTtsOutputAvailable = true;
6434 }
6435
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006436 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006437 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006438 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006439 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6440 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006441 } else {
6442 // choose first device present in profile's SupportedDevices also part of
6443 // mAvailableOutputDevices.
6444 if (availProfileDevices.isEmpty()) {
6445 continue;
6446 }
6447 supportedDevice = availProfileDevices.itemAt(0);
6448 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006449 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006450 continue;
6451 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306452
6453 if (outProfile->isMmap() && !outProfile->hasDynamicAudioProfile()
6454 && availProfileDevices.areAllDevicesAttached()) {
6455 ALOGV("%s skip opening output for mmap profile %s", __func__,
6456 outProfile->getTagName().c_str());
6457 continue;
6458 }
6459
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006460 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6461 mpClientInterface);
6462 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006463 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6464 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006465 AUDIO_STREAM_DEFAULT,
6466 AUDIO_OUTPUT_FLAG_NONE, &output);
6467 if (status != NO_ERROR) {
6468 ALOGW("Cannot open output stream for devices %s on hw module %s",
6469 supportedDevice->toString().c_str(), hwModule->getName());
6470 continue;
6471 }
6472 for (const auto &device : availProfileDevices) {
6473 // give a valid ID to an attached device once confirmed it is reachable
6474 if (!device->isAttached()) {
6475 device->attach(hwModule);
6476 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006477 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006478 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006479 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6480 }
6481 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006482 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006483 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6484 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006485 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006486 }
Eric Laurent39095982021-08-24 18:29:27 +02006487 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006488 outputDesc->close();
6489 } else {
6490 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306491 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006492 DeviceVector(supportedDevice),
6493 true,
6494 0,
6495 NULL);
6496 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006497 }
6498 // open input streams needed to access attached devices to validate
6499 // mAvailableInputDevices list
6500 for (const auto& inProfile : hwModule->getInputProfiles()) {
6501 if (!inProfile->canOpenNewIo()) {
6502 ALOGE("Invalid Input profile max open count %u for profile %s",
6503 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6504 continue;
6505 }
6506 if (!inProfile->hasSupportedDevices()) {
6507 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6508 continue;
6509 }
6510 // chose first device present in profile's SupportedDevices also part of
6511 // available input devices
6512 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006513 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006514 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006515 ALOGV("%s: Input device list is empty! for profile %s",
6516 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006517 continue;
6518 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306519
6520 if (inProfile->isMmap() && !inProfile->hasDynamicAudioProfile()
6521 && availProfileDevices.areAllDevicesAttached()) {
6522 ALOGV("%s skip opening input for mmap profile %s", __func__,
6523 inProfile->getTagName().c_str());
6524 continue;
6525 }
6526
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006527 sp<AudioInputDescriptor> inputDesc =
6528 new AudioInputDescriptor(inProfile, mpClientInterface);
6529
6530 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6531 status_t status = inputDesc->open(nullptr,
6532 availProfileDevices.itemAt(0),
6533 AUDIO_SOURCE_MIC,
Mikhail Naganov08816472024-07-18 16:01:54 +00006534 (audio_input_flags_t) inProfile->getFlags(),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006535 &input);
6536 if (status != NO_ERROR) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306537 ALOGW("%s: Cannot open input stream for device %s for profile %s on hw module %s",
6538 __func__, availProfileDevices.toString().c_str(),
6539 inProfile->getTagName().c_str(), hwModule->getName());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006540 continue;
6541 }
6542 for (const auto &device : availProfileDevices) {
6543 // give a valid ID to an attached device once confirmed it is reachable
6544 if (!device->isAttached()) {
6545 device->attach(hwModule);
6546 device->importAudioPortAndPickAudioProfile(inProfile, true);
6547 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006548 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006549 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6550 }
6551 }
6552 inputDesc->close();
6553 }
6554 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006555
6556 // Check if spatializer outputs can be closed until used.
6557 // mOutputs vector never contains duplicated outputs at this point.
6558 std::vector<audio_io_handle_t> outputsClosed;
6559 for (size_t i = 0; i < mOutputs.size(); i++) {
6560 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6561 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6562 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6563 outputsClosed.push_back(desc->mIoHandle);
Eric Laurentccc19632024-05-03 20:22:49 +00006564 nextAudioPortGeneration();
6565 ssize_t index = mAudioPatches.indexOfKey(desc->getPatchHandle());
6566 if (index >= 0) {
6567 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
6568 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6569 patchDesc->getAfHandle(), 0);
6570 mAudioPatches.removeItemsAt(index);
6571 mpClientInterface->onAudioPatchListUpdate();
6572 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006573 desc->close();
6574 }
6575 }
6576 for (auto output : outputsClosed) {
6577 removeOutput(output);
6578 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006579}
6580
Eric Laurent98e38192018-02-15 18:31:53 -08006581void AudioPolicyManager::addOutput(audio_io_handle_t output,
6582 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006583{
Eric Laurent1c333e22014-05-20 10:48:17 -07006584 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006585 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006586 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006587 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006588 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006589}
6590
François Gaffie53615e22015-03-19 09:24:12 +01006591void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6592{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006593 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6594 ALOGV("%s: removing primary output", __func__);
6595 mPrimaryOutput = nullptr;
6596 }
François Gaffie53615e22015-03-19 09:24:12 +01006597 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006598 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006599}
6600
Eric Laurent98e38192018-02-15 18:31:53 -08006601void AudioPolicyManager::addInput(audio_io_handle_t input,
6602 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006603{
Eric Laurent1c333e22014-05-20 10:48:17 -07006604 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006605 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006606}
Eric Laurente552edb2014-03-10 17:42:56 -07006607
François Gaffie11d30102018-11-02 16:09:09 +01006608status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006609 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006610 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006611{
François Gaffie11d30102018-11-02 16:09:09 +01006612 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006613 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006614 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006615
François Gaffie11d30102018-11-02 16:09:09 +01006616 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006617 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006618 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006619 }
Eric Laurente552edb2014-03-10 17:42:56 -07006620
Eric Laurent3b73df72014-03-11 09:06:29 -07006621 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006622 // first call getAudioPort to get the supported attributes from the HAL
6623 struct audio_port_v7 port = {};
6624 device->toAudioPort(&port);
6625 status_t status = mpClientInterface->getAudioPort(&port);
6626 if (status == NO_ERROR) {
6627 device->importAudioPort(port);
6628 }
6629
6630 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006631 for (size_t i = 0; i < mOutputs.size(); i++) {
6632 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006633 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006634 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006635 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6636 mOutputs.keyAt(i), device->toString().c_str());
6637 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006638 }
6639 }
6640 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006641 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006642 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006643 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6644 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006645 if (profile->supportsDevice(device)) {
6646 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306647 ALOGV("%s(): adding profile %s from module %s",
6648 __func__, profile->getTagName().c_str(), hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006649 }
6650 }
6651 }
6652
Eric Laurent7b279bb2015-12-14 10:18:23 -08006653 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006654
Eric Laurente552edb2014-03-10 17:42:56 -07006655 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006656 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006657 return BAD_VALUE;
6658 }
6659
6660 // open outputs for matching profiles if needed. Direct outputs are also opened to
6661 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6662 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006663 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006664
6665 // nothing to do if one output is already opened for this profile
6666 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006667 for (j = 0; j < outputs.size(); j++) {
6668 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006669 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006670 // matching profile: save the sample rates, format and channel masks supported
6671 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006672 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006673 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006674 }
Eric Laurente552edb2014-03-10 17:42:56 -07006675 break;
6676 }
6677 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006678 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006679 continue;
6680 }
Jaideep Sharma44824a22024-06-18 16:32:34 +05306681 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6682 ALOGV("%s skip opening output for mmap profile %s",
6683 __func__, profile->getTagName().c_str());
6684 continue;
6685 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006686 if (!profile->canOpenNewIo()) {
6687 ALOGW("Max Output number %u already opened for this profile %s",
6688 profile->maxOpenCount, profile->getTagName().c_str());
6689 continue;
6690 }
6691
Eric Laurent83efe1c2017-07-09 16:51:08 -07006692 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00006693 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006694 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6695 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006696 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006697 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006698 profiles.removeAt(profile_index);
6699 profile_index--;
6700 } else {
6701 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006702 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006703 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006704 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6705 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006706 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006707 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006708
François Gaffie11d30102018-11-02 16:09:09 +01006709 if (device_distinguishes_on_address(deviceType)) {
6710 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6711 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306712 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6713 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006714 }
Eric Laurente552edb2014-03-10 17:42:56 -07006715 ALOGV("checkOutputsForDevice(): adding output %d", output);
6716 }
6717 }
6718
6719 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006720 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006721 return BAD_VALUE;
6722 }
Eric Laurentd4692962014-05-05 18:13:44 -07006723 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006724 // check if one opened output is not needed any more after disconnecting one device
6725 for (size_t i = 0; i < mOutputs.size(); i++) {
6726 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006727 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006728 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006729 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006730 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006731 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006732 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006733 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6734 mOutputs.keyAt(i));
6735 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006736 }
Eric Laurente552edb2014-03-10 17:42:56 -07006737 }
6738 }
Eric Laurentd4692962014-05-05 18:13:44 -07006739 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006740 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006741 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6742 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006743 if (!profile->supportsDevice(device)) {
6744 continue;
6745 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306746 ALOGV("%s(): clearing direct output profile %s on module %s",
6747 __func__, profile->getTagName().c_str(), hwModule->getName());
jiabinbce0c1d2020-10-05 11:20:18 -07006748 profile->clearAudioProfiles();
6749 if (!profile->hasDynamicAudioProfile()) {
6750 continue;
6751 }
6752 // When a device is disconnected, if there is an IOProfile that contains dynamic
6753 // profiles and supports the disconnected device, call getAudioPort to repopulate
6754 // the capabilities of the devices that is supported by the IOProfile.
6755 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6756 if (supportedDevice == device ||
6757 !mAvailableOutputDevices.contains(supportedDevice)) {
6758 continue;
6759 }
6760 struct audio_port_v7 port;
6761 supportedDevice->toAudioPort(&port);
6762 status_t status = mpClientInterface->getAudioPort(&port);
6763 if (status == NO_ERROR) {
6764 supportedDevice->importAudioPort(port);
6765 }
Eric Laurente552edb2014-03-10 17:42:56 -07006766 }
6767 }
6768 }
6769 }
6770 return NO_ERROR;
6771}
6772
François Gaffie11d30102018-11-02 16:09:09 +01006773status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006774 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006775{
François Gaffie11d30102018-11-02 16:09:09 +01006776 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006777 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006778 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006779 }
6780
Eric Laurentd4692962014-05-05 18:13:44 -07006781 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006782 sp<AudioInputDescriptor> desc;
6783
jiabinbf5f4262023-04-12 21:48:34 +00006784 // 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
Eric Laurent0dd51852019-04-19 18:18:58 -07006792 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006793 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006794 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006795 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006796 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006797 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006798 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006799
François Gaffie11d30102018-11-02 16:09:09 +01006800 if (profile->supportsDevice(device)) {
6801 profiles.add(profile);
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306802 ALOGV("%s : adding profile %s from module %s", __func__,
6803 profile->getTagName().c_str(), hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006804 }
6805 }
6806 }
6807
Eric Laurent0dd51852019-04-19 18:18:58 -07006808 if (profiles.isEmpty()) {
6809 ALOGW("%s: No input profile available for device %s",
6810 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006811 return BAD_VALUE;
6812 }
6813
6814 // open inputs for matching profiles if needed. Direct inputs are also opened to
6815 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6816 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6817
Eric Laurent1c333e22014-05-20 10:48:17 -07006818 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006819
Eric Laurentd4692962014-05-05 18:13:44 -07006820 // nothing to do if one input is already opened for this profile
6821 size_t input_index;
6822 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6823 desc = mInputs.valueAt(input_index);
6824 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006825 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006826 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006827 }
Eric Laurentd4692962014-05-05 18:13:44 -07006828 break;
6829 }
6830 }
6831 if (input_index != mInputs.size()) {
6832 continue;
6833 }
6834
Jaideep Sharma44824a22024-06-18 16:32:34 +05306835 if (profile->isMmap() && !profile->hasDynamicAudioProfile()) {
6836 ALOGV("%s skip opening input for mmap profile %s",
6837 __func__, profile->getTagName().c_str());
6838 continue;
6839 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08006840 if (!profile->canOpenNewIo()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306841 ALOGW("%s Max Input number %u already opened for this profile %s",
6842 __func__, profile->maxOpenCount, profile->getTagName().c_str());
Eric Laurent3974e3b2017-12-07 17:58:43 -08006843 continue;
6844 }
6845
Eric Laurentfe231122017-11-17 17:48:06 -08006846 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006847 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306848 ALOGV("%s opening input for profile %s", __func__, profile->getTagName().c_str());
Mikhail Naganov08816472024-07-18 16:01:54 +00006849 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC,
6850 (audio_input_flags_t) profile->getFlags(), &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006851
Eric Laurentcf2c0212014-07-25 16:20:43 -07006852 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006853 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006854 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006855 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006856 mpClientInterface->setParameters(input, String8(param));
6857 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006858 }
jiabin12537fc2023-10-12 17:56:08 +00006859 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006860 if (!profile->hasValidAudioProfile()) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306861 ALOGW("%s direct input missing param for profile %s", __func__,
6862 profile->getTagName().c_str());
Eric Laurentfe231122017-11-17 17:48:06 -08006863 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006864 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006865 }
6866
Eric Laurent0dd51852019-04-19 18:18:58 -07006867 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006868 addInput(input, desc);
6869 }
6870 } // endif input != 0
6871
Eric Laurentcf2c0212014-07-25 16:20:43 -07006872 if (input == AUDIO_IO_HANDLE_NONE) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306873 ALOGW("%s could not open input for device %s on profile %s", __func__,
6874 device->toString().c_str(), profile->getTagName().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006875 profiles.removeAt(profile_index);
6876 profile_index--;
6877 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006878 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006879 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006880 }
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306881 ALOGV("%s: adding input %d for profile %s", __func__,
6882 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006883
6884 if (checkCloseInput(desc)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306885 ALOGV("%s: closing input %d for profile %s", __func__,
6886 input, profile->getTagName().c_str());
Mikhail Naganov2b61ab52024-05-30 16:56:25 -07006887 closeInput(input);
6888 }
Eric Laurentd4692962014-05-05 18:13:44 -07006889 }
6890 } // end scan profiles
6891
6892 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006893 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006894 return BAD_VALUE;
6895 }
6896 } else {
6897 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006898 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006899 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006900 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006901 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006902 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006903 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006904 if (profile->supportsDevice(device)) {
Jaideep Sharmac1857d42024-06-18 17:46:45 +05306905 ALOGV("%s: clearing direct input profile %s on module %s", __func__,
6906 profile->getTagName().c_str(), hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006907 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006908 }
6909 }
6910 }
6911 } // end disconnect
6912
6913 return NO_ERROR;
6914}
6915
6916
Eric Laurente0720872014-03-11 09:30:41 -07006917void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006918{
6919 ALOGV("closeOutput(%d)", output);
6920
François Gaffie1c878552018-11-22 16:53:21 +01006921 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6922 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006923 ALOGW("closeOutput() unknown output %d", output);
6924 return;
6925 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006926 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006927 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006928
Eric Laurente552edb2014-03-10 17:42:56 -07006929 // look for duplicated outputs connected to the output being removed.
6930 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006931 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6932 if (dupOutput->isDuplicated() &&
6933 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6934 sp<SwAudioOutputDescriptor> remainingOutput =
6935 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006936 // As all active tracks on duplicated output will be deleted,
6937 // and as they were also referenced on the other output, the reference
6938 // count for their stream type must be adjusted accordingly on
6939 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006940 const bool wasActive = remainingOutput->isActive();
6941 // Note: no-op on the closing output where all clients has already been set inactive
6942 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006943 // stop() will be a no op if the output is still active but is needed in case all
6944 // active streams refcounts where cleared above
6945 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006946 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006947 }
Eric Laurente552edb2014-03-10 17:42:56 -07006948 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6949 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6950
6951 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006952 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006953 }
6954 }
6955
Eric Laurent05b90f82014-08-27 15:32:29 -07006956 nextAudioPortGeneration();
6957
François Gaffie1c878552018-11-22 16:53:21 +01006958 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006959 if (index >= 0) {
6960 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006961 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6962 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006963 mAudioPatches.removeItemsAt(index);
6964 mpClientInterface->onAudioPatchListUpdate();
6965 }
6966
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006967 if (closingOutputWasActive) {
6968 closingOutput->stop();
6969 }
François Gaffie1c878552018-11-22 16:53:21 +01006970 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006971 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6972 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6973 for (const auto device : closingOutput->devices()) {
6974 device->setPreferredConfig(nullptr);
6975 }
6976 }
Eric Laurente552edb2014-03-10 17:42:56 -07006977
François Gaffie53615e22015-03-19 09:24:12 +01006978 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006979 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006980 if (closingOutput == mSpatializerOutput) {
6981 mSpatializerOutput.clear();
6982 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006983
6984 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6985 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006986 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006987 bool directOutputOpen = false;
6988 for (size_t i = 0; i < mOutputs.size(); i++) {
6989 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6990 directOutputOpen = true;
6991 break;
6992 }
6993 }
6994 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006995 ALOGV("no direct outputs open, reset MSD patches");
6996 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6997 // how output devices for patching are resolved. Avoid by caching and reusing the
6998 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6999 // devices to patch to. This may be complicated by the fact that devices may become
7000 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007001 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10007002 }
7003 }
Eric Laurent05b90f82014-08-27 15:32:29 -07007004}
7005
7006void AudioPolicyManager::closeInput(audio_io_handle_t input)
7007{
7008 ALOGV("closeInput(%d)", input);
7009
7010 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
7011 if (inputDesc == NULL) {
7012 ALOGW("closeInput() unknown input %d", input);
7013 return;
7014 }
7015
Eric Laurent6a94d692014-05-20 11:18:06 -07007016 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07007017
François Gaffie11d30102018-11-02 16:09:09 +01007018 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007019 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07007020 if (index >= 0) {
7021 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007022 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
7023 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07007024 mAudioPatches.removeItemsAt(index);
7025 mpClientInterface->onAudioPatchListUpdate();
7026 }
7027
François Gaffie6ebbce02023-07-19 13:27:53 +02007028 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08007029 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07007030 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007031
François Gaffie11d30102018-11-02 16:09:09 +01007032 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
7033 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007034 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07007035 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07007036 }
Eric Laurente552edb2014-03-10 17:42:56 -07007037}
7038
François Gaffie11d30102018-11-02 16:09:09 +01007039SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
7040 const DeviceVector &devices,
7041 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07007042{
7043 SortedVector<audio_io_handle_t> outputs;
7044
François Gaffie11d30102018-11-02 16:09:09 +01007045 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07007046 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01007047 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07007048 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01007049 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08007050 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07007051 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01007052 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07007053 outputs.add(openOutputs.keyAt(i));
7054 }
7055 }
7056 return outputs;
7057}
7058
Mikhail Naganov37977152018-07-11 15:54:44 -07007059void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
7060{
7061 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
7062 // output is suspended before any tracks are moved to it
7063 checkA2dpSuspend();
7064 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08007065 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007066 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07007067 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00007068 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11007069 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
7070 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
7071 // configuration changes will ultimately be rerouted correctly. We can still avoid
7072 // unnecessary rerouting by caching and reusing the arguments to
7073 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
7074 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11007075 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11007076 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07007077 // an event that changed routing likely occurred, inform upper layers
7078 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07007079}
7080
François Gaffiec005e562018-11-06 15:04:49 +01007081bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
7082 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07007083{
François Gaffiec005e562018-11-06 15:04:49 +01007084 return mEngine->getProductStrategyForAttributes(lAttr) ==
7085 mEngine->getProductStrategyForAttributes(rAttr);
7086}
7087
Francois Gaffieff1eb522020-05-06 18:37:04 +02007088void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
7089{
7090 for (size_t i = 0; i < mAudioSources.size(); i++) {
7091 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7092 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02007093 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007094 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02007095 connectAudioSource(sourceDesc);
7096 }
7097 }
7098}
7099
7100void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
7101{
7102 for (size_t i = 0; i < mAudioSources.size(); i++) {
7103 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
7104 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
7105 && sourceDesc->swOutput().promote()->mIoHandle == output) {
7106 disconnectAudioSource(sourceDesc);
7107 }
7108 }
7109}
7110
François Gaffiec005e562018-11-06 15:04:49 +01007111void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
7112{
7113 auto psId = mEngine->getProductStrategyForAttributes(attr);
7114
7115 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
7116 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07007117
François Gaffie11d30102018-11-02 16:09:09 +01007118 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
7119 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07007120
Eric Laurentc209fe42020-06-05 18:11:23 -07007121 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007122 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01007123 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07007124 // take into account dynamic audio policies related changes: if a client is now associated
7125 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01007126 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007127 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
7128 if (desc->isDuplicated()) {
7129 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007130 }
Eric Laurentc209fe42020-06-05 18:11:23 -07007131 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
7132 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
7133 continue;
7134 }
7135 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007136 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007137 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7138 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
7139 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07007140 if (status != OK) {
7141 continue;
7142 }
yucliuf4de36d2020-09-14 14:57:56 -07007143 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01007144 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07007145 maxLatency = desc->latency();
7146 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007147 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07007148 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08007149 }
7150 }
7151
Eric Laurent56ed8842022-11-15 16:04:41 +01007152 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007153 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
7154 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07007155 for (audio_io_handle_t srcOut : srcOutputs) {
7156 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07007157 if (desc == nullptr) continue;
7158
7159 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07007160 maxLatency = desc->latency();
7161 }
Eric Laurentaa02db82019-09-05 17:31:49 -07007162
Eric Laurent56ed8842022-11-15 16:04:41 +01007163 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07007164 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007165 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007166 // a client on a non direct outputs has necessarily a linear PCM format
7167 // so we can call selectOutput() safely
7168 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7169 client->flags(),
7170 client->config().format,
7171 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007172 client->config().sample_rate,
7173 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007174 if (newOutput != srcOut) {
7175 invalidate = true;
7176 break;
7177 }
7178 } else {
7179 sp<IOProfile> profile = getProfileForOutput(newDevices,
7180 client->config().sample_rate,
7181 client->config().format,
7182 client->config().channel_mask,
7183 client->flags(),
7184 true /* directOnly */);
7185 if (profile != desc->mProfile) {
7186 invalidate = true;
7187 break;
7188 }
7189 }
7190 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007191 // mute strategy while moving tracks from one output to another
7192 if (invalidate) {
7193 invalidatedOutputs.push_back(desc);
7194 if (desc->isStrategyActive(psId)) {
7195 setStrategyMute(psId, true, desc);
7196 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7197 newDevices.types());
7198 }
Eric Laurente552edb2014-03-10 17:42:56 -07007199 }
François Gaffiec005e562018-11-06 15:04:49 +01007200 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007201 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007202 connectAudioSource(source);
7203 }
Eric Laurente552edb2014-03-10 17:42:56 -07007204 }
7205
Eric Laurent56ed8842022-11-15 16:04:41 +01007206 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7207 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7208 std::to_string(srcOutputs[0]).c_str(),
7209 std::to_string(dstOutputs[0]).c_str());
7210
François Gaffiec005e562018-11-06 15:04:49 +01007211 // Move effects associated to this stream from previous output to new output
7212 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007213 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007214 }
François Gaffiec005e562018-11-06 15:04:49 +01007215 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007216 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007217 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007218 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007219 desc->setTracksInvalidatedStatusByStrategy(psId);
7220 }
Eric Laurente552edb2014-03-10 17:42:56 -07007221 }
7222 }
7223}
7224
Eric Laurente0720872014-03-11 09:30:41 -07007225void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007226{
François Gaffiec005e562018-11-06 15:04:49 +01007227 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7228 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7229 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007230 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007231 }
Eric Laurente552edb2014-03-10 17:42:56 -07007232}
7233
Kevin Rocard153f92d2018-12-18 18:33:28 -08007234void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007235 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007236 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007237 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007238 for (size_t i = 0; i < mOutputs.size(); i++) {
7239 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7240 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007241 sp<AudioPolicyMix> primaryMix;
7242 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007243 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007244 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7245 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7246 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007247 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7248 for (auto &secondaryMix : secondaryMixes) {
7249 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7250 if (outputDesc != nullptr &&
7251 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7252 secondaryDescs.push_back(outputDesc);
7253 }
7254 }
7255
jiabinc44b3462022-12-08 12:52:31 -08007256 if (status != OK &&
7257 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7258 // When it failed to query secondary output, only invalidate the client that is not
7259 // MMAP. The reason is that MMAP stream will not support secondary output.
7260 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007261 } else if (!std::equal(
7262 client->getSecondaryOutputs().begin(),
7263 client->getSecondaryOutputs().end(),
7264 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007265 if (!audio_is_linear_pcm(client->config().format)) {
7266 // If the format is not PCM, the tracks should be invalidated to get correct
7267 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007268 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007269 } else {
7270 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7271 std::vector<audio_io_handle_t> secondaryOutputIds;
7272 for (const auto &secondaryDesc: secondaryDescs) {
7273 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7274 weakSecondaryDescs.push_back(secondaryDesc);
7275 }
7276 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7277 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007278 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007279 }
7280 }
7281 }
jiabin10a03f12021-05-07 23:46:28 +00007282 if (!trackSecondaryOutputs.empty()) {
7283 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7284 }
jiabinc44b3462022-12-08 12:52:31 -08007285 if (!clientsToInvalidate.empty()) {
7286 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7287 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007288 }
7289}
7290
Eric Laurent2517af32020-11-25 15:31:27 +01007291bool AudioPolicyManager::isScoRequestedForComm() const {
7292 AudioDeviceTypeAddrVector devices;
7293 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7294 for (const auto &device : devices) {
7295 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7296 return true;
7297 }
7298 }
7299 return false;
7300}
7301
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007302bool AudioPolicyManager::isHearingAidUsedForComm() const {
7303 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7304 true /*fromCache*/);
7305 for (const auto &device : devices) {
7306 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7307 return true;
7308 }
7309 }
7310 return false;
7311}
7312
7313
Eric Laurente0720872014-03-11 09:30:41 -07007314void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007315{
François Gaffie53615e22015-03-19 09:24:12 +01007316 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007317 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007318 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007319 return;
7320 }
7321
Eric Laurent3a4311c2014-03-17 12:00:47 -07007322 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007323 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7324 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007325 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007326
7327 // if suspended, restore A2DP output if:
7328 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007329 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007330 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007331 //
Eric Laurentf732e072016-08-03 19:30:28 -07007332 // if not suspended, suspend A2DP output if:
7333 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007334 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007335 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007336 //
7337 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007338 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007339 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007340 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007341 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007342
7343 mpClientInterface->restoreOutput(a2dpOutput);
7344 mA2dpSuspended = false;
7345 }
7346 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007347 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007348 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007349 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007350 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007351
7352 mpClientInterface->suspendOutput(a2dpOutput);
7353 mA2dpSuspended = true;
7354 }
7355 }
7356}
7357
François Gaffie11d30102018-11-02 16:09:09 +01007358DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7359 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007360{
François Gaffiedb1755b2023-09-01 11:50:35 +02007361 if (outputDesc == nullptr) {
7362 return DeviceVector{};
7363 }
François Gaffie11d30102018-11-02 16:09:09 +01007364
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007365 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007366 if (index >= 0) {
7367 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007368 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007369 ALOGV("%s device %s forced by patch %d", __func__,
7370 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7371 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007372 }
7373 }
7374
Dean Wheatley514b4312020-06-17 21:45:00 +10007375 // Do not retrieve engine device for outputs through MSD
7376 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7377 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7378 return outputDesc->devices();
7379 }
7380
Eric Laurent97ac8712018-07-27 18:59:02 -07007381 // Honor explicit routing requests only if no client using default routing is active on this
7382 // input: a specific app can not force routing for other apps by setting a preferred device.
7383 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007384 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007385 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007386 if (device != nullptr) {
7387 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007388 }
7389
François Gaffiea807ef92018-11-05 10:44:33 +01007390 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7391 // of setForceUse / Default Bus device here
7392 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7393 if (device != nullptr) {
7394 return DeviceVector(device);
7395 }
7396
François Gaffiedb1755b2023-09-01 11:50:35 +02007397 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007398 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7399 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307400 auto hasStreamActive = [&](auto stream) {
7401 return hasStream(streams, stream) && isStreamActive(stream, 0);
7402 };
Eric Laurent484e9272018-06-07 17:29:23 -07007403
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307404 auto doGetOutputDevicesForVoice = [&]() {
7405 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007406 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307407 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007408 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7409 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307410 };
7411
7412 // With low-latency playing on speaker, music on WFD, when the first low-latency
7413 // output is stopped, getNewOutputDevices checks for a product strategy
7414 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007415 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307416 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7417 // stream is associated to the output descriptor.
7418 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7419 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7420 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7421 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007422 // Retrieval of devices for voice DL is done on primary output profile, cannot
7423 // check the route (would force modifying configuration file for this profile)
jiangyao94780942024-03-05 10:43:14 +08007424 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
François Gaffiec005e562018-11-06 15:04:49 +01007425 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7426 break;
7427 }
Eric Laurente552edb2014-03-10 17:42:56 -07007428 }
François Gaffiec005e562018-11-06 15:04:49 +01007429 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007430 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007431}
7432
François Gaffie11d30102018-11-02 16:09:09 +01007433sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7434 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007435{
François Gaffie11d30102018-11-02 16:09:09 +01007436 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007437
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007438 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007439 if (index >= 0) {
7440 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007441 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007442 ALOGV("getNewInputDevice() device %s forced by patch %d",
7443 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7444 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007445 }
7446 }
7447
Eric Laurent97ac8712018-07-27 18:59:02 -07007448 // Honor explicit routing requests only if no client using default routing is active on this
7449 // input: a specific app can not force routing for other apps by setting a preferred device.
7450 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007451 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7452 if (device != nullptr) {
7453 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007454 }
7455
Eric Laurentdc95a252018-04-12 12:46:56 -07007456 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007457 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007458 audio_attributes_t attributes;
7459 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007460 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007461 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7462 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007463 attributes = topClient->attributes();
7464 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007465 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007466 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007467 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7468 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007469 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007470 }
7471
Francois Gaffie716e1432019-01-14 16:58:59 +01007472 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7473 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007474 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007475 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007476 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007477 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007478
Eric Laurente552edb2014-03-10 17:42:56 -07007479 return device;
7480}
7481
Eric Laurent794fde22016-03-11 09:50:45 -08007482bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7483 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007484 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007485}
7486
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007487status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007488 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007489 if (devices == nullptr) {
7490 return BAD_VALUE;
7491 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007492
Andy Hung6d23c0f2022-02-16 09:37:15 -08007493 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007494 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7495 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007496 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007497 for (const auto& device : curDevices) {
7498 devices->push_back(device->getDeviceTypeAddr());
7499 }
7500 return NO_ERROR;
7501}
7502
Eric Laurente0720872014-03-11 09:30:41 -07007503void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007504 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007505 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007506 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007507 updateDevicesAndOutputs();
7508 break;
7509 default:
7510 break;
7511 }
7512}
7513
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007514uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007515
7516 // skip beacon mute management if a dedicated TTS output is available
7517 if (mTtsOutputAvailable) {
7518 return 0;
7519 }
7520
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007521 switch(event) {
7522 case STARTING_OUTPUT:
7523 mBeaconMuteRefCount++;
7524 break;
7525 case STOPPING_OUTPUT:
7526 if (mBeaconMuteRefCount > 0) {
7527 mBeaconMuteRefCount--;
7528 }
7529 break;
7530 case STARTING_BEACON:
7531 mBeaconPlayingRefCount++;
7532 break;
7533 case STOPPING_BEACON:
7534 if (mBeaconPlayingRefCount > 0) {
7535 mBeaconPlayingRefCount--;
7536 }
7537 break;
7538 }
7539
7540 if (mBeaconMuteRefCount > 0) {
7541 // any playback causes beacon to be muted
7542 return setBeaconMute(true);
7543 } else {
7544 // no other playback: unmute when beacon starts playing, mute when it stops
7545 return setBeaconMute(mBeaconPlayingRefCount == 0);
7546 }
7547}
7548
7549uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7550 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7551 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7552 // keep track of muted state to avoid repeating mute/unmute operations
7553 if (mBeaconMuted != mute) {
7554 // mute/unmute AUDIO_STREAM_TTS on all outputs
7555 ALOGV("\t muting %d", mute);
7556 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007557 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7558 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7559 ALOGV("\t no tts volume source available");
7560 return 0;
7561 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007562 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007563 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007564 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007565 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007566 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007567 maxLatency = latency;
7568 }
7569 }
7570 mBeaconMuted = mute;
7571 return maxLatency;
7572 }
7573 return 0;
7574}
7575
Eric Laurente0720872014-03-11 09:30:41 -07007576void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007577{
François Gaffiec005e562018-11-06 15:04:49 +01007578 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007579 mPreviousOutputs = mOutputs;
7580}
7581
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007582uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007583 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007584 uint32_t delayMs)
7585{
7586 // mute/unmute strategies using an incompatible device combination
7587 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7588 // if unmuting, unmute only after the specified delay
7589 if (outputDesc->isDuplicated()) {
7590 return 0;
7591 }
7592
7593 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007594 DeviceVector devices = outputDesc->devices();
7595 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007596
François Gaffiec005e562018-11-06 15:04:49 +01007597 auto productStrategies = mEngine->getOrderedProductStrategies();
7598 for (const auto &productStrategy : productStrategies) {
7599 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7600 DeviceVector curDevices =
7601 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7602 curDevices = curDevices.filter(outputDesc->supportedDevices());
7603 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007604 bool doMute = false;
7605
François Gaffiec005e562018-11-06 15:04:49 +01007606 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007607 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007608 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7609 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007610 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007611 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007612 }
Eric Laurent99401132014-05-07 19:48:15 -07007613 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007614 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007615 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007616 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007617 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007618 continue;
7619 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307620 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007621 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7622 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7623 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007624 if (mute) {
7625 // FIXME: should not need to double latency if volume could be applied
7626 // immediately by the audioflinger mixer. We must account for the delay
7627 // between now and the next time the audioflinger thread for this output
7628 // will process a buffer (which corresponds to one buffer size,
7629 // usually 1/2 or 1/4 of the latency).
7630 if (muteWaitMs < desc->latency() * 2) {
7631 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007632 }
7633 }
7634 }
7635 }
7636 }
7637 }
7638
Eric Laurent99401132014-05-07 19:48:15 -07007639 // temporary mute output if device selection changes to avoid volume bursts due to
7640 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007641 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007642 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007643
Eric Laurentdc462862016-07-19 12:29:53 -07007644 if (muteWaitMs < tempMuteWaitMs) {
7645 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007646 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007647
7648 // If recommended duration is defined, replace temporary mute duration to avoid
7649 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7650 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7651 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7652 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7653 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7654
François Gaffieaaac0fd2018-11-22 17:56:39 +01007655 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7656 // make sure that we do not start the temporary mute period too early in case of
7657 // delayed device change
7658 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7659 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007660 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007661 }
7662 }
7663
Eric Laurente552edb2014-03-10 17:42:56 -07007664 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7665 if (muteWaitMs > delayMs) {
7666 muteWaitMs -= delayMs;
7667 usleep(muteWaitMs * 1000);
7668 return muteWaitMs;
7669 }
7670 return 0;
7671}
7672
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307673uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7674 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007675 const DeviceVector &devices,
7676 bool force,
7677 int delayMs,
7678 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007679 bool requiresMuteCheck, bool requiresVolumeCheck,
7680 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007681{
jiabin3ff8d7d2022-12-13 06:27:44 +00007682 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307683 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7684 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7685 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007686 uint32_t muteWaitMs;
7687
7688 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307689 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007690 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307691 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007692 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007693 return muteWaitMs;
7694 }
Eric Laurente552edb2014-03-10 17:42:56 -07007695
7696 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007697 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007698 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007699 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007700
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307701 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7702 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007703
7704 if (!filteredDevices.isEmpty()) {
7705 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007706 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007707
7708 // if the outputs are not materially active, there is no need to mute.
7709 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007710 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007711 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307712 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7713 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007714 muteWaitMs = 0;
7715 }
Eric Laurente552edb2014-03-10 17:42:56 -07007716
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007717 bool outputRouted = outputDesc->isRouted();
7718
Eric Laurent79ea9582020-06-11 18:49:24 -07007719 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7720 // output profile or if new device is not supported AND previous device(s) is(are) still
7721 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007722 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307723 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7724 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007725 // restore previous device after evaluating strategy mute state
7726 outputDesc->setDevices(prevDevices);
7727 return muteWaitMs;
7728 }
7729
Eric Laurente552edb2014-03-10 17:42:56 -07007730 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007731 // the requested device is AUDIO_DEVICE_NONE
7732 // OR the requested device is the same as current device
7733 // AND force is not specified
7734 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007735 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007736 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307737 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7738 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7739 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007740 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307741 ALOGV("%s %s setting same device on routed output, force apply volumes",
7742 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007743 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7744 }
Eric Laurente552edb2014-03-10 17:42:56 -07007745 return muteWaitMs;
7746 }
7747
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307748 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7749 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007750
Eric Laurente552edb2014-03-10 17:42:56 -07007751 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007752 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007753 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007754 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007755 PatchBuilder patchBuilder;
7756 patchBuilder.addSource(outputDesc);
7757 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7758 for (const auto &filteredDevice : filteredDevices) {
7759 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007760 }
7761
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007762 // Add half reported latency to delayMs when muteWaitMs is null in order
7763 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007764 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7765 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7766 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007767 }
Eric Laurente552edb2014-03-10 17:42:56 -07007768
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007769 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7770 if (!skipMuteDelay) {
7771 // update stream volumes according to new device
7772 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7773 }
Eric Laurente552edb2014-03-10 17:42:56 -07007774
7775 return muteWaitMs;
7776}
7777
Eric Laurentc75307b2015-03-17 15:29:32 -07007778status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007779 int delayMs,
7780 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007781{
Eric Laurent6a94d692014-05-20 11:18:06 -07007782 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007783 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7784 return INVALID_OPERATION;
7785 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007786 if (patchHandle) {
7787 index = mAudioPatches.indexOfKey(*patchHandle);
7788 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007789 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007790 }
7791 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007792 return INVALID_OPERATION;
7793 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007794 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007795 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007796 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007797 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007798 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007799 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007800 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007801 return status;
7802}
7803
7804status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007805 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007806 bool force,
7807 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007808{
7809 status_t status = NO_ERROR;
7810
Eric Laurent1f2f2232014-06-02 12:01:23 -07007811 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007812 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7813 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007814
François Gaffie11d30102018-11-02 16:09:09 +01007815 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007816 PatchBuilder patchBuilder;
7817 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007818 // AUDIO_SOURCE_HOTWORD is for internal use only:
7819 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007820 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7821 auto result = usecase;
7822 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7823 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7824 }
7825 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007826 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007827 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007828 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007829 }
7830 }
7831 return status;
7832}
7833
Eric Laurent6a94d692014-05-20 11:18:06 -07007834status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7835 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007836{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007837 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007838 ssize_t index;
7839 if (patchHandle) {
7840 index = mAudioPatches.indexOfKey(*patchHandle);
7841 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007842 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007843 }
7844 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007845 return INVALID_OPERATION;
7846 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007847 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007848 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007849 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007850 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007851 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007852 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007853 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007854 return status;
7855}
7856
François Gaffie11d30102018-11-02 16:09:09 +01007857sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007858 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007859 audio_format_t& format,
7860 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007861 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007862{
7863 // Choose an input profile based on the requested capture parameters: select the first available
7864 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007865 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007866
Atneya Nair0f0a8032022-12-12 16:20:12 -08007867 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7868 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7869 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7870
7871 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007872
jiabin2fd710d2022-05-02 23:20:22 +00007873 for (;;) {
7874 sp<IOProfile> firstInexact = nullptr;
7875 uint32_t updatedSamplingRate = 0;
7876 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7877 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7878 for (const auto& hwModule : mHwModules) {
7879 for (const auto& profile : hwModule->getInputProfiles()) {
7880 // profile->log();
7881 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007882 if (profile->getCompatibilityScore(
7883 DeviceVector(device),
7884 samplingRate,
7885 &updatedSamplingRate,
7886 format,
7887 &updatedFormat,
7888 channelMask,
7889 &updatedChannelMask,
7890 // FIXME ugly cast
7891 (audio_output_flags_t) flags,
7892 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7893 samplingRate = updatedSamplingRate;
7894 format = updatedFormat;
7895 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007896 return profile;
7897 }
jiabin66acc432024-02-06 00:57:36 +00007898 if (firstInexact == nullptr
7899 && profile->getCompatibilityScore(
7900 DeviceVector(device),
7901 samplingRate,
7902 &updatedSamplingRate,
7903 format,
7904 &updatedFormat,
7905 channelMask,
7906 &updatedChannelMask,
7907 // FIXME ugly cast
7908 (audio_output_flags_t) flags,
7909 false /*exactMatchRequiredForInputFlags*/)
7910 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007911 firstInexact = profile;
7912 }
7913 }
7914 }
7915
7916 if (firstInexact != nullptr) {
7917 samplingRate = updatedSamplingRate;
7918 format = updatedFormat;
7919 channelMask = updatedChannelMask;
7920 return firstInexact;
7921 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7922 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7923 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7924 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7925 flags = AUDIO_INPUT_FLAG_NONE;
7926 } else { // fail
7927 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7928 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7929 samplingRate, format, channelMask, oriFlags);
7930 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007931 }
7932 }
jiabin2fd710d2022-05-02 23:20:22 +00007933
7934 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007935}
7936
François Gaffieaaac0fd2018-11-22 17:56:39 +01007937float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7938 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007939 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007940 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007941{
jiabin9a3361e2019-10-01 09:38:30 -07007942 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007943
7944 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7945 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7946 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7947 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007948 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7949 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7950 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7951 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7952 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena5300db62023-08-30 18:45:18 -07007953 // Verify that the current volume source is not the ringer volume to prevent recursively
7954 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7955 // to the same volume group.
7956 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007957 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7958 mOutputs.isActive(ringVolumeSrc, 0)) {
7959 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007960 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007961 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007962 }
7963
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007964 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007965 if ((volumeSource != callVolumeSrc && (isInCall() ||
7966 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007967 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007968 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7969 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007970 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7971 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7972 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007973 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007974 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007975 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007976 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007977 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007978 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007979 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7980 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7981 // programmatically muted.
7982 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7983 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7984 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007985 bool exemptFromCapping =
7986 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7987 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007988 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7989 volumeSource, volumeDb);
7990 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007991 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7992 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7993 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007994 }
7995 }
Eric Laurente552edb2014-03-10 17:42:56 -07007996 // if a headset is connected, apply the following rules to ring tones and notifications
7997 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007998 // - always attenuate notifications volume by 6dB
7999 // - attenuate ring tones volume by 6dB unless music is not playing and
8000 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07008001 // - if music is playing, always limit the volume to current music volume,
8002 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07008003 if (!Intersection(deviceTypes,
8004 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8005 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07008006 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
8007 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008008 ((volumeSource == alarmVolumeSrc ||
8009 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008010 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
8011 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
8012 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008013 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
8014 curves.canBeMuted()) {
8015
Eric Laurente552edb2014-03-10 17:42:56 -07008016 // when the phone is ringing we must consider that music could have been paused just before
8017 // by the music application and behave as if music was active if the last music track was
8018 // just stopped
Oscar Azucena5300db62023-08-30 18:45:18 -07008019 // Verify that the current volume source is not the music volume to prevent recursively
8020 // calling to compute volume. This could happen in cases where music and
8021 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
8022 if (volumeSource != musicVolumeSrc &&
8023 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
8024 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01008025 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07008026 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01008027 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
8028 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01008029 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07008030 float musicVolDb = computeVolume(musicCurves,
8031 musicVolumeSrc,
8032 musicCurves.getVolumeIndex(musicDevice),
8033 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008034 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
8035 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
8036 if (volumeDb > minVolDb) {
8037 volumeDb = minVolDb;
8038 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07008039 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02008040 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
8041 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
chenxin2058f15fd2024-06-13 22:04:29 +08008042 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
8043 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty()) {
8044 // on A2DP/BLE, also ensure notification volume is not too low compared to media
8045 // when intended to be played.
François Gaffie43c73442018-11-08 08:21:55 +01008046 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01008047 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07008048 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
8049 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01008050 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
8051 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07008052 }
8053 }
jiabin9a3361e2019-10-01 09:38:30 -07008054 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008055 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01008056 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07008057 }
8058 }
8059
François Gaffie43c73442018-11-08 08:21:55 +01008060 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07008061}
8062
Eric Laurent3839bc02018-07-10 18:33:34 -07008063int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008064 VolumeSource fromVolumeSource,
8065 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07008066{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008067 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07008068 return srcIndex;
8069 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01008070 auto &srcCurves = getVolumeCurves(fromVolumeSource);
8071 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008072 float minSrc = (float)srcCurves.getVolumeIndexMin();
8073 float maxSrc = (float)srcCurves.getVolumeIndexMax();
8074 float minDst = (float)dstCurves.getVolumeIndexMin();
8075 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07008076
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08008077 // preserve mute request or correct range
8078 if (srcIndex < minSrc) {
8079 if (srcIndex == 0) {
8080 return 0;
8081 }
8082 srcIndex = minSrc;
8083 } else if (srcIndex > maxSrc) {
8084 srcIndex = maxSrc;
8085 }
Eric Laurent3839bc02018-07-10 18:33:34 -07008086 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
8087}
8088
François Gaffieaaac0fd2018-11-22 17:56:39 +01008089status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
8090 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008091 int index,
8092 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008093 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008094 int delayMs,
8095 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008096{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008097 // do not change actual attributes volume if the attributes is muted
8098 if (outputDesc->isMuted(volumeSource)) {
8099 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
8100 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07008101 return NO_ERROR;
8102 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008103
Eric Laurent5baf07c2024-01-11 16:57:27 +00008104 bool isVoiceVolSrc;
8105 bool isBtScoVolSrc;
8106 if (!isVolumeConsistentForCalls(
8107 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07008108 // Do not return an error here as AudioService will always set both voice call
Eric Laurent5baf07c2024-01-11 16:57:27 +00008109 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07008110 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07008111 }
Eric Laurent5baf07c2024-01-11 16:57:27 +00008112
jiabin9a3361e2019-10-01 09:38:30 -07008113 if (deviceTypes.empty()) {
8114 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08008115 index = curves.getVolumeIndex(deviceTypes);
Mikhail Naganov0621c042024-06-05 11:43:22 -07008116 ALOGV("%s if deviceTypes is change from none to device %s, need get index %d",
chenxin2080986da2023-07-17 11:45:21 +08008117 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07008118 }
Eric Laurent275e8e92014-11-30 15:14:47 -08008119
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00008120 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
8121 ALOGE("invalid volume index range");
8122 return BAD_VALUE;
8123 }
8124
jiabin9a3361e2019-10-01 09:38:30 -07008125 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
8126 if (outputDesc->isFixedVolume(deviceTypes) ||
chenxin2095559032024-06-15 13:59:29 +08008127 // Force VoIP volume to max for bluetooth SCO/BLE device except if muted
Eric Laurent9698a4c2020-10-12 17:10:23 -07008128 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
chenxin2095559032024-06-15 13:59:29 +08008129 (isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device)
8130 || isSingleDeviceType(deviceTypes, audio_is_ble_out_device)))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07008131 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08008132 }
Francois Gaffie593634d2021-06-22 13:31:31 +02008133 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02008134 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
8135 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07008136
Eric Laurente8f2c0f2021-08-17 11:17:19 +02008137 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
chenxin2095559032024-06-15 13:59:29 +08008138 bool voiceVolumeManagedByHost = isVoiceVolSrc &&
8139 !isSingleDeviceType(deviceTypes, audio_is_ble_out_device);
8140 setVoiceVolume(index, curves, voiceVolumeManagedByHost, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008141 }
Eric Laurente552edb2014-03-10 17:42:56 -07008142 return NO_ERROR;
8143}
8144
Eric Laurent5baf07c2024-01-11 16:57:27 +00008145void AudioPolicyManager::setVoiceVolume(
chenxin2095559032024-06-15 13:59:29 +08008146 int index, IVolumeCurves &curves, bool voiceVolumeManagedByHost, int delayMs) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008147 float voiceVolume;
chenxin2095559032024-06-15 13:59:29 +08008148 // Force voice volume to max or mute for Bluetooth SCO/BLE as other attenuations are managed
Eric Laurent5baf07c2024-01-11 16:57:27 +00008149 // by the headset
chenxin2095559032024-06-15 13:59:29 +08008150 if (voiceVolumeManagedByHost) {
Eric Laurent5baf07c2024-01-11 16:57:27 +00008151 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
8152 } else {
8153 voiceVolume = index == 0 ? 0.0 : 1.0;
8154 }
8155 if (voiceVolume != mLastVoiceVolume) {
8156 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
8157 mLastVoiceVolume = voiceVolume;
8158 }
8159}
8160
8161bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
8162 const DeviceTypeSet& deviceTypes,
8163 bool& isVoiceVolSrc,
8164 bool& isBtScoVolSrc,
8165 const char* caller) {
8166 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
8167 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
8168 const bool isScoRequested = isScoRequestedForComm();
8169 const bool isHAUsed = isHearingAidUsedForComm();
8170
8171 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8172 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8173
8174 if ((callVolSrc != btScoVolSrc) &&
8175 ((isVoiceVolSrc && isScoRequested) ||
8176 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8177 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8178 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8179 volumeSource, isScoRequested ? " " : " not ");
8180 return false;
8181 }
8182 return true;
8183}
8184
Eric Laurentc75307b2015-03-17 15:29:32 -07008185void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008186 const DeviceTypeSet& deviceTypes,
8187 int delayMs,
8188 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008189{
jiabincd510522020-01-22 09:40:55 -08008190 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008191 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8192 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8193 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008194 curves.getVolumeIndex(deviceTypes),
8195 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008196 }
8197}
8198
François Gaffiec005e562018-11-06 15:04:49 +01008199void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8200 bool on,
8201 const sp<AudioOutputDescriptor>& outputDesc,
8202 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008203 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008204{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008205 std::vector<VolumeSource> sourcesToMute;
8206 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8207 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8208 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008209 VolumeSource source = toVolumeSource(attributes, false);
8210 if ((source != VOLUME_SOURCE_NONE) &&
8211 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8212 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008213 sourcesToMute.push_back(source);
8214 }
Eric Laurente552edb2014-03-10 17:42:56 -07008215 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008216 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008217 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008218 }
8219
Eric Laurente552edb2014-03-10 17:42:56 -07008220}
8221
François Gaffieaaac0fd2018-11-22 17:56:39 +01008222void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8223 bool on,
8224 const sp<AudioOutputDescriptor>& outputDesc,
8225 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008226 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008227{
jiabin9a3361e2019-10-01 09:38:30 -07008228 if (deviceTypes.empty()) {
8229 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008230 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008231 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008232 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008233 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008234 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008235 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008236 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8237 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008238 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008239 }
8240 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008241 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8242 // ignored
8243 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008244 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008245 if (!outputDesc->isMuted(volumeSource)) {
8246 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008247 return;
8248 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008249 if (outputDesc->decMuteCount(volumeSource) == 0) {
8250 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008251 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008252 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008253 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008254 delayMs);
8255 }
8256 }
8257}
8258
François Gaffie53615e22015-03-19 09:24:12 +01008259bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8260{
François Gaffiec005e562018-11-06 15:04:49 +01008261 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008262 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8263 return true;
8264 }
8265
8266 // has known usage?
8267 switch (paa->usage) {
8268 case AUDIO_USAGE_UNKNOWN:
8269 case AUDIO_USAGE_MEDIA:
8270 case AUDIO_USAGE_VOICE_COMMUNICATION:
8271 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8272 case AUDIO_USAGE_ALARM:
8273 case AUDIO_USAGE_NOTIFICATION:
8274 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8275 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8276 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8277 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8278 case AUDIO_USAGE_NOTIFICATION_EVENT:
8279 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8280 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8281 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8282 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008283 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008284 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008285 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008286 case AUDIO_USAGE_EMERGENCY:
8287 case AUDIO_USAGE_SAFETY:
8288 case AUDIO_USAGE_VEHICLE_STATUS:
8289 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008290 break;
8291 default:
8292 return false;
8293 }
8294 return true;
8295}
8296
François Gaffie2110e042015-03-24 08:41:51 +01008297audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8298{
8299 return mEngine->getForceUse(usage);
8300}
8301
Eric Laurent96d1dda2022-03-14 17:14:19 +01008302bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008303 return isStateInCall(mEngine->getPhoneState());
8304}
8305
Eric Laurent96d1dda2022-03-14 17:14:19 +01008306bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008307 return is_state_in_call(state);
8308}
8309
Eric Laurentf9cccec2022-11-16 19:12:00 +01008310bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008311 audio_mode_t mode = mEngine->getPhoneState();
8312 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008313 || (mode == AUDIO_MODE_CALL_SCREEN)
8314 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008315}
8316
Eric Laurentf9cccec2022-11-16 19:12:00 +01008317bool AudioPolicyManager::isInCallOrScreening() const {
8318 audio_mode_t mode = mEngine->getPhoneState();
8319 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8320}
8321
Eric Laurentd60560a2015-04-10 11:31:20 -07008322void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8323{
8324 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008325 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008326 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008327 sourceDesc->sinkDevice()->equals(deviceDesc))
8328 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008329 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008330 }
8331 }
8332
8333 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8334 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8335 bool release = false;
8336 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8337 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8338 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8339 source->ext.device.type == deviceDesc->type()) {
8340 release = true;
8341 }
8342 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008343 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008344 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8345 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8346 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008347 sink->ext.device.type == deviceDesc->type() &&
8348 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8349 || strncmp(sink->ext.device.address, address,
8350 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008351 release = true;
8352 }
8353 }
8354 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008355 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8356 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008357 }
8358 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008359
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008360 mInputs.clearSessionRoutesForDevice(deviceDesc);
8361
Francois Gaffie716e1432019-01-14 16:58:59 +01008362 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008363}
8364
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008365void AudioPolicyManager::modifySurroundFormats(
8366 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008367 std::unordered_set<audio_format_t> enforcedSurround(
8368 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008369 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008370 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008371 allSurround.insert(pair.first);
8372 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8373 }
Phil Burk09bc4612016-02-24 15:58:15 -08008374
8375 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8376 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008377 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008378 // This is the resulting set of formats depending on the surround mode:
8379 // 'all surround' = allSurround
8380 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8381 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8382 // 'manual surround' = mManualSurroundFormats
8383 // AUTO: formats v 'enforced surround'
8384 // ALWAYS: formats v 'all surround' v 'enforced surround'
8385 // NEVER: formats ^ 'non-surround'
8386 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008387
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008388 std::unordered_set<audio_format_t> formatSet;
8389 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8390 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008391 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008392 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008393 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008394 formatSet.insert(*formatIter);
8395 }
8396 }
8397 } else {
8398 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8399 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008400 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008401
jiabin81772902018-04-02 17:52:27 -07008402 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008403 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008404 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8405 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8406 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008407 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008408 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8409 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8410 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008411 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008412 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008413 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008414 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008415 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008416 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008417}
8418
jiabin06e4bab2019-07-29 10:13:34 -07008419void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8420 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008421 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8422 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8423
8424 // If NEVER, then remove support for channelMasks > stereo.
8425 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008426 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8427 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008428 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008429 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008430 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008431 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008432 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008433 }
8434 }
jiabin81772902018-04-02 17:52:27 -07008435 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8436 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8437 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008438 bool supports5dot1 = false;
8439 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008440 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008441 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8442 supports5dot1 = true;
8443 break;
8444 }
8445 }
8446 // If not then add 5.1 support.
8447 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008448 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008449 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008450 }
Phil Burk09bc4612016-02-24 15:58:15 -08008451 }
8452}
8453
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008454void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008455 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008456 const sp<IOProfile>& profile) {
8457 if (!profile->hasDynamicAudioProfile()) {
8458 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008459 }
François Gaffie112b0af2015-11-19 16:13:25 +01008460
jiabin12537fc2023-10-12 17:56:08 +00008461 audio_port_v7 devicePort;
8462 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008463
jiabin12537fc2023-10-12 17:56:08 +00008464 audio_port_v7 mixPort;
8465 profile->toAudioPort(&mixPort);
8466 mixPort.ext.mix.handle = ioHandle;
8467
8468 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8469 if (status != NO_ERROR) {
8470 ALOGE("%s failed to query the attributes of the mix port", __func__);
8471 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008472 }
jiabin12537fc2023-10-12 17:56:08 +00008473
8474 std::set<audio_format_t> supportedFormats;
8475 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8476 supportedFormats.insert(mixPort.audio_profiles[i].format);
8477 }
8478 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8479 mReportedFormatsMap[devDesc] = formats;
8480
8481 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8482 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8483 modifySurroundFormats(devDesc, &formats);
8484 size_t modifiedNumProfiles = 0;
8485 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8486 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8487 formats.end()) {
8488 // Skip the format that is not present after modifying surround formats.
8489 continue;
8490 }
8491 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8492 sizeof(struct audio_profile));
8493 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8494 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8495 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8496 modifySurroundChannelMasks(&channels);
8497 std::copy(channels.begin(), channels.end(),
8498 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8499 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8500 }
8501 mixPort.num_audio_profiles = modifiedNumProfiles;
8502 }
8503 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008504}
Eric Laurentd60560a2015-04-10 11:31:20 -07008505
Mikhail Naganovdc769682018-05-04 15:34:08 -07008506status_t AudioPolicyManager::installPatch(const char *caller,
8507 audio_patch_handle_t *patchHandle,
8508 AudioIODescriptorInterface *ioDescriptor,
8509 const struct audio_patch *patch,
8510 int delayMs)
8511{
8512 ssize_t index = mAudioPatches.indexOfKey(
8513 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8514 *patchHandle : ioDescriptor->getPatchHandle());
8515 sp<AudioPatch> patchDesc;
8516 status_t status = installPatch(
8517 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8518 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008519 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008520 }
8521 return status;
8522}
8523
8524status_t AudioPolicyManager::installPatch(const char *caller,
8525 ssize_t index,
8526 audio_patch_handle_t *patchHandle,
8527 const struct audio_patch *patch,
8528 int delayMs,
8529 uid_t uid,
8530 sp<AudioPatch> *patchDescPtr)
8531{
8532 sp<AudioPatch> patchDesc;
8533 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8534 if (index >= 0) {
8535 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008536 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008537 }
8538
8539 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8540 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8541 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8542 if (status == NO_ERROR) {
8543 if (index < 0) {
8544 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008545 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008546 } else {
8547 patchDesc->mPatch = *patch;
8548 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008549 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008550 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008551 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008552 }
8553 nextAudioPortGeneration();
8554 mpClientInterface->onAudioPatchListUpdate();
8555 }
8556 if (patchDescPtr) *patchDescPtr = patchDesc;
8557 return status;
8558}
8559
jiabinbce0c1d2020-10-05 11:20:18 -07008560bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8561{
8562 const TrackClientVector activeClients = output->getActiveClients();
8563 if (activeClients.empty()) {
8564 return true;
8565 }
8566 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8567 if (index < 0) {
8568 ALOGE("%s, no audio patch found while there are active clients on output %d",
8569 __func__, output->getId());
8570 return false;
8571 }
8572 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8573 DeviceVector routedDevices;
8574 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8575 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8576 patchDesc->mPatch.sinks[i].id);
8577 if (device == nullptr) {
8578 ALOGE("%s, no audio device found with id(%d)",
8579 __func__, patchDesc->mPatch.sinks[i].id);
8580 return false;
8581 }
8582 routedDevices.add(device);
8583 }
8584 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008585 if (client->isInvalid()) {
8586 // No need to take care about invalidated clients.
8587 continue;
8588 }
jiabinbce0c1d2020-10-05 11:20:18 -07008589 sp<DeviceDescriptor> preferredDevice =
8590 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8591 if (mEngine->getOutputDevicesForAttributes(
8592 client->attributes(), preferredDevice, false) == routedDevices) {
8593 return false;
8594 }
8595 }
8596 return true;
8597}
8598
8599sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008600 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008601 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8602 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008603{
8604 for (const auto& device : devices) {
8605 // TODO: This should be checking if the profile supports the device combo.
8606 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008607 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8608 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008609 return nullptr;
8610 }
8611 }
8612 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8613 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008614 status_t status = desc->open(halConfig, mixerConfig, devices,
8615 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008616 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008617 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008618 return nullptr;
8619 }
jiabin14b50cc2023-12-13 19:01:52 +00008620 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8621 auto portConfig = desc->getConfig();
8622 for (const auto& device : devices) {
8623 device->setPreferredConfig(&portConfig);
8624 }
8625 }
jiabinbce0c1d2020-10-05 11:20:18 -07008626
8627 // Here is where the out_set_parameters() for card & device gets called
8628 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8629 const audio_devices_t deviceType = device->type();
8630 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008631 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008632 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8633 mpClientInterface->setParameters(output, String8(param));
8634 free(param);
8635 }
jiabin12537fc2023-10-12 17:56:08 +00008636 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008637 if (!profile->hasValidAudioProfile()) {
8638 ALOGW("%s() missing param", __func__);
8639 desc->close();
8640 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008641 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8642 // Reopen the output with the best audio profile picked by APM when the profile supports
8643 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008644 desc->close();
8645 output = AUDIO_IO_HANDLE_NONE;
8646 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8647 profile->pickAudioProfile(
8648 config.sample_rate, config.channel_mask, config.format);
8649 config.offload_info.sample_rate = config.sample_rate;
8650 config.offload_info.channel_mask = config.channel_mask;
8651 config.offload_info.format = config.format;
8652
jiabina84c3d32022-12-02 18:59:55 +00008653 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008654 if (status != NO_ERROR) {
8655 return nullptr;
8656 }
8657 }
8658
8659 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008660
baek.kim -61c20122022-07-27 10:05:32 +00008661 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8662 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8663
jiabinbce0c1d2020-10-05 11:20:18 -07008664 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8665 sp<AudioPolicyMix> policyMix;
8666 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8667 policyMix->setOutput(desc);
8668 desc->mPolicyMix = policyMix;
8669 } else {
8670 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk5b054372023-08-15 20:59:35 +00008671 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008672 }
8673
baek.kim -61c20122022-07-27 10:05:32 +00008674 } else if (hasPrimaryOutput() && speaker != nullptr
8675 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008676 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8677 // no duplicated output for:
8678 // - direct outputs
8679 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008680 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008681 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8682
8683 //TODO: configure audio effect output stage here
8684
8685 // open a duplicating output thread for the new output and the primary output
8686 sp<SwAudioOutputDescriptor> dupOutputDesc =
8687 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8688 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8689 if (status == NO_ERROR) {
8690 // add duplicated output descriptor
8691 addOutput(duplicatedOutput, dupOutputDesc);
8692 } else {
8693 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8694 mPrimaryOutput->mIoHandle, output);
8695 desc->close();
8696 removeOutput(output);
8697 nextAudioPortGeneration();
8698 return nullptr;
8699 }
8700 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008701 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8702 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8703 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008704 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008705 }
jiabinbce0c1d2020-10-05 11:20:18 -07008706 return desc;
8707}
8708
jiabinf1c73972022-04-14 16:28:52 -07008709status_t AudioPolicyManager::getDevicesForAttributes(
8710 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8711 // Devices are determined in the following precedence:
8712 //
8713 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8714 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8715 //
8716 // If no such dynamic policy then
8717 // 2) Devices containing an active client using setPreferredDevice
8718 // with same strategy as the attributes.
8719 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8720 //
8721 // If no corresponding active client with setPreferredDevice then
8722 // 3) Devices associated with the strategy determined by the attributes
8723 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8724 //
8725 // See related getOutputForAttrInt().
8726
8727 // check dynamic policies but only for primary descriptors (secondary not used for audible
8728 // audio routing, only used for duplication for playback capture)
8729 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008730 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008731 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008732 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8733 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8734 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008735 if (status != OK) {
8736 return status;
8737 }
8738
8739 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8740 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8741 // as they are unaffected by device/stream volume
8742 // (per SwAudioOutputDescriptor::isFixedVolume()).
8743 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8744 ) {
8745 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8746 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8747 devices.add(deviceDesc);
8748 } else {
8749 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8750 // which selects setPreferredDevice if active. This means forVolume call
8751 // will take an active setPreferredDevice, if such exists.
8752
8753 devices = mEngine->getOutputDevicesForAttributes(
8754 attr, nullptr /* preferredDevice */, false /* fromCache */);
8755 }
8756
8757 if (forVolume) {
8758 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8759 // for single volume control in AudioService (such relationship should exist if
8760 // SPEAKER_SAFE is present).
8761 //
8762 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8763 DeviceVector speakerSafeDevices =
8764 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8765 if (!speakerSafeDevices.isEmpty()) {
8766 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8767 devices.remove(speakerSafeDevices);
8768 }
8769 }
8770
8771 return NO_ERROR;
8772}
8773
8774status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8775 AudioProfileVector& audioProfiles,
8776 uint32_t flags,
8777 bool isInput) {
8778 for (const auto& hwModule : mHwModules) {
8779 // the MSD module checks for different conditions
8780 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8781 continue;
8782 }
8783 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8784 : hwModule->getOutputProfiles();
8785 for (const auto& profile : ioProfiles) {
8786 if (!profile->areAllDevicesSupported(devices) ||
8787 !profile->isCompatibleProfileForFlags(
8788 flags, false /*exactMatchRequiredForInputFlags*/)) {
8789 continue;
8790 }
8791 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8792 }
8793 }
8794
8795 if (!isInput) {
8796 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8797 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8798 if (msdModule != nullptr) {
8799 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8800 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8801 for (const auto &profile: msdModule->getOutputProfiles()) {
8802 if (!profile->asAudioPort()->isDirectOutput()) {
8803 continue;
8804 }
8805 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8806 }
8807 } else {
8808 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8809 }
8810 }
8811 }
8812
8813 return NO_ERROR;
8814}
8815
jiabin3ff8d7d2022-12-13 06:27:44 +00008816sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8817 const audio_config_t *config,
8818 audio_output_flags_t flags,
8819 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008820 closeOutput(outputDesc->mIoHandle);
8821 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8822 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8823 if (preferredOutput == nullptr) {
8824 ALOGE("%s failed to reopen output device=%d, caller=%s",
8825 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008826 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008827 return preferredOutput;
8828}
8829
8830void AudioPolicyManager::reopenOutputsWithDevices(
8831 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8832 for (const auto& [output, devices] : outputsToReopen) {
8833 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8834 closeOutput(output);
8835 openOutputWithProfileAndDevice(desc->mProfile, devices);
8836 }
jiabina84c3d32022-12-02 18:59:55 +00008837}
8838
jiabinc44b3462022-12-08 12:52:31 -08008839PortHandleVector AudioPolicyManager::getClientsForStream(
8840 audio_stream_type_t streamType) const {
8841 PortHandleVector clients;
8842 for (size_t i = 0; i < mOutputs.size(); ++i) {
8843 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8844 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8845 }
8846 return clients;
8847}
8848
8849void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8850 PortHandleVector clients;
8851 for (auto stream : streams) {
8852 PortHandleVector clientsForStream = getClientsForStream(stream);
8853 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8854 }
8855 mpClientInterface->invalidateTracks(clients);
8856}
8857
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008858} // namespace android