blob: 0084273510176b090c73923bb70566c7cae02469 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
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>
Atneya Nairb16666a2023-12-11 20:18:33 -080045#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070046#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070047#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070048#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070049#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070050#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070051#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070052#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070053#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070054#include <utils/Log.h>
55
Eric Laurentd4692962014-05-05 18:13:44 -070056#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010057#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurent3b73df72014-03-11 09:06:29 -070059namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070060
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010061using android::media::audio::common::AudioDevice;
62using android::media::audio::common::AudioDeviceAddress;
63using android::media::audio::common::AudioPortDeviceExt;
64using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000065using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070066
Eric Laurentdc462862016-07-19 12:29:53 -070067//FIXME: workaround for truncated touch sounds
68// to be removed when the problem is handled by system UI
69#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070070
71// Largest difference in dB on earpiece in call between the voice volume and another
72// media / notification / system volume.
73constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
74
jiabin06e4bab2019-07-29 10:13:34 -070075template <typename T>
76bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
77{
78 if (left.size() != right.size()) {
79 return false;
80 }
81 for (size_t index = 0; index < right.size(); index++) {
82 if (left[index] != right[index]) {
83 return false;
84 }
85 }
86 return true;
87}
88
89template <typename T>
90bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
91{
92 return !(left == right);
93}
94
Eric Laurente552edb2014-03-10 17:42:56 -070095// ----------------------------------------------------------------------------
96// AudioPolicyInterface implementation
97// ----------------------------------------------------------------------------
98
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010099status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
100 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
101 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800102 nextAudioPortGeneration();
103 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800104}
105
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100106status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
107 audio_policy_dev_state_t state,
108 const char* device_address,
109 const char* device_name,
110 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800111 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100112 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
113 status == OK) {
114 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
115 } else {
116 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
117 return status;
118 }
119}
120
François Gaffie11d30102018-11-02 16:09:09 +0100121void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000122 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200123{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000124 audio_port_v7 devicePort;
125 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000126 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000127 status != OK) {
jiabinc0048632023-04-27 22:04:31 +0000128 ALOGE("Error %d while setting connected state for device %s", state,
Mikhail Naganov516d3982022-02-01 23:53:59 +0000129 device->getDeviceTypeAddr().toString(false).c_str());
130 }
François Gaffie44481e72016-04-20 07:49:57 +0200131}
132
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100133status_t AudioPolicyManager::setDeviceConnectionStateInt(
134 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
135 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100136 if (port.ext.getTag() != AudioPortExt::device) {
137 return BAD_VALUE;
138 }
139 audio_devices_t device_type;
140 std::string device_address;
141 if (status_t status = aidl2legacy_AudioDevice_audio_device(
142 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
143 status != OK) {
144 return status;
145 };
146 const char* device_name = port.name.c_str();
147 // connect/disconnect only 1 device at a time
148 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
149 return BAD_VALUE;
150
151 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
152 device_type, device_address.c_str(), device_name, encodedFormat,
153 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000154 if (device == nullptr) {
155 return INVALID_OPERATION;
156 }
157 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
158 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
159 }
160 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100161}
162
François Gaffie11d30102018-11-02 16:09:09 +0100163status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800164 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100165 const char* device_address,
166 const char* device_name,
167 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800168 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100169 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
170 status == OK) {
171 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
172 } else {
173 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
174 return status;
175 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700176}
Paul McLeane743a472015-01-28 11:07:31 -0800177
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700178status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
179 audio_policy_dev_state_t state)
180{
Eric Laurente552edb2014-03-10 17:42:56 -0700181 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700182 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700183 SortedVector <audio_io_handle_t> outputs;
184
François Gaffie11d30102018-11-02 16:09:09 +0100185 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700186
Eric Laurente552edb2014-03-10 17:42:56 -0700187 // save a copy of the opened output descriptors before any output is opened or closed
188 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
189 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100190
191 bool wasLeUnicastActive = isLeUnicastActive();
192
Eric Laurente552edb2014-03-10 17:42:56 -0700193 switch (state)
194 {
195 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800196 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700197 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100198 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700199 return INVALID_OPERATION;
200 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800201 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700202 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700203
Eric Laurente552edb2014-03-10 17:42:56 -0700204 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200205 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700206 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700207 }
208
François Gaffie44481e72016-04-20 07:49:57 +0200209 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
210 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000211 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200212
François Gaffie11d30102018-11-02 16:09:09 +0100213 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
214 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200215
Francois Gaffie716e1432019-01-14 16:58:59 +0100216 mHwModules.cleanUpForDevice(device);
217
jiabinc0048632023-04-27 22:04:31 +0000218 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700219 return INVALID_OPERATION;
220 }
François Gaffie2110e042015-03-24 08:41:51 +0100221
jiabin1c4794b2020-05-05 10:08:05 -0700222 // Populate encapsulation information when a output device is connected.
223 device->setEncapsulationInfoFromHal(mpClientInterface);
224
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700225 // outputs should never be empty here
226 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
227 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100228 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800229
Eric Laurent3ae5f312015-02-03 17:12:08 -0800230 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700231 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700232 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700233 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100234 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700235 return INVALID_OPERATION;
236 }
237
François Gaffie11d30102018-11-02 16:09:09 +0100238 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700239
jiabinc0048632023-04-27 22:04:31 +0000240 // Notify the HAL to prepare to disconnect device
241 broadcastDeviceConnectionState(
242 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700243
Eric Laurente552edb2014-03-10 17:42:56 -0700244 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100245 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700246
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100247 mOutputs.clearSessionRoutesForDevice(device);
248
François Gaffie11d30102018-11-02 16:09:09 +0100249 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100250
jiabinc0048632023-04-27 22:04:31 +0000251 // Send Disconnect to HALs
252 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
253
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800254 // Reset active device codec
255 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
256
Kriti Dangef6be8f2020-11-05 11:58:19 +0100257 // remove device from mReportedFormatsMap cache
258 mReportedFormatsMap.erase(device);
259
jiabina84c3d32022-12-02 18:59:55 +0000260 // remove preferred mixer configurations
261 mPreferredMixerAttrInfos.erase(device->getId());
262
Eric Laurente552edb2014-03-10 17:42:56 -0700263 } break;
264
265 default:
François Gaffie11d30102018-11-02 16:09:09 +0100266 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700267 return BAD_VALUE;
268 }
269
Eric Laurent736a1022019-03-27 18:28:46 -0700270 // Propagate device availability to Engine
271 setEngineDeviceConnectionState(device, state);
272
Eric Laurentae970022019-01-29 14:25:04 -0800273 // No need to evaluate playback routing when connecting a remote submix
274 // output device used by a dynamic policy of type recorder as no
275 // playback use case is affected.
276 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700277 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800278 for (audio_io_handle_t output : outputs) {
279 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800280 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
281 if (policyMix != nullptr
282 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000283 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800284 doCheckForDeviceAndOutputChanges = false;
285 break;
286 }
287 }
288 }
289
290 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700291 // outputs must be closed after checkOutputForAllStrategies() is executed
292 if (!outputs.isEmpty()) {
293 for (audio_io_handle_t output : outputs) {
294 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100295 // close unused outputs after device disconnection or direct outputs that have
296 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200297 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200298 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
299 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200300 (desc->mDirectOpenCount == 0))
301 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
302 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200303 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700304 closeOutput(output);
305 }
Eric Laurente552edb2014-03-10 17:42:56 -0700306 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700307 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
308 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700309 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700310 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800311 };
312
313 if (doCheckForDeviceAndOutputChanges) {
314 checkForDeviceAndOutputChanges(checkCloseOutputs);
315 } else {
316 checkCloseOutputs();
317 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100318 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100319 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700320 const DeviceVector activeMediaDevices =
321 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000322 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700323 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700324 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530325 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
326 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100327 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 // do not force device change on duplicated output because if device is 0, it will
329 // also force a device 0 for the two outputs it is duplicated to which may override
330 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100331 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100332 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700333 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700334 // always force when disconnecting (a non-duplicated device)
335 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000336 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
337 // If the device is using preferred mixer attributes, the output need to reopen
338 // with default configuration when the new selected devices are different from
339 // current routing devices
340 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
341 continue;
342 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530343 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700344 }
jiabinbce0c1d2020-10-05 11:20:18 -0700345 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000346 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700347 desc->supportsDevicesForPlayback(activeMediaDevices)) {
348 // Reopen the output to query the dynamic profiles when there is not active
349 // clients or all active clients will be rerouted. Otherwise, set the flag
350 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
351 // can be reopened to query dynamic profiles when all clients are inactive.
352 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000353 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700354 } else {
355 desc->mPendingReopenToQueryProfiles = true;
356 }
357 }
358 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
359 // Clear the flag that previously set for re-querying profiles.
360 desc->mPendingReopenToQueryProfiles = false;
361 }
362 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000363 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700364
Eric Laurentd60560a2015-04-10 11:31:20 -0700365 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100366 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700367 }
368
Eric Laurent96d1dda2022-03-14 17:14:19 +0100369 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
370
Eric Laurent72aa32f2014-05-30 18:51:48 -0700371 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700372 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700373 } // end if is output device
374
Eric Laurente552edb2014-03-10 17:42:56 -0700375 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700376 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100377 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700378 switch (state)
379 {
380 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700381 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700382 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700384 return INVALID_OPERATION;
385 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700386
387 if (mAvailableInputDevices.add(device) < 0) {
388 return NO_MEMORY;
389 }
390
François Gaffie44481e72016-04-20 07:49:57 +0200391 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
392 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000393 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200394
Eric Laurent0dd51852019-04-19 18:18:58 -0700395 if (checkInputsForDevice(device, state) != NO_ERROR) {
396 mAvailableInputDevices.remove(device);
397
jiabinc0048632023-04-27 22:04:31 +0000398 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100399
400 mHwModules.cleanUpForDevice(device);
401
Eric Laurentd4692962014-05-05 18:13:44 -0700402 return INVALID_OPERATION;
403 }
404
Eric Laurentd4692962014-05-05 18:13:44 -0700405 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700406
407 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700408 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700409 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100410 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700411 return INVALID_OPERATION;
412 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700413
François Gaffie11d30102018-11-02 16:09:09 +0100414 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700415
jiabinc0048632023-04-27 22:04:31 +0000416 // Notify the HAL to prepare to disconnect device
417 broadcastDeviceConnectionState(
418 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700419
François Gaffie11d30102018-11-02 16:09:09 +0100420 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700421
422 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100423
jiabinc0048632023-04-27 22:04:31 +0000424 // Set Disconnect to HALs
425 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
426
Kriti Dangef6be8f2020-11-05 11:58:19 +0100427 // remove device from mReportedFormatsMap cache
428 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700429 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700430
431 default:
François Gaffie11d30102018-11-02 16:09:09 +0100432 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700433 return BAD_VALUE;
434 }
435
Eric Laurent736a1022019-03-27 18:28:46 -0700436 // Propagate device availability to Engine
437 setEngineDeviceConnectionState(device, state);
438
Eric Laurent0dd51852019-04-19 18:18:58 -0700439 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700440 // As the input device list can impact the output device selection, update
441 // getDeviceForStrategy() cache
442 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700443
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100444 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200445 // Reconnect Audio Source
446 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
447 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
448 checkAudioSourceForAttributes(attributes);
449 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700450 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100451 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700452 }
453
Eric Laurentb52c1522014-05-20 11:27:36 -0700454 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700455 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700456 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700457
François Gaffie11d30102018-11-02 16:09:09 +0100458 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700459 return BAD_VALUE;
460}
461
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100462status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
463 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800464 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700465 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
466 devDescr->setName(device_name);
467 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100468}
469
Eric Laurent736a1022019-03-27 18:28:46 -0700470void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
471 audio_policy_dev_state_t state) {
472
473 // the Engine does not have to know about remote submix devices used by dynamic audio policies
474 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
475 return;
476 }
477 mEngine->setDeviceConnectionState(device, state);
478}
479
480
Eric Laurente0720872014-03-11 09:30:41 -0700481audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100482 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700483{
Eric Laurent634b7142016-04-20 13:48:02 -0700484 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800485 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
486 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700487 (strlen(device_address) != 0)/*matchAddress*/);
488
489 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100490 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700491 device, device_address);
492 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
493 }
François Gaffie53615e22015-03-19 09:24:12 +0100494
Eric Laurent3a4311c2014-03-17 12:00:47 -0700495 DeviceVector *deviceVector;
496
Eric Laurente552edb2014-03-10 17:42:56 -0700497 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700498 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700499 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700500 deviceVector = &mAvailableInputDevices;
501 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100502 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700503 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700504 }
Eric Laurent634b7142016-04-20 13:48:02 -0700505
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800506 return (deviceVector->getDevice(
507 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700508 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800509}
510
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800511status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
512 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800513 const char *device_name,
514 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800515{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800516 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
517 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800518
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800519 // connect/disconnect only 1 device at a time
520 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
521
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800522 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700523 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800524 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525 // Nothing to do: device is not connected
526 return NO_ERROR;
527 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800528 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800529
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700530 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800531 // configure codecs.
532 // Handle two specific cases by sending a set parameter to
533 // configure A2DP codecs. No need to toggle device state.
534 // Case 1: A2DP active device switches from primary to primary
535 // module
536 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100537 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700538 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800539 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
540 if (availablePrimaryOutputDevices().contains(devDesc) &&
541 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100542 bool isA2dp = audio_is_a2dp_out_device(device);
543 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
544 : String8(AudioParameter::keyReconfigLeSupported);
545 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800546 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100547 int isReconfigSupported;
548 repliedParameters.getInt(supportKey, isReconfigSupported);
549 if (isReconfigSupported) {
550 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
551 : String8(AudioParameter::keyReconfigLe);
552 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800553 param.add(key, String8("true"));
554 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
555 devDesc->setEncodedFormat(encodedFormat);
556 return NO_ERROR;
557 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700558 }
559 }
cnx421bd2dcc42020-07-11 14:58:44 +0800560 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
561 for (size_t i = 0; i < mOutputs.size(); i++) {
562 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
563 // mute media strategies and delay device switch by the largest
564 // This avoid sending the music tail into the earpiece or headset.
565 setStrategyMute(musicStrategy, true, desc);
566 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
567 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
568 nullptr, true /*fromCache*/).types());
569 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800570 // Toggle the device state: UNAVAILABLE -> AVAILABLE
571 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100572 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800573 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800574 device_address, device_name,
575 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800576 if (status != NO_ERROR) {
577 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
578 status);
579 return status;
580 }
581
582 status = setDeviceConnectionState(device,
583 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800584 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800585 if (status != NO_ERROR) {
586 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
587 status);
588 return status;
589 }
590
591 return NO_ERROR;
592}
593
Pattydd807582021-11-04 21:01:03 +0800594status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
595 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800596{
Pattydd807582021-11-04 21:01:03 +0800597 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800598 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800599 std::unordered_set<audio_format_t> formatSet;
600 sp<HwModule> primaryModule =
601 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700602 if (primaryModule == nullptr) {
603 ALOGE("%s() unable to get primary module", __func__);
604 return NO_INIT;
605 }
Pattydd807582021-11-04 21:01:03 +0800606
607 DeviceTypeSet audioDeviceSet;
608
609 switch(device) {
610 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
611 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
612 break;
613 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800614 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
615 break;
616 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
617 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800618 break;
619 default:
620 ALOGE("%s() device type 0x%08x not supported", __func__, device);
621 return BAD_VALUE;
622 }
623
jiabin9a3361e2019-10-01 09:38:30 -0700624 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800625 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800626 for (const auto& device : declaredDevices) {
627 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800628 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800629 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800630 return status;
631}
632
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100633DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
634{
635 DeviceVector rxSinkdevices{};
636 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
637 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
638 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
639 auto rxSinkDevice = rxSinkdevices.itemAt(0);
640 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
641 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
642 // retrieve Rx Source device descriptor
643 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
644 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
645
646 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
647 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
648 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
649 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
650 return DeviceVector(rxSinkDevice);
651 }
652 }
653 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
654 // the device returned is not necessarily reachable via this output
655 // (filter later by setOutputDevices())
656 return getNewOutputDevices(mPrimaryOutput, fromCache);
657}
658
659status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
660{
François Gaffiedb1755b2023-09-01 11:50:35 +0200661 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100662 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
663 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
664 }
665 return INVALID_OPERATION;
666}
667
668status_t AudioPolicyManager::updateCallRoutingInternal(
669 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670{
671 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100672 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700673 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200674 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700675 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100676 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700677 }
François Gaffie11d30102018-11-02 16:09:09 +0100678
Francois Gaffie716e1432019-01-14 16:58:59 +0100679 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100680 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200681
682 disconnectTelephonyAudioSource(mCallRxSourceClient);
683 disconnectTelephonyAudioSource(mCallTxSourceClient);
684
685 if (rxDevices.isEmpty()) {
686 ALOGW("%s() no selected output device", __func__);
687 return INVALID_OPERATION;
688 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000689 if (txSourceDevice == nullptr) {
690 ALOGE("%s() selected input device not available", __func__);
691 return INVALID_OPERATION;
692 }
François Gaffiec005e562018-11-06 15:04:49 +0100693
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100694 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100695 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700696
François Gaffie9eb18552018-11-05 10:33:26 +0100697 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700698 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100699 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700700 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100701 // retrieve Rx Source and Tx Sink device descriptors
702 sp<DeviceDescriptor> rxSourceDevice =
703 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
704 String8(),
705 AUDIO_FORMAT_DEFAULT);
706 sp<DeviceDescriptor> txSinkDevice =
707 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
708 String8(),
709 AUDIO_FORMAT_DEFAULT);
710
711 // RX and TX Telephony device are declared by Primary Audio HAL
712 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
713 (telephonyRxModule->getHalVersionMajor() >= 3)) {
714 if (rxSourceDevice == 0 || txSinkDevice == 0) {
715 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100716 ALOGE("%s() no telephony Tx and/or RX device", __func__);
717 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100718 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100719 // createAudioPatchInternal now supports both HW / SW bridging
720 createRxPatch = true;
721 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100722 } else {
723 // If the RX device is on the primary HW module, then use legacy routing method for
724 // voice calls via setOutputDevice() on primary output.
725 // Otherwise, create two audio patches for TX and RX path.
726 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
727 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700728 // If the TX device is also on the primary HW module, setOutputDevice() will take care
729 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100730 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
731 (txSinkDevice != 0);
732 }
733 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
734 // Otherwise, create two audio patches for TX and RX path.
735 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200736 if (!hasPrimaryOutput()) {
737 ALOGW("%s() no primary output available", __func__);
738 return INVALID_OPERATION;
739 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530740 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700741 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200742 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800743 // If the TX device is on the primary HW module but RX device is
744 // on other HW module, SinkMetaData of telephony input should handle it
745 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700746 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700747 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100748 // terminate active capture if on the same HW module as the call TX source device
749 // FIXME: would be better to refine to only inputs whose profile connects to the
750 // call TX device but this information is not in the audio patch and logic here must be
751 // symmetric to the one in startInput()
752 for (const auto& activeDesc : mInputs.getActiveInputs()) {
753 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
754 closeActiveClients(activeDesc);
755 }
756 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200757 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800758 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100759 if (waitMs != nullptr) {
760 *waitMs = muteWaitMs;
761 }
762 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800763}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700764
Mikhail Naganov100f0122018-11-29 11:22:16 -0800765bool AudioPolicyManager::isDeviceOfModule(
766 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
767 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
768 if (module != 0) {
769 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
770 .indexOf(devDesc) != NAME_NOT_FOUND
771 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
772 .indexOf(devDesc) != NAME_NOT_FOUND;
773 }
774 return false;
775}
776
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200777void AudioPolicyManager::connectTelephonyRxAudioSource()
778{
Francois Gaffie601801d2021-06-22 13:27:39 +0200779 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200780 const struct audio_port_config source = {
781 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
782 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
783 };
784 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100785
786 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
787 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
788 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
789 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200790 ALOGE_IF(mCallRxSourceClient == nullptr,
791 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200792}
793
Francois Gaffie601801d2021-06-22 13:27:39 +0200794void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200795{
Francois Gaffie601801d2021-06-22 13:27:39 +0200796 if (clientDesc == nullptr) {
797 return;
798 }
799 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
800 "%s error stopping audio source", __func__);
801 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200802}
803
804void AudioPolicyManager::connectTelephonyTxAudioSource(
805 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
806 uint32_t delayMs)
807{
Francois Gaffie601801d2021-06-22 13:27:39 +0200808 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200809 if (srcDevice == nullptr || sinkDevice == nullptr) {
810 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
811 return;
812 }
813 PatchBuilder patchBuilder;
814 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
815 ALOGV("%s between source %s and sink %s", __func__,
816 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200817 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200818 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
819
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200820 struct audio_port_config source = {};
821 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100822 mCallTxSourceClient = new SourceClientDescriptor(
823 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
824 mCommunnicationStrategy, toVolumeSource(aa), true);
825 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
826
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200827 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
828 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200829 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
830 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200831 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
832 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200833 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200834 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200835}
836
Eric Laurente0720872014-03-11 09:30:41 -0700837void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700838{
839 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100840 // store previous phone state for management of sonification strategy below
841 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100842 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100843
844 if (mEngine->setPhoneState(state) != NO_ERROR) {
845 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700846 return;
847 }
François Gaffie2110e042015-03-24 08:41:51 +0100848 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700849 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700850 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700851 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800852 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700853 }
854
François Gaffie2110e042015-03-24 08:41:51 +0100855 /**
856 * Switching to or from incall state or switching between telephony and VoIP lead to force
857 * routing command.
858 */
Eric Laurent74b71512019-11-06 17:21:57 -0800859 bool force = ((isStateInCall(oldState) != isStateInCall(state))
860 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700861
862 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700863 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700864
Eric Laurente552edb2014-03-10 17:42:56 -0700865 int delayMs = 0;
866 if (isStateInCall(state)) {
867 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100868 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
869 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700870 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700871 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700872 // mute media and sonification strategies and delay device switch by the largest
873 // latency of any output where either strategy is active.
874 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100875 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
876 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
877 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700878 (delayMs < (int)desc->latency()*2)) {
879 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700880 }
François Gaffiec005e562018-11-06 15:04:49 +0100881 setStrategyMute(musicStrategy, true, desc);
882 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
883 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
884 nullptr, true /*fromCache*/).types());
885 setStrategyMute(sonificationStrategy, true, desc);
886 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
887 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
888 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700889 }
890 }
891
François Gaffiedb1755b2023-09-01 11:50:35 +0200892 if (state == AUDIO_MODE_IN_CALL) {
893 (void)updateCallRouting(false /*fromCache*/, delayMs);
894 } else {
895 if (oldState == AUDIO_MODE_IN_CALL) {
896 disconnectTelephonyAudioSource(mCallRxSourceClient);
897 disconnectTelephonyAudioSource(mCallTxSourceClient);
898 }
899 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100900 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
901 // force routing command to audio hardware when ending call
902 // even if no device change is needed
903 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
904 rxDevices = mPrimaryOutput->devices();
905 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530906 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700907 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700908 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700909
jiabin3ff8d7d2022-12-13 06:27:44 +0000910 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700911 // reevaluate routing on all outputs in case tracks have been started during the call
912 for (size_t i = 0; i < mOutputs.size(); i++) {
913 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100914 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200915 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
916 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000917 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
918 // If the device is using preferred mixer attributes, the output need to reopen
919 // with default configuration when the new selected devices are different from
920 // current routing devices.
921 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
922 continue;
923 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530924 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200925 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700926 }
927 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000928 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700929
Eric Laurent96d1dda2022-03-14 17:14:19 +0100930 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
931
Eric Laurente552edb2014-03-10 17:42:56 -0700932 if (isStateInCall(state)) {
933 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700934 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800935 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700936 }
937
938 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100939 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
940 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700941}
942
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700943audio_mode_t AudioPolicyManager::getPhoneState() {
944 return mEngine->getPhoneState();
945}
946
Eric Laurente0720872014-03-11 09:30:41 -0700947void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100948 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700949{
François Gaffie2110e042015-03-24 08:41:51 +0100950 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700951 if (config == mEngine->getForceUse(usage)) {
952 return;
953 }
Eric Laurente552edb2014-03-10 17:42:56 -0700954
François Gaffie2110e042015-03-24 08:41:51 +0100955 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
956 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
957 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700958 }
François Gaffie2110e042015-03-24 08:41:51 +0100959 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
960 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
961 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700962
963 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700964 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800965
Eric Laurent22fcda22019-05-17 16:28:47 -0700966 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
967 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800968 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700969 }
970
Eric Laurentdc462862016-07-19 12:29:53 -0700971 //FIXME: workaround for truncated touch sounds
972 // to be removed when the problem is handled by system UI
973 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700974 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
975 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
976 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700977
978 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100979 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700980}
981
Eric Laurente0720872014-03-11 09:30:41 -0700982void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700983{
984 ALOGV("setSystemProperty() property %s, value %s", property, value);
985}
986
Dorin Drimusecc9f422022-03-09 17:57:40 +0100987// Find an MSD output profile compatible with the parameters passed.
988// When "directOnly" is set, restrict search to profiles for direct outputs.
989sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
990 const DeviceVector& devices,
991 uint32_t samplingRate,
992 audio_format_t format,
993 audio_channel_mask_t channelMask,
994 audio_output_flags_t flags,
995 bool directOnly)
996{
997 flags = getRelevantFlags(flags, directOnly);
998
999 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1000 if (msdModule != nullptr) {
1001 // for the msd module check if there are patches to the output devices
1002 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1003 HwModuleCollection modules;
1004 modules.add(msdModule);
1005 return searchCompatibleProfileHwModules(
1006 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1007 flags, directOnly);
1008 }
1009 }
1010 return nullptr;
1011}
1012
Michael Chana94fbb22018-04-24 14:31:19 +10001013// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1014// search to profiles for direct outputs.
1015sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001016 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001017 uint32_t samplingRate,
1018 audio_format_t format,
1019 audio_channel_mask_t channelMask,
1020 audio_output_flags_t flags,
1021 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001022{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001023 flags = getRelevantFlags(flags, directOnly);
1024
1025 return searchCompatibleProfileHwModules(
1026 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1027}
1028
1029audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1030 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001031 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001032 // only retain flags that will drive the direct output profile selection
1033 // if explicitly requested
1034 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001035 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1037 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001038 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001039 return flags;
1040}
Eric Laurent861a6282015-05-18 15:40:16 -07001041
Dorin Drimusecc9f422022-03-09 17:57:40 +01001042sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1043 const HwModuleCollection& hwModules,
1044 const DeviceVector& devices,
1045 uint32_t samplingRate,
1046 audio_format_t format,
1047 audio_channel_mask_t channelMask,
1048 audio_output_flags_t flags,
1049 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001050 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001051 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001052 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001053 if (!curProfile->isCompatibleProfile(devices,
1054 samplingRate, NULL /*updatedSamplingRate*/,
1055 format, NULL /*updatedFormat*/,
1056 channelMask, NULL /*updatedChannelMask*/,
1057 flags)) {
1058 continue;
1059 }
1060 // reject profiles not corresponding to a device currently available
1061 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1062 continue;
1063 }
1064 // reject profiles if connected device does not support codec
1065 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1066 continue;
1067 }
1068 if (!directOnly) {
1069 return curProfile;
1070 }
1071
1072 // when searching for direct outputs, if several profiles are compatible, give priority
1073 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001074 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001075 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001076 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001077 }
1078 profile = curProfile;
1079 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1080 break;
1081 }
Eric Laurente552edb2014-03-10 17:42:56 -07001082 }
1083 }
Eric Laurent861a6282015-05-18 15:40:16 -07001084 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001085}
1086
Eric Laurentfa0f6742021-08-17 18:39:44 +02001087sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001088 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001089{
1090 for (const auto& hwModule : mHwModules) {
1091 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001092 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001093 continue;
1094 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001095 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001096 // reject profiles not corresponding to a device currently available
1097 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1098 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1099 continue;
1100 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001101 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1102 != devices.size()) {
1103 continue;
1104 }
1105 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001106 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1107 return curProfile;
1108 }
1109 }
1110 return nullptr;
1111}
1112
Eric Laurentf4e63452017-11-06 19:31:46 +00001113audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001114{
François Gaffiec005e562018-11-06 15:04:49 +01001115 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001116
1117 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1118 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1119 // format, flags, etc. This may result in some discrepancy for functions that utilize
1120 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1121 // and AudioSystem::getOutputSamplingRate().
1122
François Gaffie11d30102018-11-02 16:09:09 +01001123 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001124 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1125 if (stream == AUDIO_STREAM_MUSIC &&
1126 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1127 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1128 }
1129 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001130
François Gaffie11d30102018-11-02 16:09:09 +01001131 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1132 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001133 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001134}
1135
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001136status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1137 const audio_attributes_t *srcAttr,
1138 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001139{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001140 if (srcAttr != NULL) {
1141 if (!isValidAttributes(srcAttr)) {
1142 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1143 __func__,
1144 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1145 srcAttr->tags);
1146 return BAD_VALUE;
1147 }
1148 *dstAttr = *srcAttr;
1149 } else {
1150 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1151 ALOGE("%s: invalid stream type", __func__);
1152 return BAD_VALUE;
1153 }
François Gaffiec005e562018-11-06 15:04:49 +01001154 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001155 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001156
1157 // Only honor audibility enforced when required. The client will be
1158 // forced to reconnect if the forced usage changes.
1159 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001160 dstAttr->flags = static_cast<audio_flags_mask_t>(
1161 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001162 }
1163
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001164 return NO_ERROR;
1165}
1166
Kevin Rocard153f92d2018-12-18 18:33:28 -08001167status_t AudioPolicyManager::getOutputForAttrInt(
1168 audio_attributes_t *resultAttr,
1169 audio_io_handle_t *output,
1170 audio_session_t session,
1171 const audio_attributes_t *attr,
1172 audio_stream_type_t *stream,
1173 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001174 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001175 audio_output_flags_t *flags,
1176 audio_port_handle_t *selectedDeviceId,
1177 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001178 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001179 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001180 bool *isSpatialized,
1181 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001182{
François Gaffiec005e562018-11-06 15:04:49 +01001183 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001184 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001185 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001186 const sp<DeviceDescriptor> requestedDevice =
1187 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1188
Eric Laurent8a1095a2019-11-08 14:44:16 -08001189 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001190 *isSpatialized = false;
1191
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001192 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1193 if (status != NO_ERROR) {
1194 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001195 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001196 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001197 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001198 }
François Gaffiec005e562018-11-06 15:04:49 +01001199 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001200
François Gaffiec005e562018-11-06 15:04:49 +01001201 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1202 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001203
Oscar Azucena873d10f2023-01-12 18:34:42 -08001204 bool usePrimaryOutputFromPolicyMixes = false;
1205
Kevin Rocard153f92d2018-12-18 18:33:28 -08001206 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1207 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1208 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001209 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001210 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1211 .channel_mask = config->channel_mask,
1212 .format = config->format,
1213 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001214 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001215 mAvailableOutputDevices, requestedDevice, primaryMix,
1216 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001217 if (status != OK) {
1218 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001219 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001220
Kevin Rocard153f92d2018-12-18 18:33:28 -08001221 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001222 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1223 && !audio_is_linear_pcm(config->format)) {
1224 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001225 return BAD_VALUE;
1226 }
1227 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001228 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001229 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1230 primaryMix->mDeviceAddress,
1231 AUDIO_FORMAT_DEFAULT);
1232 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001233 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001234 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1235 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001236 // if a direct output can be opened to deliver the track's multi-channel content to the
1237 // output rather than being downmixed by the primary output, then use this direct
1238 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1239 // mix.
1240 bool tryDirectForChannelMask = policyDesc != nullptr
1241 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1242 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001243 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001244 audio_io_handle_t newOutput;
1245 status = openDirectOutput(
1246 *stream, session, config,
1247 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001248 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001249 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001250 policyDesc = mOutputs.valueFor(newOutput);
1251 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001252 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001253 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001254 policyDesc = nullptr;
1255 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001256 }
1257 if (policyDesc != nullptr) {
1258 policyDesc->mPolicyMix = primaryMix;
1259 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001260 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1261 : AUDIO_PORT_HANDLE_NONE;
1262 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1263 // Remove direct flag as it is not on a direct output.
1264 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1265 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001266
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001267 ALOGV("getOutputForAttr() returns output %d", *output);
1268 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1269 *outputType = API_OUT_MIX_PLAYBACK;
1270 } else {
1271 *outputType = API_OUTPUT_LEGACY;
1272 }
1273 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001274 } else {
1275 if (policyMixDevice != nullptr) {
1276 ALOGE("%s, try to use primary mix but no output found", __func__);
1277 return INVALID_OPERATION;
1278 }
1279 // Fallback to default engine selection as the selected primary mix device is not
1280 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001281 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001282 }
François Gaffiec005e562018-11-06 15:04:49 +01001283 // Virtual sources must always be dynamicaly or explicitly routed
1284 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1285 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1286 return BAD_VALUE;
1287 }
1288 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1289 // in order to let the choice of the order to future vendor engine
1290 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001291
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001292 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001293 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001294 }
1295
Nadav Barb2f18162018-07-18 13:01:53 +03001296 // Set incall music only if device was explicitly set, and fallback to the device which is
1297 // chosen by the engine if not.
1298 // FIXME: provide a more generic approach which is not device specific and move this back
1299 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001300 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001301 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001302 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001303 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001304 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001305 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001306 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001307 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001308 }
1309 }
1310
François Gaffiec005e562018-11-06 15:04:49 +01001311 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1312 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1313 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001314
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001315 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001316 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001317 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001318 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001319 ALOGV("%s() Using MSD devices %s instead of devices %s",
1320 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001321 } else {
1322 *output = AUDIO_IO_HANDLE_NONE;
1323 }
1324 }
1325 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001326 sp<PreferredMixerAttributesInfo> info = nullptr;
1327 if (outputDevices.size() == 1) {
1328 info = getPreferredMixerAttributesInfo(
1329 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001330 mEngine->getProductStrategyForAttributes(*resultAttr),
1331 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001332 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1333 // and it is currently active.
1334 if (info != nullptr && info->getUid() != uid &&
1335 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1336 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001337 info = nullptr;
1338 }
1339 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001340 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001341 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001342 // The client will be active if the client is currently preferred mixer owner and the
1343 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001344 *isBitPerfect = (info != nullptr
1345 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001346 && info->getUid() == uid
1347 && *output != AUDIO_IO_HANDLE_NONE
1348 // When bit-perfect output is selected for the preferred mixer attributes owner,
1349 // only need to consider the config matches.
1350 && mOutputs.valueFor(*output)->isConfigurationMatched(
1351 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001352 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001353 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001354 AudioProfileVector profiles;
1355 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1356 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001357 const auto channels = profiles[0]->getChannels();
1358 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1359 config->channel_mask = *channels.begin();
1360 }
1361 const auto sampleRates = profiles[0]->getSampleRates();
1362 if (!sampleRates.empty() &&
1363 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1364 config->sample_rate = *sampleRates.begin();
1365 }
jiabinf1c73972022-04-14 16:28:52 -07001366 config->format = profiles[0]->getFormat();
1367 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001368 return INVALID_OPERATION;
1369 }
Paul McLeanaa981192015-03-21 09:55:15 -07001370
François Gaffiec005e562018-11-06 15:04:49 +01001371 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001372 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001373 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001374 *selectedDeviceId = outputDevice->getId();
1375 break;
1376 }
1377 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001378
Eric Laurent8a1095a2019-11-08 14:44:16 -08001379 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1380 *outputType = API_OUTPUT_TELEPHONY_TX;
1381 } else {
1382 *outputType = API_OUTPUT_LEGACY;
1383 }
1384
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001385 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1386
1387 return NO_ERROR;
1388}
1389
1390status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1391 audio_io_handle_t *output,
1392 audio_session_t session,
1393 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001394 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001395 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001396 audio_output_flags_t *flags,
1397 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001398 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001399 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001400 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001401 bool *isSpatialized,
1402 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001403{
1404 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1405 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1406 return INVALID_OPERATION;
1407 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001408 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001409 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001410 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001411 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001412 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001413 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001414 const sp<DeviceDescriptor> requestedDevice =
1415 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1416
1417 // Prevent from storing invalid requested device id in clients
1418 const audio_port_handle_t sanitizedRequestedPortId =
1419 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1420 *selectedDeviceId = sanitizedRequestedPortId;
1421
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001422 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001423 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001424 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1425 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001426 if (status != NO_ERROR) {
1427 return status;
1428 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001429 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001430 if (secondaryOutputs != nullptr) {
1431 for (auto &secondaryMix : secondaryMixes) {
1432 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1433 if (outputDesc != nullptr &&
1434 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1435 secondaryOutputs->push_back(outputDesc->mIoHandle);
1436 weakSecondaryOutputDescs.push_back(outputDesc);
1437 }
1438 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001439 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001440
Eric Laurent8fc147b2018-07-22 19:13:55 -07001441 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001442 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001443 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001444 };
jiabin4ef93452019-09-10 14:29:54 -07001445 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001446
Eric Laurentc209fe42020-06-05 18:11:23 -07001447 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001448 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001449 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001450 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001451 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001452 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001453 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001454 std::move(weakSecondaryOutputDescs),
1455 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001456 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001457
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001458 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1459 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001460
Eric Laurente83b55d2014-11-14 10:06:21 -08001461 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001462}
1463
Eric Laurentc529cf62020-04-17 18:19:10 -07001464status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1465 audio_session_t session,
1466 const audio_config_t *config,
1467 audio_output_flags_t flags,
1468 const DeviceVector &devices,
1469 audio_io_handle_t *output) {
1470
1471 *output = AUDIO_IO_HANDLE_NONE;
1472
1473 // skip direct output selection if the request can obviously be attached to a mixed output
1474 // and not explicitly requested
1475 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1476 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1477 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1478 return NAME_NOT_FOUND;
1479 }
1480
1481 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1482 // This prevents creating an offloaded track and tearing it down immediately after start
1483 // when audioflinger detects there is an active non offloadable effect.
1484 // FIXME: We should check the audio session here but we do not have it in this context.
1485 // This may prevent offloading in rare situations where effects are left active by apps
1486 // in the background.
1487 sp<IOProfile> profile;
1488 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1489 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1490 profile = getProfileForOutput(
1491 devices, config->sample_rate, config->format, config->channel_mask,
1492 flags, true /* directOnly */);
1493 }
1494
1495 if (profile == nullptr) {
1496 return NAME_NOT_FOUND;
1497 }
1498
1499 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1500 for (size_t i = 0; i < mOutputs.size(); i++) {
1501 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1502 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1503 // reuse direct output if currently open by the same client
1504 // and configured with same parameters
1505 if ((config->sample_rate == desc->getSamplingRate()) &&
1506 (config->format == desc->getFormat()) &&
1507 (config->channel_mask == desc->getChannelMask()) &&
1508 (session == desc->mDirectClientSession)) {
1509 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001510 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001511 mOutputs.keyAt(i), session);
1512 *output = mOutputs.keyAt(i);
1513 return NO_ERROR;
1514 }
1515 }
1516 }
1517
1518 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001519 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1520 return NAME_NOT_FOUND;
1521 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1522 // MMAP gracefully handles lack of an exclusive track resource by mixing
1523 // above the audio framework. For AAudio to know that the limit is reached,
1524 // return an error.
1525 return NAME_NOT_FOUND;
1526 } else {
1527 // Close outputs on this profile, if available, to free resources for this request
1528 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1529 const auto desc = mOutputs.valueAt(i);
1530 if (desc->mProfile == profile) {
1531 closeOutput(desc->mIoHandle);
1532 }
1533 }
1534 }
1535 }
1536
1537 // Unable to close streams to find free resources for this request
1538 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001539 return NAME_NOT_FOUND;
1540 }
1541
Atneya Nairb16666a2023-12-11 20:18:33 -08001542 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001543
Michael Chan6fb34492020-12-08 15:44:49 +11001544 // An MSD patch may be using the only output stream that can service this request. Release
1545 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001546 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001547
Eric Laurentf1f22e72021-07-13 14:04:14 +02001548 status_t status =
1549 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001550
1551 // only accept an output with the requested parameters
1552 if (status != NO_ERROR ||
1553 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1554 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1555 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1556 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1557 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1558 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1559 config->channel_mask, outputDesc->getChannelMask());
1560 if (*output != AUDIO_IO_HANDLE_NONE) {
1561 outputDesc->close();
1562 }
1563 // fall back to mixer output if possible when the direct output could not be open
1564 if (audio_is_linear_pcm(config->format) &&
1565 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1566 return NAME_NOT_FOUND;
1567 }
1568 *output = AUDIO_IO_HANDLE_NONE;
1569 return BAD_VALUE;
1570 }
1571 outputDesc->mDirectOpenCount = 1;
1572 outputDesc->mDirectClientSession = session;
1573
1574 addOutput(*output, outputDesc);
1575 mPreviousOutputs = mOutputs;
1576 ALOGV("%s returns new direct output %d", __func__, *output);
1577 mpClientInterface->onAudioPortListUpdate();
1578 return NO_ERROR;
1579}
1580
François Gaffie11d30102018-11-02 16:09:09 +01001581audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1582 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001583 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001584 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001585 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001586 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001587 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001588 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001589 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001590{
Andy Hungc88b0642018-04-27 15:42:35 -07001591 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001592
jiabine375d412019-02-26 12:54:53 -08001593 // Discard haptic channel mask when forcing muting haptic channels.
1594 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001595 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1596 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001597
Eric Laurente552edb2014-03-10 17:42:56 -07001598 // open a direct output if required by specified parameters
1599 //force direct flag if offload flag is set: offloading implies a direct output stream
1600 // and all common behaviors are driven by checking only the direct flag
1601 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001602 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1603 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001604 }
Nadav Bar766fb022018-01-07 12:18:03 +02001605 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1606 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001607 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001608
1609 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1610
Eric Laurente83b55d2014-11-14 10:06:21 -08001611 // only allow deep buffering for music stream type
1612 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001613 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001614 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001615 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001616 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1617 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001618 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001619 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001620 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001621 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001622 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001623 audio_is_linear_pcm(config->format) &&
1624 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001625 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001626 AUDIO_OUTPUT_FLAG_DIRECT);
1627 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001628 }
Eric Laurente552edb2014-03-10 17:42:56 -07001629
Carter Hsua3abb402021-10-26 11:11:20 +08001630 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1631 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1632 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1633 }
1634
Eric Laurentf9230d52024-01-26 18:49:09 +01001635 // Use the spatializer output if the content can be spatialized, no preferred mixer
1636 // was specified and offload or direct playback is not explicitly requested.
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001637 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001638 if (mSpatializerOutput != nullptr
jiabin2462ce82024-01-12 20:37:59 +00001639 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())
Eric Laurentf9230d52024-01-26 18:49:09 +01001640 && prefMixerConfigInfo == nullptr
1641 && ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001642 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001643 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001644 }
1645
Eric Laurentc529cf62020-04-17 18:19:10 -07001646 audio_config_t directConfig = *config;
1647 directConfig.channel_mask = channelMask;
1648 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1649 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001650 return output;
1651 }
1652
Eric Laurent14cbfca2016-03-17 09:42:16 -07001653 // A request for HW A/V sync cannot fallback to a mixed output because time
1654 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001655 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001656 return AUDIO_IO_HANDLE_NONE;
1657 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001658 // A request for Tuner cannot fallback to a mixed output
1659 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1660 return AUDIO_IO_HANDLE_NONE;
1661 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001662
Eric Laurente552edb2014-03-10 17:42:56 -07001663 // ignoring channel mask due to downmix capability in mixer
1664
1665 // open a non direct output
1666
1667 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001668 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001669 // get which output is suitable for the specified stream. The actual
1670 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001671 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001672 if (prefMixerConfigInfo != nullptr) {
1673 for (audio_io_handle_t outputHandle : outputs) {
1674 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1675 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1676 output = outputHandle;
1677 break;
1678 }
1679 }
1680 if (output == AUDIO_IO_HANDLE_NONE) {
1681 // No output open with the preferred profile. Open a new one.
1682 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1683 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1684 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1685 config.format = prefMixerConfigInfo->getConfigBase().format;
1686 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1687 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1688 &config, prefMixerConfigInfo->getFlags());
1689 if (preferredOutput == nullptr) {
1690 ALOGE("%s failed to open output with preferred mixer config", __func__);
1691 } else {
1692 output = preferredOutput->mIoHandle;
1693 }
1694 }
1695 } else {
1696 // at this stage we should ignore the DIRECT flag as no direct output could be
1697 // found earlier
1698 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1699 output = selectOutput(
1700 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1701 }
Eric Laurente552edb2014-03-10 17:42:56 -07001702 }
François Gaffie11d30102018-11-02 16:09:09 +01001703 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001704 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001705 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001706
Eric Laurente552edb2014-03-10 17:42:56 -07001707 return output;
1708}
1709
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001710sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001711 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1712 mAvailableInputDevices);
1713 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1714}
1715
1716DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1717 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1718 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001719}
1720
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001721const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001722 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001723 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1724 if (msdModule != 0) {
1725 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1726 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1727 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1728 const struct audio_port_config *source = &patch->mPatch.sources[j];
1729 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1730 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001731 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001732 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001733 }
1734 }
1735 }
1736 return msdPatches;
1737}
1738
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001739bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1740 ssize_t index = mAudioPatches.indexOfKey(handle);
1741 if (index < 0) {
1742 return false;
1743 }
1744 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1745 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1746 if (msdModule == nullptr) {
1747 return false;
1748 }
1749 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1750 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1751 return true;
1752 }
1753 index = getMsdOutputPatches().indexOfKey(handle);
1754 if (index < 0) {
1755 return false;
1756 }
1757 return true;
1758}
1759
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001760status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1761 const InputProfileCollection &inputProfiles,
1762 const OutputProfileCollection &outputProfiles,
1763 const sp<DeviceDescriptor> &sourceDevice,
1764 const sp<DeviceDescriptor> &sinkDevice,
1765 AudioProfileVector& sourceProfiles,
1766 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001767 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001768 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001769 return NO_INIT;
1770 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001771 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001772 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001773 return NO_INIT;
1774 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001775 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001776 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1777 inProfile->supportsDevice(sourceDevice)) {
1778 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001779 }
1780 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001781 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001782 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001783 outProfile->supportsDevice(sinkDevice)) {
1784 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001785 }
1786 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001787 return NO_ERROR;
1788}
1789
1790status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1791 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1792 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1793{
Dean Wheatley16809da2022-12-09 14:55:46 +11001794 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1795 static const std::vector<audio_format_t> formatsOrder = {{
1796 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001797 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1798 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001799 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1800 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1801 // preferred).
1802 std::vector<audio_channel_mask_t> masks = {{
1803 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1804 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1805 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1806 // insert index masks (higher counts most preferred) as preferred over position masks
1807 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1808 masks.insert(
1809 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1810 }
1811 return masks;
1812 }();
1813
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001814 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001815 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1816 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001817 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001818 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1819 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001820 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001821 }
1822 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1823 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1824 sinkConfig->format = bestSinkConfig.format;
1825 // For encoded streams force direct flag to prevent downstream mixing.
1826 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1827 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001828 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1829 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001830 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001831 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1832 // raw and IEC61937 framed streams.
1833 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1834 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1835 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001836 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1837 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001838 sourceConfig->channel_mask =
1839 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1840 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1841 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 sourceConfig->format = bestSinkConfig.format;
1843 // Copy input stream directly without any processing (e.g. resampling).
1844 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1845 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1846 if (hwAvSync) {
1847 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1848 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1849 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1850 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1851 }
1852 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1853 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1854 sinkConfig->config_mask |= config_mask;
1855 sourceConfig->config_mask |= config_mask;
1856 return NO_ERROR;
1857}
1858
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001859PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1860 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001861{
1862 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001863 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1864 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1865 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1866 if (deviceModule == nullptr) {
1867 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1868 return patchBuilder;
1869 }
1870 const InputProfileCollection inputProfiles = msdIsSource ?
1871 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1872 const OutputProfileCollection outputProfiles = msdIsSource ?
1873 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1874
1875 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1876 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1877 device : getMsdAudioOutDevices().itemAt(0);
1878 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1879
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001880 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1881 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001882 AudioProfileVector sourceProfiles;
1883 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1885 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001886 for (auto hwAvSync : { true, false }) {
1887 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1888 sourceProfiles, sinkProfiles) != NO_ERROR) {
1889 continue;
1890 }
1891 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1892 &sinkConfig) == NO_ERROR) {
1893 // Found a matching config. Re-create PatchBuilder with this config.
1894 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1895 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001896 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001897 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001898 " supporting PCM format conversion.", __func__);
1899 return patchBuilder;
1900}
1901
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001902status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001903 DeviceVector devices;
1904 if (outputDevices != nullptr && outputDevices->size() > 0) {
1905 devices.add(*outputDevices);
1906 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001907 // Use media strategy for unspecified output device. This should only
1908 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1909 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001910 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001911 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001912 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001913 }
Michael Chan6fb34492020-12-08 15:44:49 +11001914 std::vector<PatchBuilder> patchesToCreate;
1915 for (auto i = 0u; i < devices.size(); ++i) {
1916 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001917 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001918 }
1919 // Retain only the MSD patches associated with outputDevices request.
1920 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001921 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001922 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1923 auto retainedPatch = false;
1924 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1925 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1926 patchesToRemove.removeItemsAt(i);
1927 retainedPatch = true;
1928 break;
1929 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001930 }
Michael Chan6fb34492020-12-08 15:44:49 +11001931 if (retainedPatch) {
1932 it = patchesToCreate.erase(it);
1933 continue;
1934 }
1935 ++it;
1936 }
1937 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1938 return NO_ERROR;
1939 }
1940 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1941 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001942 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001943 }
Michael Chan6fb34492020-12-08 15:44:49 +11001944 status_t status = NO_ERROR;
1945 for (const auto &p : patchesToCreate) {
1946 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1947 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1948 char message[256];
1949 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1950 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1951 currStatus == NO_ERROR ? "Success" : "Error",
1952 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1953 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1954 if (currStatus == NO_ERROR) {
1955 ALOGD("%s", message);
1956 } else {
1957 ALOGE("%s", message);
1958 if (status == NO_ERROR) {
1959 status = currStatus;
1960 }
1961 }
1962 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001963 return status;
1964}
1965
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001966void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1967 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001968 for (size_t i = 0; i < msdPatches.size(); i++) {
1969 const auto& patch = msdPatches[i];
1970 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1971 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1972 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1973 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1974 releaseAudioPatch(patch->getHandle(), mUidCached);
1975 break;
1976 }
1977 }
1978 }
1979}
1980
Dorin Drimus94d94412022-02-02 09:05:02 +01001981bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001982 DeviceVector devicesToCheck =
1983 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001984 AudioPatchCollection msdPatches = getMsdOutputPatches();
1985 for (size_t i = 0; i < msdPatches.size(); i++) {
1986 const auto& patch = msdPatches[i];
1987 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1988 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1989 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1990 const auto& foundDevice = devicesToCheck.getDevice(
1991 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1992 if (foundDevice != nullptr) {
1993 devicesToCheck.remove(foundDevice);
1994 if (devicesToCheck.isEmpty()) {
1995 return true;
1996 }
1997 }
1998 }
1999 }
2000 }
2001 return false;
2002}
2003
Eric Laurente0720872014-03-11 09:30:41 -07002004audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002005 audio_output_flags_t flags,
2006 audio_format_t format,
2007 audio_channel_mask_t channelMask,
2008 uint32_t samplingRate,
2009 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002010{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002011 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2012 "%s called with format %#x", __func__, format);
2013
jiabinebb6af42020-06-09 17:31:17 -07002014 // Return the output that haptic-generating attached to when 1) session id is specified,
2015 // 2) haptic-generating effect exists for given session id and 3) the output that
2016 // haptic-generating effect attached to is in given outputs.
2017 if (sessionId != AUDIO_SESSION_NONE) {
2018 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2019 sessionId, FX_IID_HAPTICGENERATOR);
2020 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2021 return hapticGeneratingOutput;
2022 }
2023 }
2024
Eric Laurent16c66dd2019-05-01 17:54:10 -07002025 // Flags disqualifying an output: the match must happen before calling selectOutput()
2026 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2027 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2028
2029 // Flags expressing a functional request: must be honored in priority over
2030 // other criteria
2031 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2032 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002033 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2034 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002035 // Flags expressing a performance request: have lower priority than serving
2036 // requested sampling rate or channel mask
2037 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2038 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2039 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2040
2041 const audio_output_flags_t functionalFlags =
2042 (audio_output_flags_t)(flags & kFunctionalFlags);
2043 const audio_output_flags_t performanceFlags =
2044 (audio_output_flags_t)(flags & kPerformanceFlags);
2045
2046 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2047
Eric Laurente552edb2014-03-10 17:42:56 -07002048 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002049 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002050 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002051 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002052 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002053 // with tiebreak preferring the minimum number of extra functional flags
2054 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002055 // 3: the output supporting the exact channel mask
2056 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002057 // 5: the output with the highest sampling rate if the requested sample rate is
2058 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002059 // 6: the output with the highest number of requested performance flags
2060 // 7: the output with the bit depth the closest to the requested one
2061 // 8: the primary output
2062 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002063
Eric Laurent16c66dd2019-05-01 17:54:10 -07002064 // matching criteria values in priority order for best matching output so far
2065 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002066
Eric Laurent16c66dd2019-05-01 17:54:10 -07002067 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2068 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2069 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002070
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002071 for (audio_io_handle_t output : outputs) {
2072 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002073 // matching criteria values in priority order for current output
2074 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002075
Eric Laurent16c66dd2019-05-01 17:54:10 -07002076 if (outputDesc->isDuplicated()) {
2077 continue;
2078 }
2079 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2080 continue;
2081 }
Eric Laurent8838a382014-09-08 16:44:28 -07002082
Eric Laurent16c66dd2019-05-01 17:54:10 -07002083 // If haptic channel is specified, use the haptic output if present.
2084 // When using haptic output, same audio format and sample rate are required.
2085 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002086 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002087 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2088 continue;
2089 }
2090 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002091 && format == outputDesc->getFormat()
2092 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002093 currentMatchCriteria[0] = outputHapticChannelCount;
2094 }
2095
2096 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002097 const int matchingFunctionalFlags =
2098 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2099 const int totalFunctionalFlags =
2100 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2101 // Prefer matching functional flags, but subtract unnecessary functional flags.
2102 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002103
2104 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002105 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2106 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002107 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2108 channelCount <= outputChannelCount) {
2109 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002110 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2111 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002112 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002113 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002114 currentMatchCriteria[3] = outputChannelCount;
2115 }
2116
2117 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002118 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002119 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002120 }
2121
2122 // performance flags match
2123 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2124
2125 // format match
2126 if (format != AUDIO_FORMAT_INVALID) {
2127 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002128 PolicyAudioPort::kFormatDistanceMax -
2129 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002130 }
2131
2132 // primary output match
2133 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2134
2135 // compare match criteria by priority then value
2136 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2137 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2138 bestMatchCriteria = currentMatchCriteria;
2139 bestOutput = output;
2140
2141 std::stringstream result;
2142 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2143 std::ostream_iterator<int>(result, " "));
2144 ALOGV("%s new bestOutput %d criteria %s",
2145 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002146 }
2147 }
2148
Eric Laurent16c66dd2019-05-01 17:54:10 -07002149 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002150}
2151
Eric Laurent8fc147b2018-07-22 19:13:55 -07002152status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002153{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002154 ALOGV("%s portId %d", __FUNCTION__, portId);
2155
2156 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2157 if (outputDesc == 0) {
2158 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002159 return BAD_VALUE;
2160 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002161 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002162
Eric Laurent8fc147b2018-07-22 19:13:55 -07002163 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002164 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002165
Eric Laurent733ce942017-12-07 12:18:25 -08002166 status_t status = outputDesc->start();
2167 if (status != NO_ERROR) {
2168 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002169 }
2170
Eric Laurent97ac8712018-07-27 18:59:02 -07002171 uint32_t delayMs;
2172 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002173
2174 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002175 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002176 if (status == DEAD_OBJECT) {
2177 sp<SwAudioOutputDescriptor> desc =
2178 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2179 if (desc == nullptr) {
2180 // This is not common, it may indicate something wrong with the HAL.
2181 ALOGE("%s unable to open output with default config", __func__);
2182 return status;
2183 }
2184 desc->mUsePreferredMixerAttributes = true;
2185 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002186 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002187 }
jiabina84c3d32022-12-02 18:59:55 +00002188
2189 // If the client is the first one active on preferred mixer parameters, reopen the output
2190 // if the current mixer parameters doesn't match the preferred one.
2191 if (outputDesc->devices().size() == 1) {
2192 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2193 outputDesc->devices()[0]->getId(), client->strategy());
2194 if (info != nullptr && info->getUid() == client->uid()) {
2195 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2196 info->getConfigBase(), info->getFlags())) {
2197 stopSource(outputDesc, client);
2198 outputDesc->stop();
2199 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2200 config.channel_mask = info->getConfigBase().channel_mask;
2201 config.sample_rate = info->getConfigBase().sample_rate;
2202 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002203 sp<SwAudioOutputDescriptor> desc =
2204 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2205 if (desc == nullptr) {
2206 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002207 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002208 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002209 // Intentionally return error to let the client side resending request for
2210 // creating and starting.
2211 return DEAD_OBJECT;
2212 }
2213 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002214 if (info->getActiveClientCount() == 1 &&
2215 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2216 // If it is first bit-perfect client, reroute all clients that will be routed to
2217 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2218 PortHandleVector clientsToInvalidate;
2219 for (size_t i = 0; i < mOutputs.size(); i++) {
2220 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002221 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002222 continue;
2223 }
2224 for (const auto& c : mOutputs[i]->getClientIterable()) {
2225 clientsToInvalidate.push_back(c->portId());
2226 }
2227 }
2228 if (!clientsToInvalidate.empty()) {
2229 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2230 __func__);
2231 mpClientInterface->invalidateTracks(clientsToInvalidate);
2232 }
2233 }
jiabina84c3d32022-12-02 18:59:55 +00002234 }
2235 }
2236
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002237 if (client->hasPreferredDevice()) {
2238 // playback activity with preferred device impacts routing occurred, inform upper layers
2239 mpClientInterface->onRoutingUpdated();
2240 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002241 if (delayMs != 0) {
2242 usleep(delayMs * 1000);
2243 }
2244
2245 return status;
2246}
2247
Eric Laurent96d1dda2022-03-14 17:14:19 +01002248bool AudioPolicyManager::isLeUnicastActive() const {
2249 if (isInCall()) {
2250 return true;
2251 }
2252 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2253}
2254
2255bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2256 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2257 return false;
2258 }
2259 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2260 ALOGV("%s active %d", __func__, active);
2261 return active;
2262}
2263
Eric Laurent97ac8712018-07-27 18:59:02 -07002264status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2265 const sp<TrackClientDescriptor>& client,
2266 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002267{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002268 // cannot start playback of STREAM_TTS if any other output is being used
2269 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002270
2271 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002272 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002273 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002274 auto clientStrategy = client->strategy();
2275 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002276 if (stream == AUDIO_STREAM_TTS) {
2277 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002278 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002279 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002280 return INVALID_OPERATION;
2281 } else {
2282 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2283 }
2284 } else {
2285 // some playback other than beacon starts
2286 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2287 }
2288
Eric Laurent77305a62016-07-25 16:39:22 -07002289 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002290 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002291 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002292
François Gaffie11d30102018-11-02 16:09:09 +01002293 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002294 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002295 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002296 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002297 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002298 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002299 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002300 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002301 } else {
2302 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002303 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002304 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2305 AUDIO_FORMAT_DEFAULT);
2306 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2307 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002308 }
2309
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002310 // requiresMuteCheck is false when we can bypass mute strategy.
2311 // It covers a common case when there is no materially active audio
2312 // and muting would result in unnecessary delay and dropped audio.
2313 const uint32_t outputLatencyMs = outputDesc->latency();
2314 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002315 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002316
Eric Laurente552edb2014-03-10 17:42:56 -07002317 // increment usage count for this stream on the requested output:
2318 // NOTE that the usage count is the same for duplicated output and hardware output which is
2319 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002320 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002321
2322 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002323 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002324 // Preferred device may be exclusive, use only if no other active clients on this output
2325 devices = DeviceVector(
2326 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2327 } else {
2328 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2329 }
François Gaffie11d30102018-11-02 16:09:09 +01002330 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002331 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002332 }
2333 }
Eric Laurente552edb2014-03-10 17:42:56 -07002334
François Gaffiec005e562018-11-06 15:04:49 +01002335 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002336 selectOutputForMusicEffects();
2337 }
2338
François Gaffie1c878552018-11-22 16:53:21 +01002339 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002340 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002341 if (devices.isEmpty()) {
2342 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002343 }
François Gaffiec005e562018-11-06 15:04:49 +01002344 bool shouldWait =
2345 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2346 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2347 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002348 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002349 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002350 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002351 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002352 // An output has a shared device if
2353 // - managed by the same hw module
2354 // - supports the currently selected device
2355 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002356 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002357
Eric Laurent77305a62016-07-25 16:39:22 -07002358 // force a device change if any other output is:
2359 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002360 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002361 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002362 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002363 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002364 // change the device currently selected by the other output.
2365 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002366 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002367 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002368 force = true;
2369 }
2370 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002371 // a notification so that audio focus effect can propagate, or that a mute/unmute
2372 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002373 const uint32_t latencyMs = desc->latency();
2374 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2375
2376 if (shouldWait && isActive && (waitMs < latencyMs)) {
2377 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002378 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002379
2380 // Require mute check if another output is on a shared device
2381 // and currently active to have proper drain and avoid pops.
2382 // Note restoring AudioTracks onto this output needs to invoke
2383 // a volume ramp if there is no mute.
2384 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002385 }
2386 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002387
jiabin3ff8d7d2022-12-13 06:27:44 +00002388 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2389 // If the output is open with preferred mixer attributes, but the routed device is
2390 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2391 // changed.
2392 return DEAD_OBJECT;
2393 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002394 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302395 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2396 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002397
Eric Laurente552edb2014-03-10 17:42:56 -07002398 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002399 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002400 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002401 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002402 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002403 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002404 outputDesc->useHwGain() /*force*/)) {
2405 // request AudioService to reinitialize the volume curves asynchronously
2406 ALOGE("checkAndSetVolume failed, requesting volume range init");
2407 mpClientInterface->onVolumeRangeInitRequest();
2408 };
Eric Laurente552edb2014-03-10 17:42:56 -07002409
2410 // update the outputs if starting an output with a stream that can affect notification
2411 // routing
2412 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002413
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002414 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002415 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002416 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002417 }
Eric Laurentdc462862016-07-19 12:29:53 -07002418
2419 if (waitMs > muteWaitMs) {
2420 *delayMs = waitMs - muteWaitMs;
2421 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002422
2423 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2424 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2425 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2426 // change occurs after the MixerThread starts and causes a stream volume
2427 // glitch.
2428 //
2429 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002430 }
Eric Laurentdc462862016-07-19 12:29:53 -07002431
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002432 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002433 mEngine->getForceUse(
2434 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002435 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002436 }
2437
Eric Laurent97ac8712018-07-27 18:59:02 -07002438 // Automatically enable the remote submix input when output is started on a re routing mix
2439 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002440 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2441 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002442 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2443 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2444 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002445 "remote-submix",
2446 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002447 }
2448
Eric Laurent96d1dda2022-03-14 17:14:19 +01002449 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2450
Eric Laurente552edb2014-03-10 17:42:56 -07002451 return NO_ERROR;
2452}
2453
Eric Laurent96d1dda2022-03-14 17:14:19 +01002454void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2455 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2456 bool isUnicastActive = isLeUnicastActive();
2457
2458 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002459 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002460 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2461 for (size_t i = 0; i < mOutputs.size(); i++) {
2462 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2463 if (desc != ignoredOutput && desc->isActive()
2464 && ((isUnicastActive &&
2465 !desc->devices().
2466 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2467 || (wasUnicastActive &&
2468 !desc->devices().getDevicesFromTypes(
2469 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2470 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2471 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002472 if (desc->mUsePreferredMixerAttributes && force) {
2473 // If the device is using preferred mixer attributes, the output need to reopen
2474 // with default configuration when the new selected devices are different from
2475 // current routing devices.
2476 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2477 continue;
2478 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302479 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002480 // re-apply device specific volume if not done by setOutputDevice()
2481 if (!force) {
2482 applyStreamVolumes(desc, newDevices.types(), delayMs);
2483 }
2484 }
2485 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002486 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002487 }
2488}
2489
Eric Laurent8fc147b2018-07-22 19:13:55 -07002490status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002491{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002492 ALOGV("%s portId %d", __FUNCTION__, portId);
2493
2494 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2495 if (outputDesc == 0) {
2496 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002497 return BAD_VALUE;
2498 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002499 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002500
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002501 if (client->hasPreferredDevice(true)) {
2502 // playback activity with preferred device impacts routing occurred, inform upper layers
2503 mpClientInterface->onRoutingUpdated();
2504 }
2505
Eric Laurent97ac8712018-07-27 18:59:02 -07002506 ALOGV("stopOutput() output %d, stream %d, session %d",
2507 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002508
Eric Laurent97ac8712018-07-27 18:59:02 -07002509 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002510
Eric Laurent733ce942017-12-07 12:18:25 -08002511 if (status == NO_ERROR ) {
2512 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002513 } else {
2514 return status;
2515 }
2516
2517 if (outputDesc->devices().size() == 1) {
2518 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2519 outputDesc->devices()[0]->getId(), client->strategy());
2520 if (info != nullptr && info->getUid() == client->uid()) {
2521 info->decreaseActiveClient();
2522 if (info->getActiveClientCount() == 0) {
2523 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2524 }
2525 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002526 }
2527 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002528}
2529
Eric Laurent97ac8712018-07-27 18:59:02 -07002530status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2531 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002532{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002533 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002534 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002535 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002536 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002537
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002538 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2539
François Gaffie1c878552018-11-22 16:53:21 +01002540 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2541 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002542 // Automatically disable the remote submix input when output is stopped on a
2543 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002544 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002545 if (isSingleDeviceType(
2546 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002547 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002548 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002549 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2550 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002551 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002552 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002553 }
2554 }
2555 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002556 if (client->hasPreferredDevice(true) &&
2557 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002558 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002559 forceDeviceUpdate = true;
2560 }
2561
Eric Laurente552edb2014-03-10 17:42:56 -07002562 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002563 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002564
Eric Laurente552edb2014-03-10 17:42:56 -07002565 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002566 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002567 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002568 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002569
2570 // If the routing does not change, if an output is routed on a device using HwGain
2571 // (aka setAudioPortConfig) and there are still active clients following different
2572 // volume group(s), force reapply volume
2573 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2574 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2575
Eric Laurente552edb2014-03-10 17:42:56 -07002576 // delay the device switch by twice the latency because stopOutput() is executed when
2577 // the track stop() command is received and at that time the audio track buffer can
2578 // still contain data that needs to be drained. The latency only covers the audio HAL
2579 // and kernel buffers. Also the latency does not always include additional delay in the
2580 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302581 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002582 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002583
2584 // force restoring the device selection on other active outputs if it differs from the
2585 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002586 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002587 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002588 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002589 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002590 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002591 desc->isActive() &&
2592 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002593 (newDevices != desc->devices())) {
2594 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2595 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002596
jiabin3ff8d7d2022-12-13 06:27:44 +00002597 if (desc->mUsePreferredMixerAttributes && force) {
2598 // If the device is using preferred mixer attributes, the output need to
2599 // reopen with default configuration when the new selected devices are
2600 // different from current routing devices.
2601 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2602 continue;
2603 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302604 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002605
Eric Laurent57de36c2016-09-28 16:59:11 -07002606 // re-apply device specific volume if not done by setOutputDevice()
2607 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002608 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002609 }
Eric Laurente552edb2014-03-10 17:42:56 -07002610 }
2611 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002612 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002613 // update the outputs if stopping one with a stream that can affect notification routing
2614 handleNotificationRoutingForStream(stream);
2615 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002616
2617 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2618 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002619 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002620 }
2621
François Gaffiec005e562018-11-06 15:04:49 +01002622 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002623 selectOutputForMusicEffects();
2624 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002625
2626 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2627
Eric Laurente552edb2014-03-10 17:42:56 -07002628 return NO_ERROR;
2629 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002630 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002631 return INVALID_OPERATION;
2632 }
2633}
2634
jiabinbce0c1d2020-10-05 11:20:18 -07002635bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002636{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002637 ALOGV("%s portId %d", __FUNCTION__, portId);
2638
2639 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2640 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002641 // If an output descriptor is closed due to a device routing change,
2642 // then there are race conditions with releaseOutput from tracks
2643 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2644 // destroyed shortly thereafter.
2645 //
2646 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002647 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002648 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002649 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002650
2651 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002652
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302653 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2654 if (outputDesc->isClientActive(client)) {
2655 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2656 stopOutput(portId);
2657 }
2658
Eric Laurent8fc147b2018-07-22 19:13:55 -07002659 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2660 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002661 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002662 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002663 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002664 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002665 if (--outputDesc->mDirectOpenCount == 0) {
2666 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002667 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002668 }
2669 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302670
Andy Hung39efb7a2018-09-26 15:39:28 -07002671 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002672 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2673 // The output is pending reopened to query dynamic profiles and
2674 // there is no active clients
2675 closeOutput(outputDesc->mIoHandle);
2676 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2677 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2678 if (newOutputDesc == nullptr) {
2679 ALOGE("%s failed to open output", __func__);
2680 }
2681 return true;
2682 }
2683 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002684}
2685
Eric Laurentcaf7f482014-11-25 17:50:47 -08002686status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2687 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002688 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002689 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002690 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002691 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002692 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002693 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002694 input_type_t *inputType,
2695 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002696{
François Gaffiec005e562018-11-06 15:04:49 +01002697 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002698 "flags %#x attributes=%s requested device ID %d",
2699 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2700 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002701
Eric Laurentad2e7b92017-09-14 20:06:42 -07002702 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002703 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002704 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002705 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002706 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002707 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002708 sp<RecordClientDescriptor> clientDesc;
2709 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002710 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002711 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002712
2713 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2714 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2715 return INVALID_OPERATION;
2716 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002717
Francois Gaffie716e1432019-01-14 16:58:59 +01002718 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2719 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002720 }
2721
Paul McLean466dc8e2015-04-17 13:15:36 -06002722 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002723 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002724 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002725
Eric Laurentad2e7b92017-09-14 20:06:42 -07002726 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2727 // possible
2728 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2729 *input != AUDIO_IO_HANDLE_NONE) {
2730 ssize_t index = mInputs.indexOfKey(*input);
2731 if (index < 0) {
2732 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2733 status = BAD_VALUE;
2734 goto error;
2735 }
2736 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002737 RecordClientVector clients = inputDesc->getClientsForSession(session);
2738 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002739 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2740 status = BAD_VALUE;
2741 goto error;
2742 }
2743 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2744 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002745 // corresponds to a new client and is only permitted from the same UID.
2746 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002747 if (clients.size() > 1) {
2748 for (const auto& client : clients) {
2749 // The client map is ordered by key values (portId) and portIds are allocated
2750 // incrementaly. So the first client in this list is the one opened by audio flinger
2751 // when the mmap stream is created and should be ignored as it does not correspond
2752 // to an actual client
2753 if (client == *clients.cbegin()) {
2754 continue;
2755 }
2756 if (uid != client->uid() && !client->isSilenced()) {
2757 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2758 uid, client->portId(), client->uid());
2759 status = INVALID_OPERATION;
2760 goto error;
2761 }
Eric Laurent331679c2018-04-16 17:03:16 -07002762 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002763 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002764 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002765 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002766
Eric Laurentfecbceb2021-02-09 14:46:43 +01002767 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002768 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002769 }
2770
2771 *input = AUDIO_IO_HANDLE_NONE;
2772 *inputType = API_INPUT_INVALID;
2773
Francois Gaffie716e1432019-01-14 16:58:59 +01002774 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002775 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002776 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002777 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002778 ALOGW("%s could not find input mix for attr %s",
2779 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002780 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002781 }
jiabinc1de2df2019-05-07 14:26:40 -07002782 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2783 String8(attr->tags + strlen("addr=")),
2784 AUDIO_FORMAT_DEFAULT);
2785 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002786 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002787 __func__, attributes.source, attributes.tags);
2788 status = BAD_VALUE;
2789 goto error;
2790 }
2791
Kevin Rocard25f9b052019-02-27 15:08:54 -08002792 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2793 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2794 } else {
2795 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2796 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002797 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002798 if (explicitRoutingDevice != nullptr) {
2799 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002800 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002801 // Prevent from storing invalid requested device id in clients
2802 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002803 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002804 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2805 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002806 }
François Gaffie11d30102018-11-02 16:09:09 +01002807 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002808 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002809 status = BAD_VALUE;
2810 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002811 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002812 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2813 *inputType = API_INPUT_MIX_CAPTURE;
2814 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002815 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2816 // there is an external policy, but this input is attached to a mix of recorders,
2817 // meaning it receives audio injected into the framework, so the recorder doesn't
2818 // know about it and is therefore considered "legacy"
2819 *inputType = API_INPUT_LEGACY;
2820 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002821 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002822 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002823 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002824 } else {
2825 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002826 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002827
Eric Laurent599c7582015-12-07 18:05:55 -08002828 }
2829
François Gaffiec005e562018-11-06 15:04:49 +01002830 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002831 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002832 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002833 AudioProfileVector profiles;
2834 status_t ret = getProfilesForDevices(
2835 DeviceVector(device), profiles, flags, true /*isInput*/);
2836 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002837 const auto channels = profiles[0]->getChannels();
2838 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2839 config->channel_mask = *channels.begin();
2840 }
2841 const auto sampleRates = profiles[0]->getSampleRates();
2842 if (!sampleRates.empty() &&
2843 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2844 config->sample_rate = *sampleRates.begin();
2845 }
jiabinf1c73972022-04-14 16:28:52 -07002846 config->format = profiles[0]->getFormat();
2847 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002848 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002849 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002850
Eric Laurent8f42ea12018-08-08 09:08:25 -07002851exit:
2852
François Gaffiec005e562018-11-06 15:04:49 +01002853 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2854 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002855
Francois Gaffie716e1432019-01-14 16:58:59 +01002856 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002857 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002858 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002859
Mikhail Naganov2996f672019-04-18 12:29:59 -07002860 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002861 requestedDeviceId, attributes.source, flags,
2862 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002863 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002864 // Move (if found) effect for the client session to its input
2865 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002866 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002867
2868 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2869 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002870
Eric Laurent599c7582015-12-07 18:05:55 -08002871 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002872
2873error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002874 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002875}
2876
2877
François Gaffie11d30102018-11-02 16:09:09 +01002878audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002879 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002880 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002881 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002882 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002883 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002884{
2885 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002886 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002887 bool isSoundTrigger = false;
2888
François Gaffiec005e562018-11-06 15:04:49 +01002889 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002890 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2891 if (index >= 0) {
2892 input = mSoundTriggerSessions.valueFor(session);
2893 isSoundTrigger = true;
2894 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2895 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2896 } else {
2897 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002898 }
François Gaffiec005e562018-11-06 15:04:49 +01002899 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002900 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002901 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002902 }
2903
Carter Hsua3abb402021-10-26 11:11:20 +08002904 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2905 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2906 }
2907
Eric Laurentfe231122017-11-17 17:48:06 -08002908 // sampling rate and flags may be updated by getInputProfile
2909 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2910 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002911 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002912 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002913 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002914 // find a compatible input profile (not necessarily identical in parameters)
2915 sp<IOProfile> profile = getInputProfile(
2916 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2917 if (profile == nullptr) {
2918 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002919 }
jiabin2fd710d2022-05-02 23:20:22 +00002920
Glenn Kasten05ddca52016-02-11 08:17:12 -08002921 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002922 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002923 if (samplingRate == 0) {
2924 samplingRate = profileSamplingRate;
2925 }
Eric Laurente552edb2014-03-10 17:42:56 -07002926
Eric Laurent322b4d22015-04-03 15:57:54 -07002927 if (profile->getModuleHandle() == 0) {
2928 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002929 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002930 }
2931
Eric Laurentec376dc2021-04-08 20:41:22 +02002932 // Reuse an already opened input if a client with the same session ID already exists
2933 // on that input
2934 for (size_t i = 0; i < mInputs.size(); i++) {
2935 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2936 if (desc->mProfile != profile) {
2937 continue;
2938 }
2939 RecordClientVector clients = desc->clientsList();
2940 for (const auto &client : clients) {
2941 if (session == client->session()) {
2942 return desc->mIoHandle;
2943 }
2944 }
2945 }
2946
Eric Laurent3974e3b2017-12-07 17:58:43 -08002947 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002948 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002949 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002950 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002951 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002952 continue;
2953 }
2954 // if sound trigger, reuse input if used by other sound trigger on same session
2955 // else
2956 // reuse input if active client app is not in IDLE state
2957 //
2958 RecordClientVector clients = desc->clientsList();
2959 bool doClose = false;
2960 for (const auto& client : clients) {
2961 if (isSoundTrigger != client->isSoundTrigger()) {
2962 continue;
2963 }
2964 if (client->isSoundTrigger()) {
2965 if (session == client->session()) {
2966 return desc->mIoHandle;
2967 }
2968 continue;
2969 }
2970 if (client->active() && client->appState() != APP_STATE_IDLE) {
2971 return desc->mIoHandle;
2972 }
2973 doClose = true;
2974 }
2975 if (doClose) {
2976 closeInput(desc->mIoHandle);
2977 } else {
2978 i++;
2979 }
2980 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002981 }
2982
Eric Laurentfe231122017-11-17 17:48:06 -08002983 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002984
Eric Laurentfe231122017-11-17 17:48:06 -08002985 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2986 lConfig.sample_rate = profileSamplingRate;
2987 lConfig.channel_mask = profileChannelMask;
2988 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002989
François Gaffie11d30102018-11-02 16:09:09 +01002990 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002991
2992 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002993 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002994 (profileSamplingRate != lConfig.sample_rate) ||
2995 !audio_formats_match(profileFormat, lConfig.format) ||
2996 (profileChannelMask != lConfig.channel_mask)) {
2997 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002998 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002999 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003000 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003001 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003002 }
Eric Laurent599c7582015-12-07 18:05:55 -08003003 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003004 }
3005
Eric Laurentc722f302014-12-10 11:21:49 -08003006 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003007
Eric Laurent599c7582015-12-07 18:05:55 -08003008 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003009 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003010
Eric Laurent599c7582015-12-07 18:05:55 -08003011 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003012}
3013
Eric Laurent4eb58f12018-12-07 16:41:02 -08003014status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003015{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003016 ALOGV("%s portId %d", __FUNCTION__, portId);
3017
3018 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3019 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003020 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003021 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003022 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003023 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003024 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003025 if (client->active()) {
3026 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3027 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003028 }
3029
Eric Laurent8f42ea12018-08-08 09:08:25 -07003030 audio_session_t session = client->session();
3031
Eric Laurent4eb58f12018-12-07 16:41:02 -08003032 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003033
Eric Laurent4eb58f12018-12-07 16:41:02 -08003034 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003035
Eric Laurent4eb58f12018-12-07 16:41:02 -08003036 status_t status = inputDesc->start();
3037 if (status != NO_ERROR) {
3038 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003039 }
Eric Laurente552edb2014-03-10 17:42:56 -07003040
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003041 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003042 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003043 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003044
Eric Laurent8f42ea12018-08-08 09:08:25 -07003045 // indicate active capture to sound trigger service if starting capture from a mic on
3046 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003047 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003048 if (device != nullptr) {
3049 status = setInputDevice(input, device, true /* force */);
3050 } else {
3051 ALOGW("%s no new input device can be found for descriptor %d",
3052 __FUNCTION__, inputDesc->getId());
3053 status = BAD_VALUE;
3054 }
Eric Laurente552edb2014-03-10 17:42:56 -07003055
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003056 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003057 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003058 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003059 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003060 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3061 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003062 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003063 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003064
François Gaffie11d30102018-11-02 16:09:09 +01003065 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3066 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003067 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003068 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003069 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003070
Eric Laurent8f42ea12018-08-08 09:08:25 -07003071 // automatically enable the remote submix output when input is started if not
3072 // used by a policy mix of type MIX_TYPE_RECORDERS
3073 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003074 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003075 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003076 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003077 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003078 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3079 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003080 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003081 if (address != "") {
3082 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3083 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003084 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003085 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003086 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003087 } else if (status != NO_ERROR) {
3088 // Restore client activity state.
3089 inputDesc->setClientActive(client, false);
3090 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003091 }
3092
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003093 ALOGV("%s input %d source = %d status = %d exit",
3094 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003095
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003096 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003097}
3098
Eric Laurent8fc147b2018-07-22 19:13:55 -07003099status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003100{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003101 ALOGV("%s portId %d", __FUNCTION__, portId);
3102
3103 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3104 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003105 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003106 return BAD_VALUE;
3107 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003108 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003109 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003110 if (!client->active()) {
3111 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003112 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003113 }
Carter Hsue6139d52021-07-08 10:30:20 +08003114 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003115 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003116
Eric Laurent8f42ea12018-08-08 09:08:25 -07003117 inputDesc->stop();
3118 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003119 auto current_source = inputDesc->source();
3120 setInputDevice(input, getNewInputDevice(inputDesc),
3121 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003122 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003123 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003124 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003125 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003126 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3127 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003128 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003129 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003130
3131 // automatically disable the remote submix output when input is stopped if not
3132 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003133 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003134 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003135 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003136 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003137 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3138 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003139 }
3140 if (address != "") {
3141 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3142 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003143 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003144 }
3145 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003146 resetInputDevice(input);
3147
3148 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3149 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003150 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3151 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003152 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003153 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003154 }
3155 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003156 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003157 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003158}
3159
Eric Laurent8fc147b2018-07-22 19:13:55 -07003160void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003161{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003162 ALOGV("%s portId %d", __FUNCTION__, portId);
3163
3164 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3165 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003166 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003167 return;
3168 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003169 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003170 audio_io_handle_t input = inputDesc->mIoHandle;
3171
Eric Laurent8f42ea12018-08-08 09:08:25 -07003172 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003173
Andy Hung39efb7a2018-09-26 15:39:28 -07003174 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003175 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003176 if (inputDesc->getClientCount() > 0) {
3177 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003178 return;
3179 }
3180
Eric Laurent05b90f82014-08-27 15:32:29 -07003181 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003182 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003183 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003184}
3185
Eric Laurent8f42ea12018-08-08 09:08:25 -07003186void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003187{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003188 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003189
3190 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003191 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003192 }
3193}
3194
Eric Laurent8f42ea12018-08-08 09:08:25 -07003195void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3196{
3197 stopInput(portId);
3198 releaseInput(portId);
3199}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003200
Eric Laurent0dd51852019-04-19 18:18:58 -07003201void AudioPolicyManager::checkCloseInputs() {
3202 // After connecting or disconnecting an input device, close input if:
3203 // - it has no client (was just opened to check profile) OR
3204 // - none of its supported devices are connected anymore OR
3205 // - one of its clients cannot be routed to one of its supported
3206 // devices anymore. Otherwise update device selection
3207 std::vector<audio_io_handle_t> inputsToClose;
3208 for (size_t i = 0; i < mInputs.size(); i++) {
3209 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3210 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003211 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003212 inputsToClose.push_back(mInputs.keyAt(i));
3213 } else {
3214 bool close = false;
3215 for (const auto& client : input->clientsList()) {
3216 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003217 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3218 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003219 if (!input->supportedDevices().contains(device)) {
3220 close = true;
3221 break;
3222 }
3223 }
3224 if (close) {
3225 inputsToClose.push_back(mInputs.keyAt(i));
3226 } else {
3227 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3228 }
3229 }
3230 }
3231
3232 for (const audio_io_handle_t handle : inputsToClose) {
3233 ALOGV("%s closing input %d", __func__, handle);
3234 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003235 }
Eric Laurentd4692962014-05-05 18:13:44 -07003236}
3237
François Gaffie251c7f02018-11-07 10:41:08 +01003238void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003239{
3240 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003241 if (indexMin < 0 || indexMax < 0) {
3242 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3243 return;
3244 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003245 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003246
3247 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003248 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3249 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003250 continue;
3251 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003252 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003253 }
Eric Laurente552edb2014-03-10 17:42:56 -07003254}
3255
Eric Laurente0720872014-03-11 09:30:41 -07003256status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003257 int index,
3258 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003259{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003260 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003261 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3262 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3263 return NO_ERROR;
3264 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003265 ALOGV("%s: stream %s attributes=%s", __func__,
3266 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003267 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003268}
3269
Eric Laurente0720872014-03-11 09:30:41 -07003270status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003271 int *index,
3272 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003273{
François Gaffiec005e562018-11-06 15:04:49 +01003274 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3275 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003276 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003277 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003278 deviceTypes = mEngine->getOutputDevicesForStream(
3279 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003280 }
jiabin9a3361e2019-10-01 09:38:30 -07003281 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003282}
3283
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003284status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003285 int index,
3286 audio_devices_t device)
3287{
3288 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003289 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3290 if (group == VOLUME_GROUP_NONE) {
3291 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003292 return BAD_VALUE;
3293 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003294 ALOGV("%s: group %d matching with %s index %d",
3295 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003296 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003297 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003298 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003299 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3300 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3301 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3302 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003303 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3304
3305 status = setVolumeCurveIndex(index, device, curves);
3306 if (status != NO_ERROR) {
3307 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3308 return status;
3309 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003310
jiabin9a3361e2019-10-01 09:38:30 -07003311 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003312 auto curCurvAttrs = curves.getAttributes();
3313 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3314 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003315 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003316 } else if (!curves.getStreamTypes().empty()) {
3317 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003318 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003319 } else {
3320 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3321 return BAD_VALUE;
3322 }
jiabin9a3361e2019-10-01 09:38:30 -07003323 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3324 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003325
François Gaffiecfe17322018-11-07 13:41:29 +01003326 // update volume on all outputs and streams matching the following:
3327 // - The requested stream (or a stream matching for volume control) is active on the output
3328 // - The device (or devices) selected by the engine for this stream includes
3329 // the requested device
3330 // - For non default requested device, currently selected device on the output is either the
3331 // requested device or one of the devices selected by the engine for this stream
3332 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3333 // no specific device volume value exists for currently selected device.
Henrik Backlund18373a32024-01-24 10:26:42 +01003334 // - Only apply the volume if the requested device is the desired device for volume control.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003335 for (size_t i = 0; i < mOutputs.size(); i++) {
3336 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003337 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003338
jiabin9a3361e2019-10-01 09:38:30 -07003339 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3340 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003341 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003342
3343 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003344 continue;
3345 }
3346 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3347 curDevices.find(device) == curDevices.end()) {
3348 continue;
3349 }
3350 bool applyVolume = false;
3351 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3352 curSrcDevices.insert(device);
3353 applyVolume = (curSrcDevices.find(
Henrik Backlund18373a32024-01-24 10:26:42 +01003354 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end())
3355 && Volume::getDeviceForVolume(curSrcDevices) == device;
François Gaffieed91f582020-01-31 10:35:37 +01003356 } else {
3357 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3358 }
3359 if (!applyVolume) {
3360 continue; // next output
3361 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003362 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3363 // If a higher priority strategy is active, and the output is routed to a device with a
3364 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003365 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003366 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003367 // If the volume source is active with higher priority source, ensure at least Sw Muted
3368 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003369 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3370 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3371 false /*preferredDevice*/);
3372 if (activeClients.empty()) {
3373 continue;
3374 }
3375 bool isPreempted = false;
3376 bool isHigherPriority = productStrategy < strategy;
3377 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003378 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003379 ALOGV("%s: Strategy=%d (\nrequester:\n"
3380 " group %d, volumeGroup=%d attributes=%s)\n"
3381 " higher priority source active:\n"
3382 " volumeGroup=%d attributes=%s) \n"
3383 " on output %zu, bailing out", __func__, productStrategy,
3384 group, group, toString(attributes).c_str(),
3385 client->volumeSource(), toString(client->attributes()).c_str(), i);
3386 applyVolume = false;
3387 isPreempted = true;
3388 break;
3389 }
3390 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003391 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003392 applyVolume = true;
3393 }
3394 }
3395 if (isPreempted || applyVolume) {
3396 break;
3397 }
3398 }
3399 if (!applyVolume) {
3400 continue; // next output
3401 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003402 }
François Gaffieed91f582020-01-31 10:35:37 +01003403 //FIXME: workaround for truncated touch sounds
3404 // delayed volume change for system stream to be removed when the problem is
3405 // handled by system UI
3406 status_t volStatus = checkAndSetVolume(
3407 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003408 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003409 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3410 if (volStatus != NO_ERROR) {
3411 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003412 }
3413 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003414
3415 // update voice volume if the an active call route exists
3416 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3417 && (curSrcDevices.find(
3418 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3419 != curSrcDevices.end())) {
3420 bool isVoiceVolSrc;
3421 bool isBtScoVolSrc;
3422 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3423 isVoiceVolSrc, isBtScoVolSrc, __func__)
3424 && (isVoiceVolSrc || isBtScoVolSrc)) {
3425 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3426 }
3427 }
3428
François Gaffiecfe17322018-11-07 13:41:29 +01003429 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3430 return status;
3431}
3432
François Gaffieaaac0fd2018-11-22 17:56:39 +01003433status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003434 audio_devices_t device,
3435 IVolumeCurves &volumeCurves)
3436{
3437 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3438 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003439 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3440 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003441 (index > volumeCurves.getVolumeIndexMax())) {
3442 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3443 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3444 return BAD_VALUE;
3445 }
3446 if (!audio_is_output_device(device)) {
3447 return BAD_VALUE;
3448 }
3449
3450 // Force max volume if stream cannot be muted
3451 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3452
François Gaffieaaac0fd2018-11-22 17:56:39 +01003453 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003454 volumeCurves.addCurrentVolumeIndex(device, index);
3455 return NO_ERROR;
3456}
3457
3458status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3459 int &index,
3460 audio_devices_t device)
3461{
3462 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3463 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003464 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003465 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003466 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003467 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003468 }
jiabin9a3361e2019-10-01 09:38:30 -07003469 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003470}
3471
3472status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3473 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003474 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003475{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003476 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003477 return BAD_VALUE;
3478 }
jiabin9a3361e2019-10-01 09:38:30 -07003479 index = curves.getVolumeIndex(deviceTypes);
3480 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003481 return NO_ERROR;
3482}
3483
3484status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3485 int &index)
3486{
3487 index = getVolumeCurves(attr).getVolumeIndexMin();
3488 return NO_ERROR;
3489}
3490
3491status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3492 int &index)
3493{
3494 index = getVolumeCurves(attr).getVolumeIndexMax();
3495 return NO_ERROR;
3496}
3497
Eric Laurent36829f92017-04-07 19:04:42 -07003498audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003499{
3500 // select one output among several suitable for global effects.
3501 // The priority is as follows:
3502 // 1: An offloaded output. If the effect ends up not being offloadable,
3503 // AudioFlinger will invalidate the track and the offloaded output
3504 // will be closed causing the effect to be moved to a PCM output.
3505 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003506 // 3: The primary output
3507 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003508
François Gaffiec005e562018-11-06 15:04:49 +01003509 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3510 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003511 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003512
Eric Laurent36829f92017-04-07 19:04:42 -07003513 if (outputs.size() == 0) {
3514 return AUDIO_IO_HANDLE_NONE;
3515 }
Eric Laurente552edb2014-03-10 17:42:56 -07003516
Eric Laurent36829f92017-04-07 19:04:42 -07003517 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3518 bool activeOnly = true;
3519
3520 while (output == AUDIO_IO_HANDLE_NONE) {
3521 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3522 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3523 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3524
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003525 for (audio_io_handle_t output : outputs) {
3526 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003527 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003528 continue;
3529 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003530 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3531 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003532 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003533 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003534 }
3535 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003536 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003537 }
3538 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003539 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003540 }
3541 }
3542 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3543 output = outputOffloaded;
3544 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3545 output = outputDeepBuffer;
3546 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3547 output = outputPrimary;
3548 } else {
3549 output = outputs[0];
3550 }
3551 activeOnly = false;
3552 }
3553
3554 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003555 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3556 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003557 mMusicEffectOutput = output;
3558 }
3559
3560 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003561 return output;
3562}
3563
Eric Laurent36829f92017-04-07 19:04:42 -07003564audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3565{
3566 return selectOutputForMusicEffects();
3567}
3568
Eric Laurente0720872014-03-11 09:30:41 -07003569status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003570 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003571 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003572 int session,
3573 int id)
3574{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003575 if (session != AUDIO_SESSION_DEVICE) {
3576 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003577 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003578 index = mInputs.indexOfKey(io);
3579 if (index < 0) {
3580 ALOGW("registerEffect() unknown io %d", io);
3581 return INVALID_OPERATION;
3582 }
Eric Laurente552edb2014-03-10 17:42:56 -07003583 }
3584 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003585 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3586 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3587 || strategy == PRODUCT_STRATEGY_NONE));
3588 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003589}
3590
Eric Laurentc241b0d2018-11-28 09:08:49 -08003591status_t AudioPolicyManager::unregisterEffect(int id)
3592{
3593 if (mEffects.getEffect(id) == nullptr) {
3594 return INVALID_OPERATION;
3595 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003596 if (mEffects.isEffectEnabled(id)) {
3597 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3598 setEffectEnabled(id, false);
3599 }
3600 return mEffects.unregisterEffect(id);
3601}
3602
3603status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3604{
3605 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3606 if (effect == nullptr) {
3607 return INVALID_OPERATION;
3608 }
3609
3610 status_t status = mEffects.setEffectEnabled(id, enabled);
3611 if (status == NO_ERROR) {
3612 mInputs.trackEffectEnabled(effect, enabled);
3613 }
3614 return status;
3615}
3616
Eric Laurent6c796322019-04-09 14:13:17 -07003617
3618status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3619{
3620 mEffects.moveEffects(ids, io);
3621 return NO_ERROR;
3622}
3623
Eric Laurentc75307b2015-03-17 15:29:32 -07003624bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3625{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003626 auto vs = toVolumeSource(stream, false);
3627 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003628}
3629
3630bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3631{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003632 auto vs = toVolumeSource(stream, false);
3633 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003634}
3635
Eric Laurente0720872014-03-11 09:30:41 -07003636bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003637{
3638 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003639 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003640 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003641 return true;
3642 }
3643 }
3644 return false;
3645}
3646
Eric Laurent275e8e92014-11-30 15:14:47 -08003647// Register a list of custom mixes with their attributes and format.
3648// When a mix is registered, corresponding input and output profiles are
3649// added to the remote submix hw module. The profile contains only the
3650// parameters (sampling rate, format...) specified by the mix.
3651// The corresponding input remote submix device is also connected.
3652//
3653// When a remote submix device is connected, the address is checked to select the
3654// appropriate profile and the corresponding input or output stream is opened.
3655//
3656// When capture starts, getInputForAttr() will:
3657// - 1 look for a mix matching the address passed in attribtutes tags if any
3658// - 2 if none found, getDeviceForInputSource() will:
3659// - 2.1 look for a mix matching the attributes source
3660// - 2.2 if none found, default to device selection by policy rules
3661// At this time, the corresponding output remote submix device is also connected
3662// and active playback use cases can be transferred to this mix if needed when reconnecting
3663// after AudioTracks are invalidated
3664//
3665// When playback starts, getOutputForAttr() will:
3666// - 1 look for a mix matching the address passed in attribtutes tags if any
3667// - 2 if none found, look for a mix matching the attributes usage
3668// - 3 if none found, default to device and output selection by policy rules.
3669
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003670status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003671{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003672 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3673 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003674 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003675 sp<HwModule> rSubmixModule;
3676 // examine each mix's route type
3677 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003678 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003679 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3680 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3681 ALOGE("Unsupported Policy Mix %zu of %zu: "
3682 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3683 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003684 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003685 break;
3686 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003687 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3688 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003689 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003690 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3691 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003692 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003693 rSubmixModule = mHwModules.getModuleFromName(
3694 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3695 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003696 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003697 i);
3698 res = INVALID_OPERATION;
3699 break;
3700 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003701 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003702
Eric Laurent97ac8712018-07-27 18:59:02 -07003703 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003704 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003705 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003706 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003707 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3708 } else {
3709 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3710 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003711 }
François Gaffie036e1e92015-03-19 10:16:24 +01003712
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003713 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003714 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003715 res = INVALID_OPERATION;
3716 break;
3717 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003718 audio_config_t outputConfig = mix.mFormat;
3719 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003720 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3721 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003722 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3723 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003724 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003725 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3726 audio_is_linear_pcm(outputConfig.format)
3727 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003728 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003729 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3730 audio_is_linear_pcm(inputConfig.format)
3731 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003732
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003733 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003734 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003735 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003736 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003737 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003738 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003739 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003740 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3741 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003742 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003743 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003744 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003745
3746 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3747 mix.mDeviceType, mix.mDeviceAddress,
3748 String8(), AUDIO_FORMAT_DEFAULT);
3749 if (device == nullptr) {
3750 res = INVALID_OPERATION;
3751 break;
3752 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003753
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003754 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003755 // First try to find an already opened output supporting the device
3756 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003757 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003758
Eric Laurentc529cf62020-04-17 18:19:10 -07003759 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003760 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003761 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003762 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003763 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003764 } else {
3765 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003766 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003767 }
3768 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003769 // If no output found, try to find a direct output profile supporting the device
3770 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3771 sp<HwModule> module = mHwModules[i];
3772 for (size_t j = 0;
3773 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3774 j++) {
3775 sp<IOProfile> profile = module->getOutputProfiles()[j];
3776 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3777 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3778 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003779 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003780 res = INVALID_OPERATION;
3781 } else {
3782 foundOutput = true;
3783 }
3784 }
3785 }
3786 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003787 if (res != NO_ERROR) {
3788 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003789 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003790 res = INVALID_OPERATION;
3791 break;
3792 } else if (!foundOutput) {
3793 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003794 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003795 res = INVALID_OPERATION;
3796 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003797 } else {
3798 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003799 }
Eric Laurentc722f302014-12-10 11:21:49 -08003800 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003801 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003802 if (res != NO_ERROR) {
3803 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003804 } else if (checkOutputs) {
3805 checkForDeviceAndOutputChanges();
3806 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003807 }
3808 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003809}
3810
3811status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3812{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003813 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003814 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003815 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003816 sp<HwModule> rSubmixModule;
3817 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003818 for (const auto& mix : mixes) {
3819 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003820
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003821 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003822 rSubmixModule = mHwModules.getModuleFromName(
3823 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3824 if (rSubmixModule == 0) {
3825 res = INVALID_OPERATION;
3826 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003827 }
3828 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003829
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003830 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003831
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003832 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003833 res = INVALID_OPERATION;
3834 continue;
3835 }
3836
Kevin Rocard04ed0462019-05-02 17:53:24 -07003837 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003838 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003839 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3840 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003841 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003842 AUDIO_FORMAT_DEFAULT);
3843 if (res != OK) {
3844 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003845 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003846 }
3847 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003848 }
jiabin5740f082019-08-19 15:08:30 -07003849 rSubmixModule->removeOutputProfile(address.c_str());
3850 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003851
Kevin Rocard153f92d2018-12-18 18:33:28 -08003852 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003853 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003854 res = INVALID_OPERATION;
3855 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003856 } else {
3857 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003858 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003859 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003860 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003861 if (res == NO_ERROR && checkOutputs) {
3862 checkForDeviceAndOutputChanges();
3863 updateCallAndOutputRouting();
3864 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003865 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003866}
3867
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003868status_t AudioPolicyManager::updatePolicyMix(
3869 const AudioMix& mix,
3870 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3871 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3872 if (res == NO_ERROR) {
3873 checkForDeviceAndOutputChanges();
3874 updateCallAndOutputRouting();
3875 }
3876 return res;
3877}
3878
Mikhail Naganov100f0122018-11-29 11:22:16 -08003879void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3880{
3881 size_t i = 0;
3882 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3883 for (const auto& fmt : mManualSurroundFormats) {
3884 if (i++ != 0) dst->append(", ");
3885 std::string sfmt;
3886 FormatConverter::toString(fmt, sfmt);
3887 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3888 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3889 }
3890}
3891
Eric Laurentc529cf62020-04-17 18:19:10 -07003892// Returns true if all devices types match the predicate and are supported by one HW module
3893bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003894 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003895 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003896 const char *context,
3897 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003898 for (size_t i = 0; i < devices.size(); i++) {
3899 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003900 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003901 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003902 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003903 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003904 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003905 return false;
3906 }
3907 }
3908 return true;
3909}
3910
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003911void AudioPolicyManager::changeOutputDevicesMuteState(
3912 const AudioDeviceTypeAddrVector& devices) {
3913 ALOGVV("%s() num devices %zu", __func__, devices.size());
3914
3915 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3916 getSoftwareOutputsForDevices(devices);
3917
3918 for (size_t i = 0; i < outputs.size(); i++) {
3919 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3920 DeviceVector prevDevices = outputDesc->devices();
3921 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3922 }
3923}
3924
3925std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3926 const AudioDeviceTypeAddrVector& devices) const
3927{
3928 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3929 DeviceVector deviceDescriptors;
3930 for (size_t j = 0; j < devices.size(); j++) {
3931 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3932 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3933 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3934 ALOGE("%s: device type %#x address %s not supported or not an output device",
3935 __func__, devices[j].mType, devices[j].getAddress());
3936 continue;
3937 }
3938 deviceDescriptors.add(desc);
3939 }
3940 for (size_t i = 0; i < mOutputs.size(); i++) {
3941 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3942 continue;
3943 }
3944 outputs.push_back(mOutputs.valueAt(i));
3945 }
3946 return outputs;
3947}
3948
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003949status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003950 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003951 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003952 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3953 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003954 }
3955 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003956 if (res != NO_ERROR) {
3957 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3958 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003959 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003960
3961 checkForDeviceAndOutputChanges();
3962 updateCallAndOutputRouting();
3963
3964 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003965}
3966
3967status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3968 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003969 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3970 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003971 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003972 __FUNCTION__, uid);
3973 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003974 }
3975
Eric Laurentc529cf62020-04-17 18:19:10 -07003976 checkForDeviceAndOutputChanges();
3977 updateCallAndOutputRouting();
3978
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003979 return res;
3980}
3981
Eric Laurent2517af32020-11-25 15:31:27 +01003982
jiabin0a488932020-08-07 17:32:40 -07003983status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3984 device_role_t role,
3985 const AudioDeviceTypeAddrVector &devices) {
3986 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3987 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003988
Eric Laurentc529cf62020-04-17 18:19:10 -07003989 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003990 return BAD_VALUE;
3991 }
jiabin0a488932020-08-07 17:32:40 -07003992 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003993 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003994 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3995 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003996 return status;
3997 }
3998
3999 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004000
4001 bool forceVolumeReeval = false;
4002 // FIXME: workaround for truncated touch sounds
4003 // to be removed when the problem is handled by system UI
4004 uint32_t delayMs = 0;
4005 if (strategy == mCommunnicationStrategy) {
4006 forceVolumeReeval = true;
4007 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4008 updateInputRouting();
4009 }
4010 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004011
4012 return NO_ERROR;
4013}
4014
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004015void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4016 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004017{
4018 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004019 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004020 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004021 // Only apply special touch sound delay once
4022 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004023 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004024 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004025 for (size_t i = 0; i < mOutputs.size(); i++) {
4026 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4027 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004028 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4029 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004030 // As done in setDeviceConnectionState, we could also fix default device issue by
4031 // preventing the force re-routing in case of default dev that distinguishes on address.
4032 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004033 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004034 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4035 // If the device is using preferred mixer attributes, the output need to reopen
4036 // with default configuration when the new selected devices are different from
4037 // current routing devices.
4038 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4039 continue;
4040 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304041
4042 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4043 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004044 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004045 // Only apply special touch sound delay once
4046 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004047 }
4048 if (forceVolumeReeval && !newDevices.isEmpty()) {
4049 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4050 }
4051 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004052 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004053 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004054}
4055
Eric Laurent2517af32020-11-25 15:31:27 +01004056void AudioPolicyManager::updateInputRouting() {
4057 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304058 // Skip for hotword recording as the input device switch
4059 // is handled within sound trigger HAL
4060 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4061 continue;
4062 }
Eric Laurent2517af32020-11-25 15:31:27 +01004063 auto newDevice = getNewInputDevice(activeDesc);
4064 // Force new input selection if the new device can not be reached via current input
4065 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4066 setInputDevice(activeDesc->mIoHandle, newDevice);
4067 } else {
4068 closeInput(activeDesc->mIoHandle);
4069 }
4070 }
4071}
4072
Paul Wang5d7cdb52022-11-22 09:45:06 +00004073status_t
4074AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4075 device_role_t role,
4076 const AudioDeviceTypeAddrVector &devices) {
4077 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4078 dumpAudioDeviceTypeAddrVector(devices).c_str());
4079
Eric Laurent78fedbf2023-03-09 14:40:44 +01004080 if (!areAllDevicesSupported(
4081 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004082 return BAD_VALUE;
4083 }
4084 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4085 if (status != NO_ERROR) {
4086 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4087 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4088 return status;
4089 }
4090
4091 checkForDeviceAndOutputChanges();
4092
4093 bool forceVolumeReeval = false;
4094 // TODO(b/263479999): 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);
4103
4104 return NO_ERROR;
4105}
4106
4107status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4108 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004109{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004110 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004111
Paul Wang5d7cdb52022-11-22 09:45:06 +00004112 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004113 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004114 ALOGW_IF(status != NAME_NOT_FOUND,
4115 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004116 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004117 return status;
4118 }
4119
4120 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004121
4122 bool forceVolumeReeval = false;
4123 // FIXME: workaround for truncated touch sounds
4124 // to be removed when the problem is handled by system UI
4125 uint32_t delayMs = 0;
4126 if (strategy == mCommunnicationStrategy) {
4127 forceVolumeReeval = true;
4128 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4129 updateInputRouting();
4130 }
4131 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004132
4133 return NO_ERROR;
4134}
4135
jiabin0a488932020-08-07 17:32:40 -07004136status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4137 device_role_t role,
4138 AudioDeviceTypeAddrVector &devices) {
4139 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004140}
4141
Jiabin Huang3b98d322020-09-03 17:54:16 +00004142status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4143 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4144 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4145 dumpAudioDeviceTypeAddrVector(devices).c_str());
4146
Mikhail Naganov55773032020-10-01 15:08:13 -07004147 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004148 return BAD_VALUE;
4149 }
4150 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4151 ALOGW_IF(status != NO_ERROR,
4152 "Engine could not set preferred devices %s for audio source %d role %d",
4153 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4154
4155 return status;
4156}
4157
4158status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4159 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4160 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4161 dumpAudioDeviceTypeAddrVector(devices).c_str());
4162
Mikhail Naganov55773032020-10-01 15:08:13 -07004163 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004164 return BAD_VALUE;
4165 }
4166 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4167 ALOGW_IF(status != NO_ERROR,
4168 "Engine could not add preferred devices %s for audio source %d role %d",
4169 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4170
Eric Laurent2517af32020-11-25 15:31:27 +01004171 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004172 return status;
4173}
4174
4175status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4176 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4177{
4178 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4179 dumpAudioDeviceTypeAddrVector(devices).c_str());
4180
Eric Laurent78fedbf2023-03-09 14:40:44 +01004181 if (!areAllDevicesSupported(
4182 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004183 return BAD_VALUE;
4184 }
4185
4186 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4187 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004188 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004189 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004190 if (status == NO_ERROR) {
4191 updateInputRouting();
4192 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004193 return status;
4194}
4195
4196status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4197 device_role_t role) {
4198 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4199
4200 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004201 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004202 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004203 if (status == NO_ERROR) {
4204 updateInputRouting();
4205 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004206 return status;
4207}
4208
4209status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4210 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4211 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4212}
4213
Oscar Azucena90e77632019-11-27 17:12:28 -08004214status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004215 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004216 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004217 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4218 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004219 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004220 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4221 if (status != NO_ERROR) {
4222 ALOGE("%s() could not set device affinity for userId %d",
4223 __FUNCTION__, userId);
4224 return status;
4225 }
4226
4227 // reevaluate outputs for all devices
4228 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004229 changeOutputDevicesMuteState(devices);
4230 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4231 true /* skipDelays */);
4232 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004233
4234 return NO_ERROR;
4235}
4236
4237status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004238 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004239 AudioDeviceTypeAddrVector devices;
4240 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004241 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4242 if (status != NO_ERROR) {
4243 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4244 __FUNCTION__, userId);
4245 return status;
4246 }
4247
4248 // reevaluate outputs for all devices
4249 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004250 changeOutputDevicesMuteState(devices);
4251 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4252 true /* skipDelays */);
4253 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004254
4255 return NO_ERROR;
4256}
4257
Andy Hungc29d82b2018-10-05 12:23:17 -07004258void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004259{
Andy Hungc29d82b2018-10-05 12:23:17 -07004260 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004261 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004262 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004263 std::string stateLiteral;
4264 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004265 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004266 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4267 "communications", "media", "record", "dock", "system",
4268 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4269 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4270 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004271 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4272 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4273 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4274 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4275 dst->append(" (MANUAL: ");
4276 dumpManualSurroundFormats(dst);
4277 dst->append(")");
4278 }
4279 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004280 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004281 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4282 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004283 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004284 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004285
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004286 dst->append("\n");
4287 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4288 dst->append("\n");
4289 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004290 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004291 mOutputs.dump(dst);
4292 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004293 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004294 mAudioPatches.dump(dst);
4295 mPolicyMixes.dump(dst);
4296 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004297
Kevin Rocardb99cc752019-03-21 20:52:24 -07004298 dst->appendFormat(" AllowedCapturePolicies:\n");
4299 for (auto& policy : mAllowedCapturePolicies) {
4300 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4301 }
4302
jiabina84c3d32022-12-02 18:59:55 +00004303 dst->appendFormat(" Preferred mixer audio configuration:\n");
4304 for (const auto it : mPreferredMixerAttrInfos) {
4305 dst->appendFormat(" - device port id: %d\n", it.first);
4306 for (const auto preferredMixerInfoIt : it.second) {
4307 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4308 preferredMixerInfoIt.second->dump(dst);
4309 }
4310 }
4311
François Gaffiec005e562018-11-06 15:04:49 +01004312 dst->appendFormat("\nPolicy Engine dump:\n");
4313 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004314}
4315
4316status_t AudioPolicyManager::dump(int fd)
4317{
4318 String8 result;
4319 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004320 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004321 return NO_ERROR;
4322}
4323
Kevin Rocardb99cc752019-03-21 20:52:24 -07004324status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4325{
4326 mAllowedCapturePolicies[uid] = capturePolicy;
4327 return NO_ERROR;
4328}
4329
Eric Laurente552edb2014-03-10 17:42:56 -07004330// This function checks for the parameters which can be offloaded.
4331// This can be enhanced depending on the capability of the DSP and policy
4332// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004333audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004334{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004335 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004336 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004337 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004338 offloadInfo.format,
4339 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4340 offloadInfo.has_video);
4341
jiabin2b9d5a12021-12-10 01:06:29 +00004342 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004343 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004344 }
4345
4346 // See if there is a profile to support this.
4347 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004348 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004349 offloadInfo.sample_rate,
4350 offloadInfo.format,
4351 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004352 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4353 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004354 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4355 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4356 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004357 if (profile == nullptr) {
4358 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4359 }
4360 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4361 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4362 }
4363 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004364}
4365
Michael Chana94fbb22018-04-24 14:31:19 +10004366bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4367 const audio_attributes_t& attributes) {
4368 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004369 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004370 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4371 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004372 config.sample_rate,
4373 config.format,
4374 config.channel_mask,
4375 output_flags,
4376 true /* directOnly */);
4377 ALOGV("%s() profile %sfound with name: %s, "
4378 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4379 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004380 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004381 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004382
4383 // also try the MSD module if compatible profile not found
4384 if (profile == nullptr) {
4385 profile = getMsdProfileForOutput(outputDevices,
4386 config.sample_rate,
4387 config.format,
4388 config.channel_mask,
4389 output_flags,
4390 true /* directOnly */);
4391 ALOGV("%s() MSD profile %sfound with name: %s, "
4392 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4393 __FUNCTION__, profile != 0 ? "" : "NOT ",
4394 (profile != 0 ? profile->getTagName().c_str() : "null"),
4395 config.sample_rate, config.format, config.channel_mask, output_flags);
4396 }
4397 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004398}
4399
jiabin2b9d5a12021-12-10 01:06:29 +00004400bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4401 bool durationIgnored) {
4402 if (mMasterMono) {
4403 return false; // no offloading if mono is set.
4404 }
4405
4406 // Check if offload has been disabled
4407 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4408 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4409 return false;
4410 }
4411
4412 // Check if stream type is music, then only allow offload as of now.
4413 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4414 {
4415 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4416 return false;
4417 }
4418
4419 //TODO: enable audio offloading with video when ready
4420 const bool allowOffloadWithVideo =
4421 property_get_bool("audio.offload.video", false /* default_value */);
4422 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4423 ALOGV("%s: has_video == true, returning false", __func__);
4424 return false;
4425 }
4426
4427 //If duration is less than minimum value defined in property, return false
4428 const int min_duration_secs = property_get_int32(
4429 "audio.offload.min.duration.secs", -1 /* default_value */);
4430 if (!durationIgnored) {
4431 if (min_duration_secs >= 0) {
4432 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4433 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4434 __func__, min_duration_secs);
4435 return false;
4436 }
4437 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4438 ALOGV("%s: Offload denied by duration < default min(=%u)",
4439 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4440 return false;
4441 }
4442 }
4443
4444 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4445 // creating an offloaded track and tearing it down immediately after start when audioflinger
4446 // detects there is an active non offloadable effect.
4447 // FIXME: We should check the audio session here but we do not have it in this context.
4448 // This may prevent offloading in rare situations where effects are left active by apps
4449 // in the background.
4450 if (mEffects.isNonOffloadableEffectEnabled()) {
4451 return false;
4452 }
4453
4454 return true;
4455}
4456
4457audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4458 const audio_config_t *config) {
4459 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4460 offloadInfo.format = config->format;
4461 offloadInfo.sample_rate = config->sample_rate;
4462 offloadInfo.channel_mask = config->channel_mask;
4463 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4464 offloadInfo.has_video = false;
4465 offloadInfo.is_streaming = false;
4466 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4467
4468 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4469 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4470 audio_flags_to_audio_output_flags(attr->flags, &flags);
4471 // only retain flags that will drive compressed offload or passthrough
4472 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4473 if (offloadPossible) {
4474 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4475 }
4476 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4477
Dorin Drimusfae3c642022-03-17 18:36:30 +01004478 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004479 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004480 DeviceVector outputDevices = engineOutputDevices;
4481 // the MSD module checks for different conditions and output devices
4482 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4483 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4484 continue;
4485 }
4486 outputDevices = getMsdAudioOutDevices();
4487 }
jiabin2b9d5a12021-12-10 01:06:29 +00004488 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004489 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004490 config->sample_rate, nullptr /*updatedSamplingRate*/,
4491 config->format, nullptr /*updatedFormat*/,
4492 config->channel_mask, nullptr /*updatedChannelMask*/,
4493 flags)) {
4494 continue;
4495 }
4496 // reject profiles not corresponding to a device currently available
4497 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4498 continue;
4499 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004500 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4501 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004502 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004503 != AUDIO_DIRECT_NOT_SUPPORTED) {
4504 // Already reports offload gapless supported. No need to report offload support.
4505 continue;
4506 }
4507 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4508 != AUDIO_OUTPUT_FLAG_NONE) {
4509 // If offload gapless is reported, no need to report offload support.
4510 directMode = (audio_direct_mode_t) ((directMode &
4511 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4512 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4513 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004514 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004515 }
4516 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004517 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004518 }
4519 }
4520 }
4521 return directMode;
4522}
4523
Dorin Drimusf2196d82022-01-03 12:11:18 +01004524status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4525 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004526 if (mEffects.isNonOffloadableEffectEnabled()) {
4527 return OK;
4528 }
jiabinf1c73972022-04-14 16:28:52 -07004529 DeviceVector devices;
4530 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004531 if (status != OK) {
4532 return status;
4533 }
4534 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4535 if (devices.empty()) {
4536 return OK; // no output devices for the attributes
4537 }
jiabinf1c73972022-04-14 16:28:52 -07004538 return getProfilesForDevices(devices, audioProfilesVector,
4539 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004540}
4541
jiabina84c3d32022-12-02 18:59:55 +00004542status_t AudioPolicyManager::getSupportedMixerAttributes(
4543 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4544 ALOGV("%s, portId=%d", __func__, portId);
4545 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4546 if (deviceDescriptor == nullptr) {
4547 ALOGE("%s the requested device is currently unavailable", __func__);
4548 return BAD_VALUE;
4549 }
jiabin96daffc2023-05-11 17:51:55 +00004550 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4551 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4552 deviceDescriptor->type());
4553 return BAD_VALUE;
4554 }
jiabina84c3d32022-12-02 18:59:55 +00004555 for (const auto& hwModule : mHwModules) {
4556 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4557 if (curProfile->supportsDevice(deviceDescriptor)) {
4558 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4559 }
4560 }
4561 }
4562 return NO_ERROR;
4563}
4564
4565status_t AudioPolicyManager::setPreferredMixerAttributes(
4566 const audio_attributes_t *attr,
4567 audio_port_handle_t portId,
4568 uid_t uid,
4569 const audio_mixer_attributes_t *mixerAttributes) {
4570 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4571 "mixerBehavior=%d}, uid=%d, portId=%u",
4572 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4573 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4574 mixerAttributes->mixer_behavior, uid, portId);
4575 if (attr->usage != AUDIO_USAGE_MEDIA) {
4576 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4577 return BAD_VALUE;
4578 }
4579 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4580 if (deviceDescriptor == nullptr) {
4581 ALOGE("%s the requested device is currently unavailable", __func__);
4582 return BAD_VALUE;
4583 }
4584 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4585 ALOGE("%s(%d), type=%d, is not a usb output device",
4586 __func__, portId, deviceDescriptor->type());
4587 return BAD_VALUE;
4588 }
4589
4590 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4591 audio_flags_to_audio_output_flags(attr->flags, &flags);
4592 flags = (audio_output_flags_t) (flags |
4593 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4594 sp<IOProfile> profile = nullptr;
4595 DeviceVector devices(deviceDescriptor);
4596 for (const auto& hwModule : mHwModules) {
4597 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4598 if (curProfile->hasDynamicAudioProfile()
4599 && curProfile->isCompatibleProfile(devices,
4600 mixerAttributes->config.sample_rate,
4601 nullptr /*updatedSamplingRate*/,
4602 mixerAttributes->config.format,
4603 nullptr /*updatedFormat*/,
4604 mixerAttributes->config.channel_mask,
4605 nullptr /*updatedChannelMask*/,
4606 flags,
4607 false /*exactMatchRequiredForInputFlags*/)) {
4608 profile = curProfile;
4609 break;
4610 }
4611 }
4612 }
4613 if (profile == nullptr) {
4614 ALOGE("%s, there is no compatible profile found", __func__);
4615 return BAD_VALUE;
4616 }
4617
4618 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4619 sp<PreferredMixerAttributesInfo>::make(
4620 uid, portId, profile, flags, *mixerAttributes);
4621 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4622 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4623
4624 // If 1) there is any client from the preferred mixer configuration owner that is currently
4625 // active and matches the strategy and 2) current output is on the preferred device and the
4626 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4627 // configuration.
4628 std::vector<audio_io_handle_t> outputsToReopen;
4629 for (size_t i = 0; i < mOutputs.size(); i++) {
4630 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004631 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4632 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4633 output->mUsePreferredMixerAttributes = true;
4634 } else {
4635 for (const auto &client: output->getActiveClients()) {
4636 if (client->uid() == uid && client->strategy() == strategy) {
4637 client->setIsInvalid();
4638 outputsToReopen.push_back(output->mIoHandle);
4639 }
jiabina84c3d32022-12-02 18:59:55 +00004640 }
4641 }
4642 }
4643 }
4644 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4645 config.sample_rate = mixerAttributes->config.sample_rate;
4646 config.channel_mask = mixerAttributes->config.channel_mask;
4647 config.format = mixerAttributes->config.format;
4648 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004649 sp<SwAudioOutputDescriptor> desc =
4650 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4651 if (desc == nullptr) {
4652 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4653 continue;
4654 }
4655 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004656 }
4657
4658 return NO_ERROR;
4659}
4660
4661sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004662 audio_port_handle_t devicePortId,
4663 product_strategy_t strategy,
4664 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004665 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4666 if (it == mPreferredMixerAttrInfos.end()) {
4667 return nullptr;
4668 }
jiabind9a58d32023-06-01 17:57:30 +00004669 if (activeBitPerfectPreferred) {
4670 for (auto [strategy, info] : it->second) {
4671 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4672 && info->getActiveClientCount() != 0) {
4673 return info;
4674 }
4675 }
jiabina84c3d32022-12-02 18:59:55 +00004676 }
jiabind9a58d32023-06-01 17:57:30 +00004677 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4678 return strategyMatchedMixerAttrInfoIt == it->second.end()
4679 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004680}
4681
4682status_t AudioPolicyManager::getPreferredMixerAttributes(
4683 const audio_attributes_t *attr,
4684 audio_port_handle_t portId,
4685 audio_mixer_attributes_t* mixerAttributes) {
4686 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4687 portId, mEngine->getProductStrategyForAttributes(*attr));
4688 if (info == nullptr) {
4689 return NAME_NOT_FOUND;
4690 }
4691 *mixerAttributes = info->getMixerAttributes();
4692 return NO_ERROR;
4693}
4694
4695status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4696 audio_port_handle_t portId,
4697 uid_t uid) {
4698 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4699 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4700 if (preferredMixerAttrInfo == nullptr) {
4701 return NAME_NOT_FOUND;
4702 }
4703 if (preferredMixerAttrInfo->getUid() != uid) {
4704 ALOGE("%s, requested uid=%d, owned uid=%d",
4705 __func__, uid, preferredMixerAttrInfo->getUid());
4706 return PERMISSION_DENIED;
4707 }
4708 mPreferredMixerAttrInfos[portId].erase(strategy);
4709 if (mPreferredMixerAttrInfos[portId].empty()) {
4710 mPreferredMixerAttrInfos.erase(portId);
4711 }
4712
4713 // Reconfig existing output
4714 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4715 for (size_t i = 0; i < mOutputs.size(); i++) {
4716 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4717 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4718 }
4719 }
4720 for (const auto output : potentialOutputsToReopen) {
4721 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4722 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4723 preferredMixerAttrInfo->getFlags())) {
4724 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4725 }
4726 }
4727 return NO_ERROR;
4728}
4729
Eric Laurent6a94d692014-05-20 11:18:06 -07004730status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4731 audio_port_type_t type,
4732 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004733 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004734 unsigned int *generation)
4735{
jiabin19cdba52020-11-24 11:28:58 -08004736 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4737 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004738 return BAD_VALUE;
4739 }
4740 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004741 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004742 *num_ports = 0;
4743 }
4744
4745 size_t portsWritten = 0;
4746 size_t portsMax = *num_ports;
4747 *num_ports = 0;
4748 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004749 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4750 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004751 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004752 for (const auto& dev : mAvailableOutputDevices) {
4753 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004754 continue;
4755 }
4756 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004757 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004758 }
4759 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004760 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004761 }
4762 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004763 for (const auto& dev : mAvailableInputDevices) {
4764 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004765 continue;
4766 }
4767 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004768 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004769 }
4770 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004771 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004772 }
4773 }
4774 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4775 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4776 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4777 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4778 }
4779 *num_ports += mInputs.size();
4780 }
4781 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004782 size_t numOutputs = 0;
4783 for (size_t i = 0; i < mOutputs.size(); i++) {
4784 if (!mOutputs[i]->isDuplicated()) {
4785 numOutputs++;
4786 if (portsWritten < portsMax) {
4787 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4788 }
4789 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004790 }
Eric Laurent84c70242014-06-23 08:46:27 -07004791 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004792 }
4793 }
jiabina84c3d32022-12-02 18:59:55 +00004794
Eric Laurent6a94d692014-05-20 11:18:06 -07004795 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004796 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 return NO_ERROR;
4798}
4799
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004800status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4801 std::vector<media::AudioPortFw>* _aidl_return) {
4802 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4803 audio_port_v7 port;
4804 dev->toAudioPort(&port);
4805 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4806 _aidl_return->push_back(std::move(aidlPort));
4807 return OK;
4808 };
4809
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004810 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004811 for (const auto& dev : module->getDeclaredDevices()) {
4812 if (role == media::AudioPortRole::NONE ||
4813 ((role == media::AudioPortRole::SOURCE)
4814 == audio_is_input_device(dev->type()))) {
4815 RETURN_STATUS_IF_ERROR(pushPort(dev));
4816 }
4817 }
4818 }
4819 return OK;
4820}
4821
jiabin19cdba52020-11-24 11:28:58 -08004822status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004823{
Eric Laurent99fcae42018-05-17 16:59:18 -07004824 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4825 return BAD_VALUE;
4826 }
4827 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4828 if (dev != 0) {
4829 dev->toAudioPort(port);
4830 return NO_ERROR;
4831 }
4832 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4833 if (dev != 0) {
4834 dev->toAudioPort(port);
4835 return NO_ERROR;
4836 }
4837 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4838 if (out != 0) {
4839 out->toAudioPort(port);
4840 return NO_ERROR;
4841 }
4842 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4843 if (in != 0) {
4844 in->toAudioPort(port);
4845 return NO_ERROR;
4846 }
4847 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004848}
4849
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004850status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4851 audio_patch_handle_t *handle,
4852 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004853{
François Gaffieafd4cea2019-11-18 15:50:22 +01004854 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004855 if (handle == NULL || patch == NULL) {
4856 return BAD_VALUE;
4857 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004858 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004859 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004860 return BAD_VALUE;
4861 }
4862 // only one source per audio patch supported for now
4863 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004864 return INVALID_OPERATION;
4865 }
Eric Laurent874c42872014-08-08 15:13:39 -07004866 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004867 return INVALID_OPERATION;
4868 }
Eric Laurent874c42872014-08-08 15:13:39 -07004869 for (size_t i = 0; i < patch->num_sinks; i++) {
4870 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4871 return INVALID_OPERATION;
4872 }
4873 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004874
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004875 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4876 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4877 if (srcDevice == nullptr || sinkDevice == nullptr) {
4878 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4879 return BAD_VALUE;
4880 }
4881 ALOGV("%s between source %s and sink %s", __func__,
4882 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4883 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4884 // Default attributes, default volume priority, not to infer with non raw audio patches.
4885 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4886 const struct audio_port_config *source = &patch->sources[0];
4887 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004888 new SourceClientDescriptor(
4889 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4890 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4891 true);
4892 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004893
4894 status_t status =
4895 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4896
4897 if (status != NO_ERROR) {
4898 return INVALID_OPERATION;
4899 }
4900 mAudioSources.add(portId, sourceDesc);
4901 return NO_ERROR;
4902}
4903
4904status_t AudioPolicyManager::connectAudioSourceToSink(
4905 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4906 const struct audio_patch *patch,
4907 audio_patch_handle_t &handle,
4908 uid_t uid, uint32_t delayMs)
4909{
4910 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4911 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4912 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4913 return INVALID_OPERATION;
4914 }
4915 sourceDesc->connect(handle, sinkDevice);
4916 if (isMsdPatch(handle)) {
4917 return NO_ERROR;
4918 }
4919 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4920 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4921 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4922 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4923 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4924 goto FailurePatchAdded;
4925 }
4926 status = swOutput->start();
4927 if (status != NO_ERROR) {
4928 goto FailureSourceAdded;
4929 }
4930 swOutput->addClient(sourceDesc);
4931 status = startSource(swOutput, sourceDesc, &delayMs);
4932 if (status != NO_ERROR) {
4933 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4934 goto FailureSourceActive;
4935 }
4936 if (delayMs != 0) {
4937 usleep(delayMs * 1000);
4938 }
4939 return NO_ERROR;
4940
4941FailureSourceActive:
4942 swOutput->stop();
4943 releaseOutput(sourceDesc->portId());
4944FailureSourceAdded:
4945 sourceDesc->setSwOutput(nullptr);
4946FailurePatchAdded:
4947 releaseAudioPatchInternal(handle);
4948 return INVALID_OPERATION;
4949}
4950
4951status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4952 audio_patch_handle_t *handle,
4953 uid_t uid, uint32_t delayMs,
4954 const sp<SourceClientDescriptor>& sourceDesc)
4955{
4956 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004957 sp<AudioPatch> patchDesc;
4958 ssize_t index = mAudioPatches.indexOfKey(*handle);
4959
François Gaffieafd4cea2019-11-18 15:50:22 +01004960 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4961 patch->sources[0].role,
4962 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004963#if LOG_NDEBUG == 0
4964 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004965 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4966 patch->sinks[i].role,
4967 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004968 }
4969#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004970
4971 if (index >= 0) {
4972 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004973 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4974 __func__, mUidCached, patchDesc->getUid(), uid);
4975 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004976 return INVALID_OPERATION;
4977 }
4978 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004979 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004980 }
4981
4982 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004983 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004984 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004985 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 return BAD_VALUE;
4987 }
Eric Laurent84c70242014-06-23 08:46:27 -07004988 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4989 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004990 if (patchDesc != 0) {
4991 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004992 ALOGV("%s source id differs for patch current id %d new id %d",
4993 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004994 return BAD_VALUE;
4995 }
4996 }
Eric Laurent874c42872014-08-08 15:13:39 -07004997 DeviceVector devices;
4998 for (size_t i = 0; i < patch->num_sinks; i++) {
4999 // Only support mix to devices connection
5000 // TODO add support for mix to mix connection
5001 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005002 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005003 return INVALID_OPERATION;
5004 }
5005 sp<DeviceDescriptor> devDesc =
5006 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5007 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005008 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005009 return BAD_VALUE;
5010 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005011
François Gaffie11d30102018-11-02 16:09:09 +01005012 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07005013 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01005014 NULL, // updatedSamplingRate
5015 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005016 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01005017 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005018 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01005019 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005020 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005021 return INVALID_OPERATION;
5022 }
5023 devices.add(devDesc);
5024 }
5025 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005026 return INVALID_OPERATION;
5027 }
Eric Laurent874c42872014-08-08 15:13:39 -07005028
Eric Laurent6a94d692014-05-20 11:18:06 -07005029 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005030 ALOGV("%s setting device %s on output %d",
5031 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305032 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005033 index = mAudioPatches.indexOfKey(*handle);
5034 if (index >= 0) {
5035 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005036 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005037 }
5038 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005039 patchDesc->setUid(uid);
5040 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005041 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005042 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005043 return INVALID_OPERATION;
5044 }
5045 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5046 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5047 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005048 // only one sink supported when connecting an input device to a mix
5049 if (patch->num_sinks > 1) {
5050 return INVALID_OPERATION;
5051 }
François Gaffie53615e22015-03-19 09:24:12 +01005052 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005053 if (inputDesc == NULL) {
5054 return BAD_VALUE;
5055 }
5056 if (patchDesc != 0) {
5057 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5058 return BAD_VALUE;
5059 }
5060 }
François Gaffie11d30102018-11-02 16:09:09 +01005061 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005062 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005063 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005064 return BAD_VALUE;
5065 }
5066
François Gaffie11d30102018-11-02 16:09:09 +01005067 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005068 patch->sinks[0].sample_rate,
5069 NULL, /*updatedSampleRate*/
5070 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005071 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005072 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005073 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005074 // FIXME for the parameter type,
5075 // and the NONE
5076 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005077 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005078 return INVALID_OPERATION;
5079 }
5080 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005081 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005082 device->toString().c_str(), inputDesc->mIoHandle);
5083 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005084 index = mAudioPatches.indexOfKey(*handle);
5085 if (index >= 0) {
5086 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005087 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005088 }
5089 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005090 patchDesc->setUid(uid);
5091 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005092 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005093 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005094 return INVALID_OPERATION;
5095 }
5096 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5097 // device to device connection
5098 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005099 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005100 return BAD_VALUE;
5101 }
5102 }
François Gaffie11d30102018-11-02 16:09:09 +01005103 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005104 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005105 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005106 return BAD_VALUE;
5107 }
Eric Laurent874c42872014-08-08 15:13:39 -07005108
Eric Laurent6a94d692014-05-20 11:18:06 -07005109 //update source and sink with our own data as the data passed in the patch may
5110 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005111 PatchBuilder patchBuilder;
5112 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005113
5114 // if first sink is to MSD, establish single MSD patch
5115 if (getMsdAudioOutDevices().contains(
5116 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5117 ALOGV("%s patching to MSD", __FUNCTION__);
5118 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5119 goto installPatch;
5120 }
5121
François Gaffieafd4cea2019-11-18 15:50:22 +01005122 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5123 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005124
Eric Laurent874c42872014-08-08 15:13:39 -07005125 for (size_t i = 0; i < patch->num_sinks; i++) {
5126 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005127 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005128 return INVALID_OPERATION;
5129 }
François Gaffie11d30102018-11-02 16:09:09 +01005130 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005131 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005132 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005133 return BAD_VALUE;
5134 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005135 audio_port_config sinkPortConfig = {};
5136 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5137 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005138
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005139 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5140 // volume management purpose (tracking activity)
5141 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5142 // in config XML to reach the sink so that is can be declared as available.
5143 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005144 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005145 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005146 // take care of dynamic routing for SwOutput selection,
5147 audio_attributes_t attributes = sourceDesc->attributes();
5148 audio_stream_type_t stream = sourceDesc->stream();
5149 audio_attributes_t resultAttr;
5150 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5151 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005152 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5153 config.channel_mask =
5154 (audio_channel_mask_get_representation(sourceMask)
5155 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5156 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005157 config.format = sourceDesc->config().format;
5158 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5159 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5160 bool isRequestedDeviceForExclusiveUse = false;
5161 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005162 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005163 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005164 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5165 &stream, sourceDesc->uid(), &config, &flags,
5166 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005167 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005168 if (output == AUDIO_IO_HANDLE_NONE) {
5169 ALOGV("%s no output for device %s",
5170 __FUNCTION__, sinkDevice->toString().c_str());
5171 return INVALID_OPERATION;
5172 }
5173 outputDesc = mOutputs.valueFor(output);
5174 if (outputDesc->isDuplicated()) {
5175 ALOGE("%s output is duplicated", __func__);
5176 return INVALID_OPERATION;
5177 }
François Gaffie7e39df22022-04-26 12:48:49 +02005178 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5179 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005180 } else {
5181 // Same for "raw patches" aka created from createAudioPatch API
5182 SortedVector<audio_io_handle_t> outputs =
5183 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5184 // if the sink device is reachable via an opened output stream, request to
5185 // go via this output stream by adding a second source to the patch
5186 // description
5187 output = selectOutput(outputs);
5188 if (output == AUDIO_IO_HANDLE_NONE) {
5189 ALOGE("%s no output available for internal patch sink", __func__);
5190 return INVALID_OPERATION;
5191 }
5192 outputDesc = mOutputs.valueFor(output);
5193 if (outputDesc->isDuplicated()) {
5194 ALOGV("%s output for device %s is duplicated",
5195 __func__, sinkDevice->toString().c_str());
5196 return INVALID_OPERATION;
5197 }
François Gaffie7e39df22022-04-26 12:48:49 +02005198 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005199 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005200 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005201 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005202 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005203 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005204 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5205 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005206 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5207 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005208 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005209 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005210 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005211 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005212 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005213 return INVALID_OPERATION;
5214 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005215 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005216 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005217 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005218 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005219 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005220 srcMixPortConfig.ext.mix.usecase.stream =
5221 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005222 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5223 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005224 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005225 }
Eric Laurent83b88082014-06-20 18:31:16 -07005226 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005227 }
5228 // TODO: check from routing capabilities in config file and other conflicting patches
5229
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005230installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005231 status_t status = installPatch(
5232 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005233 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005234 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005235 return INVALID_OPERATION;
5236 }
5237 } else {
5238 return BAD_VALUE;
5239 }
5240 } else {
5241 return BAD_VALUE;
5242 }
5243 return NO_ERROR;
5244}
5245
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005246status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005247{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005248 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005249 ssize_t index = mAudioPatches.indexOfKey(handle);
5250
5251 if (index < 0) {
5252 return BAD_VALUE;
5253 }
5254 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005255 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5256 __func__, mUidCached, patchDesc->getUid(), uid);
5257 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005258 return INVALID_OPERATION;
5259 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005260 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5261 for (size_t i = 0; i < mAudioSources.size(); i++) {
5262 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5263 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5264 portId = sourceDesc->portId();
5265 break;
5266 }
5267 }
5268 return portId != AUDIO_PORT_HANDLE_NONE ?
5269 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005270}
Eric Laurent6a94d692014-05-20 11:18:06 -07005271
François Gaffieafd4cea2019-11-18 15:50:22 +01005272status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005273 uint32_t delayMs,
5274 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005275{
5276 ALOGV("%s patch %d", __func__, handle);
5277 if (mAudioPatches.indexOfKey(handle) < 0) {
5278 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5279 return BAD_VALUE;
5280 }
5281 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005282 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005283 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005284 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005285 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005286 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005287 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 return BAD_VALUE;
5289 }
5290
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305291 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005292 getNewOutputDevices(outputDesc, true /*fromCache*/),
5293 true,
5294 0,
5295 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005296 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5297 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005298 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005299 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005300 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005301 return BAD_VALUE;
5302 }
5303 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005304 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005305 true,
5306 NULL);
5307 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005308 status_t status =
5309 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5310 ALOGV("%s patch panel returned %d patchHandle %d",
5311 __func__, status, patchDesc->getAfHandle());
5312 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005313 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005314 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005315 // SW or HW Bridge
5316 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5317 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005318 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005319 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5320 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5321 outputDesc = sourceDesc->swOutput().promote();
5322 }
5323 if (outputDesc == nullptr) {
5324 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5325 // releaseOutput has already called closeOutput in case of direct output
5326 return NO_ERROR;
5327 }
François Gaffie7e39df22022-04-26 12:48:49 +02005328 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005329 // While using a HwBridge, force reconsidering device only if not reusing an existing
5330 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005331 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005332 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5333 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5334 // Reconsider device only for cases:
5335 // 1 / Active Output
5336 // 2 / Inactive Output previously hosting HwBridge
5337 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5338 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5339 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305340 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005341 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5342 outputDesc->devices(),
5343 force,
5344 0,
5345 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005346 } else {
5347 return BAD_VALUE;
5348 }
5349 } else {
5350 return BAD_VALUE;
5351 }
5352 return NO_ERROR;
5353}
5354
5355status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5356 struct audio_patch *patches,
5357 unsigned int *generation)
5358{
François Gaffie53615e22015-03-19 09:24:12 +01005359 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005360 return BAD_VALUE;
5361 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005362 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005363 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005364}
5365
Eric Laurente1715a42014-05-20 11:30:42 -07005366status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005367{
Eric Laurente1715a42014-05-20 11:30:42 -07005368 ALOGV("setAudioPortConfig()");
5369
5370 if (config == NULL) {
5371 return BAD_VALUE;
5372 }
5373 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5374 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005375 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5376 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005377 }
5378
Eric Laurenta121f902014-06-03 13:32:54 -07005379 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005380 if (config->type == AUDIO_PORT_TYPE_MIX) {
5381 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005382 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005383 if (outputDesc == NULL) {
5384 return BAD_VALUE;
5385 }
Eric Laurent84c70242014-06-23 08:46:27 -07005386 ALOG_ASSERT(!outputDesc->isDuplicated(),
5387 "setAudioPortConfig() called on duplicated output %d",
5388 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005389 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005390 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005391 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005392 if (inputDesc == NULL) {
5393 return BAD_VALUE;
5394 }
Eric Laurenta121f902014-06-03 13:32:54 -07005395 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005396 } else {
5397 return BAD_VALUE;
5398 }
5399 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5400 sp<DeviceDescriptor> deviceDesc;
5401 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5402 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5403 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5404 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5405 } else {
5406 return BAD_VALUE;
5407 }
5408 if (deviceDesc == NULL) {
5409 return BAD_VALUE;
5410 }
Eric Laurenta121f902014-06-03 13:32:54 -07005411 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005412 } else {
5413 return BAD_VALUE;
5414 }
5415
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005416 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005417 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5418 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005419 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005420 audioPortConfig->toAudioPortConfig(&newConfig, config);
5421 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005422 }
Eric Laurenta121f902014-06-03 13:32:54 -07005423 if (status != NO_ERROR) {
5424 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005425 }
Eric Laurente1715a42014-05-20 11:30:42 -07005426
5427 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005428}
5429
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005430void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5431{
Eric Laurentd60560a2015-04-10 11:31:20 -07005432 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005433 clearAudioPatches(uid);
5434 clearSessionRoutes(uid);
5435}
5436
Eric Laurent6a94d692014-05-20 11:18:06 -07005437void AudioPolicyManager::clearAudioPatches(uid_t uid)
5438{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005439 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005440 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005441 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005442 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005443 }
5444 }
5445}
5446
François Gaffiec005e562018-11-06 15:04:49 +01005447void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005448{
François Gaffiec005e562018-11-06 15:04:49 +01005449 // Take the first attributes following the product strategy as it is used to retrieve the routed
5450 // device. All attributes wihin a strategy follows the same "routing strategy"
5451 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5452 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005453 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005454 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005455 for (size_t j = 0; j < mOutputs.size(); j++) {
5456 if (mOutputs.keyAt(j) == ouptutToSkip) {
5457 continue;
5458 }
5459 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005460 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005461 continue;
5462 }
5463 // If the default device for this strategy is on another output mix,
5464 // invalidate all tracks in this strategy to force re connection.
5465 // Otherwise select new device on the output mix.
5466 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005467 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005468 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005469 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5470 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5471 // If the device is using preferred mixer attributes, the output need to reopen
5472 // with default configuration when the new selected devices are different from
5473 // current routing devices.
5474 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5475 continue;
5476 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305477 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005478 }
5479 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005480 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005481}
5482
5483void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5484{
5485 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005486 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005487 for (size_t i = 0; i < mOutputs.size(); i++) {
5488 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005489 for (const auto& client : outputDesc->getClientIterable()) {
5490 if (client->hasPreferredDevice() && client->uid() == uid) {
5491 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005492 auto clientStrategy = client->strategy();
5493 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5494 end(affectedStrategies)) {
5495 continue;
5496 }
5497 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005498 }
5499 }
5500 }
5501 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005502 for (const auto& strategy : affectedStrategies) {
5503 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005504 }
5505
5506 // remove input routes associated with this uid
5507 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005508 for (size_t i = 0; i < mInputs.size(); i++) {
5509 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005510 for (const auto& client : inputDesc->getClientIterable()) {
5511 if (client->hasPreferredDevice() && client->uid() == uid) {
5512 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5513 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005514 }
5515 }
5516 }
5517 // reroute inputs if necessary
5518 SortedVector<audio_io_handle_t> inputsToClose;
5519 for (size_t i = 0; i < mInputs.size(); i++) {
5520 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005521 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005522 inputsToClose.add(inputDesc->mIoHandle);
5523 }
5524 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005525 for (const auto& input : inputsToClose) {
5526 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005527 }
5528}
5529
Eric Laurentd60560a2015-04-10 11:31:20 -07005530void AudioPolicyManager::clearAudioSources(uid_t uid)
5531{
5532 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005533 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5534 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005535 stopAudioSource(mAudioSources.keyAt(i));
5536 }
5537 }
5538}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005539
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005540status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5541 audio_io_handle_t *ioHandle,
5542 audio_devices_t *device)
5543{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005544 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5545 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005546 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005547 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5548 if (deviceDesc == nullptr) {
5549 return INVALID_OPERATION;
5550 }
5551 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005552
François Gaffiedf372692015-03-19 10:43:27 +01005553 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005554}
5555
Eric Laurentd60560a2015-04-10 11:31:20 -07005556status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005557 const audio_attributes_t *attributes,
5558 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005559 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005560{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005561 ALOGV("%s", __FUNCTION__);
5562 *portId = AUDIO_PORT_HANDLE_NONE;
5563
5564 if (source == NULL || attributes == NULL || portId == NULL) {
5565 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5566 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005567 return BAD_VALUE;
5568 }
5569
Eric Laurentd60560a2015-04-10 11:31:20 -07005570 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5571 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005572 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5573 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005574 return INVALID_OPERATION;
5575 }
5576
François Gaffie11d30102018-11-02 16:09:09 +01005577 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005578 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005579 String8(source->ext.device.address),
5580 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005581 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005582 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005583 return BAD_VALUE;
5584 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005585
jiabin4ef93452019-09-10 14:29:54 -07005586 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005587
François Gaffieaaac0fd2018-11-22 17:56:39 +01005588 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005589 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005590 mEngine->getStreamTypeForAttributes(*attributes),
5591 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005592 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005593
5594 status_t status = connectAudioSource(sourceDesc);
5595 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005596 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005597 }
5598 return status;
5599}
5600
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005601status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005602{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005603 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005604
5605 // make sure we only have one patch per source.
5606 disconnectAudioSource(sourceDesc);
5607
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005608 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005609 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5610 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5611 sourceDesc->srcDevice()->type(),
5612 String8(sourceDesc->srcDevice()->address().c_str()),
5613 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005614 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005615 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005616 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005617 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005618 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5619 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5620 return INVALID_OPERATION;
5621 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005622 PatchBuilder patchBuilder;
5623 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5624 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005625
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005626 return connectAudioSourceToSink(
5627 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005628}
5629
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005630status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005631{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005632 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5633 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005634 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005635 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005636 return BAD_VALUE;
5637 }
5638 status_t status = disconnectAudioSource(sourceDesc);
5639
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005640 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005641 return status;
5642}
5643
Andy Hung2ddee192015-12-18 17:34:44 -08005644status_t AudioPolicyManager::setMasterMono(bool mono)
5645{
5646 if (mMasterMono == mono) {
5647 return NO_ERROR;
5648 }
5649 mMasterMono = mono;
5650 // if enabling mono we close all offloaded devices, which will invalidate the
5651 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5652 // for recreating the new AudioTrack as non-offloaded PCM.
5653 //
5654 // If disabling mono, we leave all tracks as is: we don't know which clients
5655 // and tracks are able to be recreated as offloaded. The next "song" should
5656 // play back offloaded.
5657 if (mMasterMono) {
5658 Vector<audio_io_handle_t> offloaded;
5659 for (size_t i = 0; i < mOutputs.size(); ++i) {
5660 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5661 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5662 offloaded.push(desc->mIoHandle);
5663 }
5664 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005665 for (const auto& handle : offloaded) {
5666 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005667 }
5668 }
5669 // update master mono for all remaining outputs
5670 for (size_t i = 0; i < mOutputs.size(); ++i) {
5671 updateMono(mOutputs.keyAt(i));
5672 }
5673 return NO_ERROR;
5674}
5675
5676status_t AudioPolicyManager::getMasterMono(bool *mono)
5677{
5678 *mono = mMasterMono;
5679 return NO_ERROR;
5680}
5681
Eric Laurentac9cef52017-06-09 15:46:26 -07005682float AudioPolicyManager::getStreamVolumeDB(
5683 audio_stream_type_t stream, int index, audio_devices_t device)
5684{
jiabin9a3361e2019-10-01 09:38:30 -07005685 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005686}
5687
jiabin81772902018-04-02 17:52:27 -07005688status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5689 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005690 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005691{
Kriti Dang6537def2021-03-02 13:46:59 +01005692 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5693 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005694 return BAD_VALUE;
5695 }
Kriti Dang6537def2021-03-02 13:46:59 +01005696 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5697 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005698
5699 size_t formatsWritten = 0;
5700 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005701
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005702 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005703 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5704 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005705 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005706 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005707 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005708 bool formatEnabled = true;
5709 switch (forceUse) {
5710 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005711 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005712 break;
5713 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5714 formatEnabled = false;
5715 break;
5716 default: // AUTO or ALWAYS => true
5717 break;
jiabin81772902018-04-02 17:52:27 -07005718 }
5719 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5720 }
jiabin81772902018-04-02 17:52:27 -07005721 }
5722 return NO_ERROR;
5723}
5724
Kriti Dang6537def2021-03-02 13:46:59 +01005725status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5726 audio_format_t *surroundFormats) {
5727 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5728 return BAD_VALUE;
5729 }
5730 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5731 __func__, *numSurroundFormats, surroundFormats);
5732
5733 size_t formatsWritten = 0;
5734 size_t formatsMax = *numSurroundFormats;
5735 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5736
5737 // Return formats from all device profiles that have already been resolved by
5738 // checkOutputsForDevice().
5739 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5740 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5741 audio_devices_t deviceType = device->type();
5742 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5743 // returns formats reported by HDMI devices.
5744 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5745 continue;
5746 }
5747 // Formats reported by sink devices
5748 std::unordered_set<audio_format_t> formatset;
5749 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5750 formatset.insert(it->second.begin(), it->second.end());
5751 }
5752
5753 // Formats hard-coded in the in policy configuration file (if any).
5754 FormatVector encodedFormats = device->encodedFormats();
5755 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5756 // Filter the formats which are supported by the vendor hardware.
5757 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005758 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005759 formats.insert(*it);
5760 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005761 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005762 if (pair.second.count(*it) != 0) {
5763 formats.insert(pair.first);
5764 break;
5765 }
5766 }
5767 }
5768 }
5769 }
5770 *numSurroundFormats = formats.size();
5771 for (const auto& format: formats) {
5772 if (formatsWritten < formatsMax) {
5773 surroundFormats[formatsWritten++] = format;
5774 }
5775 }
5776 return NO_ERROR;
5777}
5778
jiabin81772902018-04-02 17:52:27 -07005779status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5780{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005781 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005782 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5783 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005784 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005785 return BAD_VALUE;
5786 }
5787
Mikhail Naganov100f0122018-11-29 11:22:16 -08005788 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5789 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005790 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005791 return INVALID_OPERATION;
5792 }
5793
Mikhail Naganov100f0122018-11-29 11:22:16 -08005794 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005795 return NO_ERROR;
5796 }
5797
Mikhail Naganov100f0122018-11-29 11:22:16 -08005798 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005799 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005800 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005801 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005802 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005803 }
5804 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005805 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005806 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005807 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005808 }
5809 }
5810
5811 sp<SwAudioOutputDescriptor> outputDesc;
5812 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005813 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5814 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005815 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5816 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005817 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005818 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005819 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5820 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5821 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005822 name.c_str(),
5823 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005824 if (status != NO_ERROR) {
5825 continue;
5826 }
5827 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5828 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5829 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005830 name.c_str(),
5831 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005832 profileUpdated |= (status == NO_ERROR);
5833 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005834 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005835 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005836 AUDIO_DEVICE_IN_HDMI);
5837 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5838 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005839 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005840 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005841 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5842 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5843 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005844 name.c_str(),
5845 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005846 if (status != NO_ERROR) {
5847 continue;
5848 }
5849 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5850 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5851 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005852 name.c_str(),
5853 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005854 profileUpdated |= (status == NO_ERROR);
5855 }
5856
jiabin81772902018-04-02 17:52:27 -07005857 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005858 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005859 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005860 }
5861
5862 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5863}
5864
Eric Laurent5ada82e2019-08-29 17:53:54 -07005865void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005866{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005867 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005868 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005869 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005870 }
5871}
5872
jiabin6012f912018-11-02 17:06:30 -07005873bool AudioPolicyManager::isHapticPlaybackSupported()
5874{
5875 for (const auto& hwModule : mHwModules) {
5876 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5877 for (const auto &outProfile : outputProfiles) {
5878 struct audio_port audioPort;
5879 outProfile->toAudioPort(&audioPort);
5880 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5881 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5882 return true;
5883 }
5884 }
5885 }
5886 }
5887 return false;
5888}
5889
Carter Hsu325a8eb2022-01-19 19:56:51 +08005890bool AudioPolicyManager::isUltrasoundSupported()
5891{
5892 bool hasUltrasoundOutput = false;
5893 bool hasUltrasoundInput = false;
5894 for (const auto& hwModule : mHwModules) {
5895 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5896 if (!hasUltrasoundOutput) {
5897 for (const auto &outProfile : outputProfiles) {
5898 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5899 hasUltrasoundOutput = true;
5900 break;
5901 }
5902 }
5903 }
5904
5905 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5906 if (!hasUltrasoundInput) {
5907 for (const auto &inputProfile : inputProfiles) {
5908 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5909 hasUltrasoundInput = true;
5910 break;
5911 }
5912 }
5913 }
5914
5915 if (hasUltrasoundOutput && hasUltrasoundInput)
5916 return true;
5917 }
5918 return false;
5919}
5920
Atneya Nair698f5ef2022-12-15 16:15:09 -08005921bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5922{
5923 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5924 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5925 for (const auto& hwModule : mHwModules) {
5926 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5927 for (const auto &inputProfile : inputProfiles) {
5928 if ((inputProfile->getFlags() & mask) == mask) {
5929 return true;
5930 }
5931 }
5932 }
5933 return false;
5934}
5935
Eric Laurent8340e672019-11-06 11:01:08 -08005936bool AudioPolicyManager::isCallScreenModeSupported()
5937{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005938 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005939}
5940
5941
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005942status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005943{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005944 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005945 if (!sourceDesc->isConnected()) {
5946 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5947 return NO_ERROR;
5948 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005949 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5950 if (swOutput != 0) {
5951 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005952 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005953 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005954 }
jiabinbce0c1d2020-10-05 11:20:18 -07005955 if (releaseOutput(sourceDesc->portId())) {
5956 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5957 // no need to release audio patch here but just return NO_ERROR.
5958 return NO_ERROR;
5959 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005960 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005961 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005962 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005963 // close Hwoutput and remove from mHwOutputs
5964 } else {
5965 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5966 }
5967 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005968 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005969 sourceDesc->disconnect();
5970 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005971}
5972
François Gaffiec005e562018-11-06 15:04:49 +01005973sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5974 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005975{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005976 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005977 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005978 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005979 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005980 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5981 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005982 source = sourceDesc;
5983 break;
5984 }
5985 }
5986 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005987}
5988
Eric Laurentb4f42a92022-01-17 17:37:31 +01005989bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005990 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005991 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005992{
5993 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5994 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005995 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005996 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005997 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5998 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5999 return false;
6000 }
6001 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6002 return false;
6003 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006004 }
6005
Eric Laurentd332bc82023-08-04 11:45:23 +02006006 // The caller can have the audio config criteria ignored by either passing a null ptr or
6007 // the AUDIO_CONFIG_INITIALIZER value.
6008 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006009 // some positional channel masks and PCM format and for stereo if low latency performance
6010 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006011
6012 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006013 const bool channel_mask_spatialized =
6014 com_android_media_audio_stereo_spatialization()
6015 ? audio_channel_mask_contains_stereo(config->channel_mask)
6016 : audio_is_channel_mask_spatialized(config->channel_mask);
6017 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006018 return false;
6019 }
6020 if (!audio_is_linear_pcm(config->format)) {
6021 return false;
6022 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006023 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6024 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6025 return false;
6026 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006027 }
6028
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006029 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006030 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006031 if (profile == nullptr) {
6032 return false;
6033 }
6034
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006035 return true;
6036}
6037
6038void AudioPolicyManager::checkVirtualizerClientRoutes() {
6039 std::set<audio_stream_type_t> streamsToInvalidate;
6040 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006041 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6042 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006043 audio_attributes_t attr = client->attributes();
6044 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6045 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6046 audio_config_base_t clientConfig = client->config();
6047 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006048 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006049 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006050 streamsToInvalidate.insert(client->stream());
6051 }
6052 }
6053 }
6054
jiabinc44b3462022-12-08 12:52:31 -08006055 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006056}
6057
Eric Laurente191d1b2022-04-15 11:59:25 +02006058
6059bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6060 const sp<SwAudioOutputDescriptor>& outputDesc) {
6061 if (outputDesc->isDuplicated()) {
6062 return false;
6063 }
6064 DeviceVector devices = outputDesc->supportedDevices();
6065 for (size_t i = 0; i < mOutputs.size(); i++) {
6066 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6067 if (desc == outputDesc || desc->isDuplicated()) {
6068 continue;
6069 }
6070 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6071 if (!sharedDevices.isEmpty()
6072 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6073 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6074 return false;
6075 }
6076 }
6077 return true;
6078}
6079
6080
Eric Laurentfa0f6742021-08-17 18:39:44 +02006081status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006082 const audio_attributes_t *attr,
6083 audio_io_handle_t *output) {
6084 *output = AUDIO_IO_HANDLE_NONE;
6085
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006086 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6087 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6088 audio_config_t *configPtr = nullptr;
6089 audio_config_t config;
6090 if (mixerConfig != nullptr) {
6091 config = audio_config_initializer(mixerConfig);
6092 configPtr = &config;
6093 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006094 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006095 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006096 return BAD_VALUE;
6097 }
6098
6099 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006100 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006101 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006102 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006103 return BAD_VALUE;
6104 }
6105
Eric Laurente191d1b2022-04-15 11:59:25 +02006106 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006107 for (size_t i = 0; i < mOutputs.size(); i++) {
6108 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006109 if (!desc->isDuplicated()
6110 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6111 spatializerOutputs.push_back(desc);
6112 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006113 }
6114 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006115 mSpatializerOutput.clear();
6116 bool outputsChanged = false;
6117 for (const auto& desc : spatializerOutputs) {
6118 if (desc->mProfile == profile
6119 && (configPtr == nullptr
6120 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6121 mSpatializerOutput = desc;
6122 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6123 } else {
6124 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6125 " and devices %s", __func__, desc->mIoHandle,
6126 configPtr != nullptr ? configPtr->channel_mask : 0,
6127 devices.toString().c_str());
6128 closeOutput(desc->mIoHandle);
6129 outputsChanged = true;
6130 }
Eric Laurent39095982021-08-24 18:29:27 +02006131 }
6132
Eric Laurente191d1b2022-04-15 11:59:25 +02006133 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006134 sp<SwAudioOutputDescriptor> desc =
6135 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006136 if (desc != nullptr) {
6137 mSpatializerOutput = desc;
6138 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006139 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006140 }
6141
6142 checkVirtualizerClientRoutes();
6143
Eric Laurente191d1b2022-04-15 11:59:25 +02006144 if (outputsChanged) {
6145 mPreviousOutputs = mOutputs;
6146 mpClientInterface->onAudioPortListUpdate();
6147 }
6148
6149 if (mSpatializerOutput == nullptr) {
6150 ALOGV("%s could not open spatializer output with requested config", __func__);
6151 return BAD_VALUE;
6152 }
Eric Laurent39095982021-08-24 18:29:27 +02006153 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006154 ALOGV("%s returning new spatializer output %d", __func__, *output);
6155 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006156}
6157
Eric Laurentfa0f6742021-08-17 18:39:44 +02006158status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6159 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006160 return INVALID_OPERATION;
6161 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006162 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006163 return BAD_VALUE;
6164 }
Eric Laurent39095982021-08-24 18:29:27 +02006165
Eric Laurente191d1b2022-04-15 11:59:25 +02006166 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6167 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6168 closeOutput(mSpatializerOutput->mIoHandle);
6169 //from now on mSpatializerOutput is null
6170 checkVirtualizerClientRoutes();
6171 }
Eric Laurent39095982021-08-24 18:29:27 +02006172
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006173 return NO_ERROR;
6174}
6175
Eric Laurente552edb2014-03-10 17:42:56 -07006176// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006177// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006178// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006179uint32_t AudioPolicyManager::nextAudioPortGeneration()
6180{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006181 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006182}
6183
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006184AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006185 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006186 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006187 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006188 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006189 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006190 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006191 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006192 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006193 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006194 mAudioPortGeneration(1),
6195 mBeaconMuteRefCount(0),
6196 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006197 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006198 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006199 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006200 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006201{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006202}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006203
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006204status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006205 if (mEngine == nullptr) {
6206 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006207 }
6208 mEngine->setObserver(this);
6209 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006210 if (status != NO_ERROR) {
6211 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6212 return status;
6213 }
François Gaffie2110e042015-03-24 08:41:51 +01006214
jiabin29230182023-04-04 21:02:36 +00006215 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6216 // at the end of this function.
6217 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006218 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6219 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6220
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006221 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006222 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006223 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006224
Eric Laurent3a4311c2014-03-17 12:00:47 -07006225 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006226 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6227 defaultOutputDevice == nullptr ||
6228 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6229 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6230 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006231 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006232 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006233 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006234
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006235 // Silence ALOGV statements
6236 property_set("log.tag." LOG_TAG, "D");
6237
Eric Laurente552edb2014-03-10 17:42:56 -07006238 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006239 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006240}
6241
Eric Laurente0720872014-03-11 09:30:41 -07006242AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006243{
Eric Laurente552edb2014-03-10 17:42:56 -07006244 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006245 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006246 }
6247 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006248 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006249 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006250 mAvailableOutputDevices.clear();
6251 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006252 mOutputs.clear();
6253 mInputs.clear();
6254 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006255 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006256 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006257}
6258
Eric Laurente0720872014-03-11 09:30:41 -07006259status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006260{
Eric Laurent87ffa392015-05-22 10:32:38 -07006261 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006262}
6263
Eric Laurente552edb2014-03-10 17:42:56 -07006264// ---
6265
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006266void AudioPolicyManager::onNewAudioModulesAvailable()
6267{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006268 DeviceVector newDevices;
6269 onNewAudioModulesAvailableInt(&newDevices);
6270 if (!newDevices.empty()) {
6271 nextAudioPortGeneration();
6272 mpClientInterface->onAudioPortListUpdate();
6273 }
6274}
6275
6276void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6277{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006278 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006279 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6280 continue;
6281 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006282 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006283 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6284 handle != AUDIO_MODULE_HANDLE_NONE) {
6285 hwModule->setHandle(handle);
6286 } else {
6287 ALOGW("could not load HW module %s", hwModule->getName());
6288 continue;
6289 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006290 }
6291 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006292 // open all output streams needed to access attached devices.
6293 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006294 // This also validates mAvailableOutputDevices list
6295 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6296 if (!outProfile->canOpenNewIo()) {
6297 ALOGE("Invalid Output profile max open count %u for profile %s",
6298 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6299 continue;
6300 }
6301 if (!outProfile->hasSupportedDevices()) {
6302 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6303 continue;
6304 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006305 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6306 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006307 mTtsOutputAvailable = true;
6308 }
6309
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006310 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006311 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006312 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006313 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6314 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006315 } else {
6316 // choose first device present in profile's SupportedDevices also part of
6317 // mAvailableOutputDevices.
6318 if (availProfileDevices.isEmpty()) {
6319 continue;
6320 }
6321 supportedDevice = availProfileDevices.itemAt(0);
6322 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006323 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006324 continue;
6325 }
6326 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6327 mpClientInterface);
6328 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006329 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6330 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006331 AUDIO_STREAM_DEFAULT,
6332 AUDIO_OUTPUT_FLAG_NONE, &output);
6333 if (status != NO_ERROR) {
6334 ALOGW("Cannot open output stream for devices %s on hw module %s",
6335 supportedDevice->toString().c_str(), hwModule->getName());
6336 continue;
6337 }
6338 for (const auto &device : availProfileDevices) {
6339 // give a valid ID to an attached device once confirmed it is reachable
6340 if (!device->isAttached()) {
6341 device->attach(hwModule);
6342 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006343 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006344 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006345 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6346 }
6347 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006348 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006349 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6350 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006351 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006352 }
Eric Laurent39095982021-08-24 18:29:27 +02006353 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006354 outputDesc->close();
6355 } else {
6356 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306357 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006358 DeviceVector(supportedDevice),
6359 true,
6360 0,
6361 NULL);
6362 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006363 }
6364 // open input streams needed to access attached devices to validate
6365 // mAvailableInputDevices list
6366 for (const auto& inProfile : hwModule->getInputProfiles()) {
6367 if (!inProfile->canOpenNewIo()) {
6368 ALOGE("Invalid Input profile max open count %u for profile %s",
6369 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6370 continue;
6371 }
6372 if (!inProfile->hasSupportedDevices()) {
6373 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6374 continue;
6375 }
6376 // chose first device present in profile's SupportedDevices also part of
6377 // available input devices
6378 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006379 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006380 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006381 ALOGV("%s: Input device list is empty! for profile %s",
6382 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006383 continue;
6384 }
6385 sp<AudioInputDescriptor> inputDesc =
6386 new AudioInputDescriptor(inProfile, mpClientInterface);
6387
6388 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6389 status_t status = inputDesc->open(nullptr,
6390 availProfileDevices.itemAt(0),
6391 AUDIO_SOURCE_MIC,
6392 AUDIO_INPUT_FLAG_NONE,
6393 &input);
6394 if (status != NO_ERROR) {
6395 ALOGW("Cannot open input stream for device %s on hw module %s",
6396 availProfileDevices.toString().c_str(),
6397 hwModule->getName());
6398 continue;
6399 }
6400 for (const auto &device : availProfileDevices) {
6401 // give a valid ID to an attached device once confirmed it is reachable
6402 if (!device->isAttached()) {
6403 device->attach(hwModule);
6404 device->importAudioPortAndPickAudioProfile(inProfile, true);
6405 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006406 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006407 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6408 }
6409 }
6410 inputDesc->close();
6411 }
6412 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006413
6414 // Check if spatializer outputs can be closed until used.
6415 // mOutputs vector never contains duplicated outputs at this point.
6416 std::vector<audio_io_handle_t> outputsClosed;
6417 for (size_t i = 0; i < mOutputs.size(); i++) {
6418 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6419 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6420 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6421 outputsClosed.push_back(desc->mIoHandle);
6422 desc->close();
6423 }
6424 }
6425 for (auto output : outputsClosed) {
6426 removeOutput(output);
6427 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006428}
6429
Eric Laurent98e38192018-02-15 18:31:53 -08006430void AudioPolicyManager::addOutput(audio_io_handle_t output,
6431 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006432{
Eric Laurent1c333e22014-05-20 10:48:17 -07006433 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006434 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006435 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006436 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006437 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006438}
6439
François Gaffie53615e22015-03-19 09:24:12 +01006440void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6441{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006442 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6443 ALOGV("%s: removing primary output", __func__);
6444 mPrimaryOutput = nullptr;
6445 }
François Gaffie53615e22015-03-19 09:24:12 +01006446 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006447 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006448}
6449
Eric Laurent98e38192018-02-15 18:31:53 -08006450void AudioPolicyManager::addInput(audio_io_handle_t input,
6451 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006452{
Eric Laurent1c333e22014-05-20 10:48:17 -07006453 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006454 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006455}
Eric Laurente552edb2014-03-10 17:42:56 -07006456
François Gaffie11d30102018-11-02 16:09:09 +01006457status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006458 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006459 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006460{
François Gaffie11d30102018-11-02 16:09:09 +01006461 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006462 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006463 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006464
François Gaffie11d30102018-11-02 16:09:09 +01006465 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006466 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006467 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006468 }
Eric Laurente552edb2014-03-10 17:42:56 -07006469
Eric Laurent3b73df72014-03-11 09:06:29 -07006470 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006471 // first call getAudioPort to get the supported attributes from the HAL
6472 struct audio_port_v7 port = {};
6473 device->toAudioPort(&port);
6474 status_t status = mpClientInterface->getAudioPort(&port);
6475 if (status == NO_ERROR) {
6476 device->importAudioPort(port);
6477 }
6478
6479 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006480 for (size_t i = 0; i < mOutputs.size(); i++) {
6481 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006482 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006483 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006484 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6485 mOutputs.keyAt(i), device->toString().c_str());
6486 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006487 }
6488 }
6489 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006490 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006491 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006492 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6493 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006494 if (profile->supportsDevice(device)) {
6495 profiles.add(profile);
6496 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6497 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006498 }
6499 }
6500 }
6501
Eric Laurent7b279bb2015-12-14 10:18:23 -08006502 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006503
Eric Laurente552edb2014-03-10 17:42:56 -07006504 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006505 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006506 return BAD_VALUE;
6507 }
6508
6509 // open outputs for matching profiles if needed. Direct outputs are also opened to
6510 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6511 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006512 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006513
6514 // nothing to do if one output is already opened for this profile
6515 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006516 for (j = 0; j < outputs.size(); j++) {
6517 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006518 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006519 // matching profile: save the sample rates, format and channel masks supported
6520 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006521 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006522 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006523 }
Eric Laurente552edb2014-03-10 17:42:56 -07006524 break;
6525 }
6526 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006527 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006528 continue;
6529 }
6530
Eric Laurent3974e3b2017-12-07 17:58:43 -08006531 if (!profile->canOpenNewIo()) {
6532 ALOGW("Max Output number %u already opened for this profile %s",
6533 profile->maxOpenCount, profile->getTagName().c_str());
6534 continue;
6535 }
6536
Eric Laurent83efe1c2017-07-09 16:51:08 -07006537 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006538 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006539 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6540 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006541 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006542 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006543 profiles.removeAt(profile_index);
6544 profile_index--;
6545 } else {
6546 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006547 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006548 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006549 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6550 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006551 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006552 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006553
François Gaffie11d30102018-11-02 16:09:09 +01006554 if (device_distinguishes_on_address(deviceType)) {
6555 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6556 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306557 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6558 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006559 }
Eric Laurente552edb2014-03-10 17:42:56 -07006560 ALOGV("checkOutputsForDevice(): adding output %d", output);
6561 }
6562 }
6563
6564 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006565 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006566 return BAD_VALUE;
6567 }
Eric Laurentd4692962014-05-05 18:13:44 -07006568 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006569 // check if one opened output is not needed any more after disconnecting one device
6570 for (size_t i = 0; i < mOutputs.size(); i++) {
6571 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006572 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006573 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006574 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006575 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006576 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006577 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006578 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6579 mOutputs.keyAt(i));
6580 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006581 }
Eric Laurente552edb2014-03-10 17:42:56 -07006582 }
6583 }
Eric Laurentd4692962014-05-05 18:13:44 -07006584 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006585 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006586 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6587 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006588 if (!profile->supportsDevice(device)) {
6589 continue;
6590 }
6591 ALOGV("checkOutputsForDevice(): "
6592 "clearing direct output profile %zu on module %s",
6593 j, hwModule->getName());
6594 profile->clearAudioProfiles();
6595 if (!profile->hasDynamicAudioProfile()) {
6596 continue;
6597 }
6598 // When a device is disconnected, if there is an IOProfile that contains dynamic
6599 // profiles and supports the disconnected device, call getAudioPort to repopulate
6600 // the capabilities of the devices that is supported by the IOProfile.
6601 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6602 if (supportedDevice == device ||
6603 !mAvailableOutputDevices.contains(supportedDevice)) {
6604 continue;
6605 }
6606 struct audio_port_v7 port;
6607 supportedDevice->toAudioPort(&port);
6608 status_t status = mpClientInterface->getAudioPort(&port);
6609 if (status == NO_ERROR) {
6610 supportedDevice->importAudioPort(port);
6611 }
Eric Laurente552edb2014-03-10 17:42:56 -07006612 }
6613 }
6614 }
6615 }
6616 return NO_ERROR;
6617}
6618
François Gaffie11d30102018-11-02 16:09:09 +01006619status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006620 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006621{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006622 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006623
François Gaffie11d30102018-11-02 16:09:09 +01006624 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006625 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006626 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006627 }
6628
Eric Laurentd4692962014-05-05 18:13:44 -07006629 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006630 // first call getAudioPort to get the supported attributes from the HAL
6631 struct audio_port_v7 port = {};
6632 device->toAudioPort(&port);
6633 status_t status = mpClientInterface->getAudioPort(&port);
6634 if (status == NO_ERROR) {
6635 device->importAudioPort(port);
6636 }
6637
Eric Laurent0dd51852019-04-19 18:18:58 -07006638 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006639 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006640 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006641 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006642 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006643 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006644 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006645
François Gaffie11d30102018-11-02 16:09:09 +01006646 if (profile->supportsDevice(device)) {
6647 profiles.add(profile);
6648 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6649 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006650 }
6651 }
6652 }
6653
Eric Laurent0dd51852019-04-19 18:18:58 -07006654 if (profiles.isEmpty()) {
6655 ALOGW("%s: No input profile available for device %s",
6656 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006657 return BAD_VALUE;
6658 }
6659
6660 // open inputs for matching profiles if needed. Direct inputs 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++) {
6663
Eric Laurent1c333e22014-05-20 10:48:17 -07006664 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006665
Eric Laurentd4692962014-05-05 18:13:44 -07006666 // nothing to do if one input is already opened for this profile
6667 size_t input_index;
6668 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6669 desc = mInputs.valueAt(input_index);
6670 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006671 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006672 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006673 }
Eric Laurentd4692962014-05-05 18:13:44 -07006674 break;
6675 }
6676 }
6677 if (input_index != mInputs.size()) {
6678 continue;
6679 }
6680
Eric Laurent3974e3b2017-12-07 17:58:43 -08006681 if (!profile->canOpenNewIo()) {
6682 ALOGW("Max Input number %u already opened for this profile %s",
6683 profile->maxOpenCount, profile->getTagName().c_str());
6684 continue;
6685 }
6686
Eric Laurentfe231122017-11-17 17:48:06 -08006687 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006688 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006689 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006690
Eric Laurentcf2c0212014-07-25 16:20:43 -07006691 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006692 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006693 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006694 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006695 mpClientInterface->setParameters(input, String8(param));
6696 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006697 }
jiabin12537fc2023-10-12 17:56:08 +00006698 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006699 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006700 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006701 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006702 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006703 }
6704
Eric Laurent0dd51852019-04-19 18:18:58 -07006705 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006706 addInput(input, desc);
6707 }
6708 } // endif input != 0
6709
Eric Laurentcf2c0212014-07-25 16:20:43 -07006710 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006711 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006712 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006713 profiles.removeAt(profile_index);
6714 profile_index--;
6715 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006716 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006717 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006718 }
Eric Laurentd4692962014-05-05 18:13:44 -07006719 ALOGV("checkInputsForDevice(): adding input %d", input);
6720 }
6721 } // end scan profiles
6722
6723 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006724 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006725 return BAD_VALUE;
6726 }
6727 } else {
6728 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006729 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006730 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006731 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006732 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006733 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006734 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006735 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006736 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6737 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006738 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006739 }
6740 }
6741 }
6742 } // end disconnect
6743
6744 return NO_ERROR;
6745}
6746
6747
Eric Laurente0720872014-03-11 09:30:41 -07006748void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006749{
6750 ALOGV("closeOutput(%d)", output);
6751
François Gaffie1c878552018-11-22 16:53:21 +01006752 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6753 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006754 ALOGW("closeOutput() unknown output %d", output);
6755 return;
6756 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006757 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006758 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006759
Eric Laurente552edb2014-03-10 17:42:56 -07006760 // look for duplicated outputs connected to the output being removed.
6761 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006762 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6763 if (dupOutput->isDuplicated() &&
6764 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6765 sp<SwAudioOutputDescriptor> remainingOutput =
6766 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006767 // As all active tracks on duplicated output will be deleted,
6768 // and as they were also referenced on the other output, the reference
6769 // count for their stream type must be adjusted accordingly on
6770 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006771 const bool wasActive = remainingOutput->isActive();
6772 // Note: no-op on the closing output where all clients has already been set inactive
6773 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006774 // stop() will be a no op if the output is still active but is needed in case all
6775 // active streams refcounts where cleared above
6776 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006777 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006778 }
Eric Laurente552edb2014-03-10 17:42:56 -07006779 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6780 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6781
6782 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006783 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006784 }
6785 }
6786
Eric Laurent05b90f82014-08-27 15:32:29 -07006787 nextAudioPortGeneration();
6788
François Gaffie1c878552018-11-22 16:53:21 +01006789 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006790 if (index >= 0) {
6791 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006792 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6793 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006794 mAudioPatches.removeItemsAt(index);
6795 mpClientInterface->onAudioPatchListUpdate();
6796 }
6797
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006798 if (closingOutputWasActive) {
6799 closingOutput->stop();
6800 }
François Gaffie1c878552018-11-22 16:53:21 +01006801 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006802 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6803 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6804 for (const auto device : closingOutput->devices()) {
6805 device->setPreferredConfig(nullptr);
6806 }
6807 }
Eric Laurente552edb2014-03-10 17:42:56 -07006808
François Gaffie53615e22015-03-19 09:24:12 +01006809 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006810 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006811 if (closingOutput == mSpatializerOutput) {
6812 mSpatializerOutput.clear();
6813 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006814
6815 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6816 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006817 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006818 bool directOutputOpen = false;
6819 for (size_t i = 0; i < mOutputs.size(); i++) {
6820 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6821 directOutputOpen = true;
6822 break;
6823 }
6824 }
6825 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006826 ALOGV("no direct outputs open, reset MSD patches");
6827 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6828 // how output devices for patching are resolved. Avoid by caching and reusing the
6829 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6830 // devices to patch to. This may be complicated by the fact that devices may become
6831 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006832 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006833 }
6834 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006835}
6836
6837void AudioPolicyManager::closeInput(audio_io_handle_t input)
6838{
6839 ALOGV("closeInput(%d)", input);
6840
6841 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6842 if (inputDesc == NULL) {
6843 ALOGW("closeInput() unknown input %d", input);
6844 return;
6845 }
6846
Eric Laurent6a94d692014-05-20 11:18:06 -07006847 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006848
François Gaffie11d30102018-11-02 16:09:09 +01006849 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006850 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006851 if (index >= 0) {
6852 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006853 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6854 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006855 mAudioPatches.removeItemsAt(index);
6856 mpClientInterface->onAudioPatchListUpdate();
6857 }
6858
François Gaffie6ebbce02023-07-19 13:27:53 +02006859 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006860 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006861 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006862
François Gaffie11d30102018-11-02 16:09:09 +01006863 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6864 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006865 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006866 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006867 }
Eric Laurente552edb2014-03-10 17:42:56 -07006868}
6869
François Gaffie11d30102018-11-02 16:09:09 +01006870SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6871 const DeviceVector &devices,
6872 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006873{
6874 SortedVector<audio_io_handle_t> outputs;
6875
François Gaffie11d30102018-11-02 16:09:09 +01006876 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006877 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006878 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006879 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006880 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006881 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006882 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006883 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006884 outputs.add(openOutputs.keyAt(i));
6885 }
6886 }
6887 return outputs;
6888}
6889
Mikhail Naganov37977152018-07-11 15:54:44 -07006890void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6891{
6892 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6893 // output is suspended before any tracks are moved to it
6894 checkA2dpSuspend();
6895 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006896 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006897 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006898 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006899 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006900 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6901 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6902 // configuration changes will ultimately be rerouted correctly. We can still avoid
6903 // unnecessary rerouting by caching and reusing the arguments to
6904 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6905 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006906 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006907 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006908 // an event that changed routing likely occurred, inform upper layers
6909 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006910}
6911
François Gaffiec005e562018-11-06 15:04:49 +01006912bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6913 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006914{
François Gaffiec005e562018-11-06 15:04:49 +01006915 return mEngine->getProductStrategyForAttributes(lAttr) ==
6916 mEngine->getProductStrategyForAttributes(rAttr);
6917}
6918
Francois Gaffieff1eb522020-05-06 18:37:04 +02006919void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6920{
6921 for (size_t i = 0; i < mAudioSources.size(); i++) {
6922 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6923 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006924 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006925 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006926 connectAudioSource(sourceDesc);
6927 }
6928 }
6929}
6930
6931void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6932{
6933 for (size_t i = 0; i < mAudioSources.size(); i++) {
6934 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6935 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6936 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6937 disconnectAudioSource(sourceDesc);
6938 }
6939 }
6940}
6941
François Gaffiec005e562018-11-06 15:04:49 +01006942void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6943{
6944 auto psId = mEngine->getProductStrategyForAttributes(attr);
6945
6946 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6947 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006948
François Gaffie11d30102018-11-02 16:09:09 +01006949 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6950 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006951
Eric Laurentc209fe42020-06-05 18:11:23 -07006952 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006953 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006954 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006955 // take into account dynamic audio policies related changes: if a client is now associated
6956 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006957 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006958 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6959 if (desc->isDuplicated()) {
6960 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006961 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006962 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6963 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6964 continue;
6965 }
6966 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006967 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006968 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6969 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6970 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006971 if (status != OK) {
6972 continue;
6973 }
yucliuf4de36d2020-09-14 14:57:56 -07006974 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006975 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006976 maxLatency = desc->latency();
6977 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006978 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006979 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006980 }
6981 }
6982
Eric Laurent56ed8842022-11-15 16:04:41 +01006983 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006984 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6985 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006986 for (audio_io_handle_t srcOut : srcOutputs) {
6987 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006988 if (desc == nullptr) continue;
6989
6990 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006991 maxLatency = desc->latency();
6992 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006993
Eric Laurent56ed8842022-11-15 16:04:41 +01006994 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006995 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006996 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006997 // a client on a non direct outputs has necessarily a linear PCM format
6998 // so we can call selectOutput() safely
6999 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7000 client->flags(),
7001 client->config().format,
7002 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007003 client->config().sample_rate,
7004 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007005 if (newOutput != srcOut) {
7006 invalidate = true;
7007 break;
7008 }
7009 } else {
7010 sp<IOProfile> profile = getProfileForOutput(newDevices,
7011 client->config().sample_rate,
7012 client->config().format,
7013 client->config().channel_mask,
7014 client->flags(),
7015 true /* directOnly */);
7016 if (profile != desc->mProfile) {
7017 invalidate = true;
7018 break;
7019 }
7020 }
7021 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007022 // mute strategy while moving tracks from one output to another
7023 if (invalidate) {
7024 invalidatedOutputs.push_back(desc);
7025 if (desc->isStrategyActive(psId)) {
7026 setStrategyMute(psId, true, desc);
7027 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7028 newDevices.types());
7029 }
Eric Laurente552edb2014-03-10 17:42:56 -07007030 }
François Gaffiec005e562018-11-06 15:04:49 +01007031 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007032 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007033 connectAudioSource(source);
7034 }
Eric Laurente552edb2014-03-10 17:42:56 -07007035 }
7036
Eric Laurent56ed8842022-11-15 16:04:41 +01007037 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7038 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7039 std::to_string(srcOutputs[0]).c_str(),
7040 std::to_string(dstOutputs[0]).c_str());
7041
François Gaffiec005e562018-11-06 15:04:49 +01007042 // Move effects associated to this stream from previous output to new output
7043 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007044 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007045 }
François Gaffiec005e562018-11-06 15:04:49 +01007046 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007047 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007048 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007049 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007050 desc->setTracksInvalidatedStatusByStrategy(psId);
7051 }
Eric Laurente552edb2014-03-10 17:42:56 -07007052 }
7053 }
7054}
7055
Eric Laurente0720872014-03-11 09:30:41 -07007056void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007057{
François Gaffiec005e562018-11-06 15:04:49 +01007058 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7059 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7060 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007061 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007062 }
Eric Laurente552edb2014-03-10 17:42:56 -07007063}
7064
Kevin Rocard153f92d2018-12-18 18:33:28 -08007065void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007066 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007067 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007068 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007069 for (size_t i = 0; i < mOutputs.size(); i++) {
7070 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7071 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007072 sp<AudioPolicyMix> primaryMix;
7073 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007074 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007075 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7076 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7077 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007078 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7079 for (auto &secondaryMix : secondaryMixes) {
7080 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7081 if (outputDesc != nullptr &&
7082 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7083 secondaryDescs.push_back(outputDesc);
7084 }
7085 }
7086
jiabinc44b3462022-12-08 12:52:31 -08007087 if (status != OK &&
7088 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7089 // When it failed to query secondary output, only invalidate the client that is not
7090 // MMAP. The reason is that MMAP stream will not support secondary output.
7091 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007092 } else if (!std::equal(
7093 client->getSecondaryOutputs().begin(),
7094 client->getSecondaryOutputs().end(),
7095 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007096 if (!audio_is_linear_pcm(client->config().format)) {
7097 // If the format is not PCM, the tracks should be invalidated to get correct
7098 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007099 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007100 } else {
7101 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7102 std::vector<audio_io_handle_t> secondaryOutputIds;
7103 for (const auto &secondaryDesc: secondaryDescs) {
7104 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7105 weakSecondaryDescs.push_back(secondaryDesc);
7106 }
7107 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7108 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007109 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007110 }
7111 }
7112 }
jiabin10a03f12021-05-07 23:46:28 +00007113 if (!trackSecondaryOutputs.empty()) {
7114 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7115 }
jiabinc44b3462022-12-08 12:52:31 -08007116 if (!clientsToInvalidate.empty()) {
7117 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7118 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007119 }
7120}
7121
Eric Laurent2517af32020-11-25 15:31:27 +01007122bool AudioPolicyManager::isScoRequestedForComm() const {
7123 AudioDeviceTypeAddrVector devices;
7124 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7125 for (const auto &device : devices) {
7126 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7127 return true;
7128 }
7129 }
7130 return false;
7131}
7132
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007133bool AudioPolicyManager::isHearingAidUsedForComm() const {
7134 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7135 true /*fromCache*/);
7136 for (const auto &device : devices) {
7137 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7138 return true;
7139 }
7140 }
7141 return false;
7142}
7143
7144
Eric Laurente0720872014-03-11 09:30:41 -07007145void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007146{
François Gaffie53615e22015-03-19 09:24:12 +01007147 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007148 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007149 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007150 return;
7151 }
7152
Eric Laurent3a4311c2014-03-17 12:00:47 -07007153 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007154 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7155 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007156 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007157
7158 // if suspended, restore A2DP output if:
7159 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007160 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007161 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007162 //
Eric Laurentf732e072016-08-03 19:30:28 -07007163 // if not suspended, suspend A2DP output if:
7164 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007165 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007166 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007167 //
7168 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007169 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007170 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007171 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007172 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007173
7174 mpClientInterface->restoreOutput(a2dpOutput);
7175 mA2dpSuspended = false;
7176 }
7177 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007178 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007179 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007180 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007181 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007182
7183 mpClientInterface->suspendOutput(a2dpOutput);
7184 mA2dpSuspended = true;
7185 }
7186 }
7187}
7188
François Gaffie11d30102018-11-02 16:09:09 +01007189DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7190 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007191{
François Gaffiedb1755b2023-09-01 11:50:35 +02007192 if (outputDesc == nullptr) {
7193 return DeviceVector{};
7194 }
François Gaffie11d30102018-11-02 16:09:09 +01007195
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007196 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007197 if (index >= 0) {
7198 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007199 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007200 ALOGV("%s device %s forced by patch %d", __func__,
7201 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7202 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007203 }
7204 }
7205
Dean Wheatley514b4312020-06-17 21:45:00 +10007206 // Do not retrieve engine device for outputs through MSD
7207 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7208 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7209 return outputDesc->devices();
7210 }
7211
Eric Laurent97ac8712018-07-27 18:59:02 -07007212 // Honor explicit routing requests only if no client using default routing is active on this
7213 // input: a specific app can not force routing for other apps by setting a preferred device.
7214 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007215 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007216 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007217 if (device != nullptr) {
7218 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007219 }
7220
François Gaffiea807ef92018-11-05 10:44:33 +01007221 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7222 // of setForceUse / Default Bus device here
7223 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7224 if (device != nullptr) {
7225 return DeviceVector(device);
7226 }
7227
François Gaffiedb1755b2023-09-01 11:50:35 +02007228 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007229 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7230 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7231 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307232 auto hasStreamActive = [&](auto stream) {
7233 return hasStream(streams, stream) && isStreamActive(stream, 0);
7234 };
Eric Laurent484e9272018-06-07 17:29:23 -07007235
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307236 auto doGetOutputDevicesForVoice = [&]() {
7237 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007238 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307239 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007240 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7241 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307242 };
7243
7244 // With low-latency playing on speaker, music on WFD, when the first low-latency
7245 // output is stopped, getNewOutputDevices checks for a product strategy
7246 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007247 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307248 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7249 // stream is associated to the output descriptor.
7250 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7251 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7252 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7253 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007254 // Retrieval of devices for voice DL is done on primary output profile, cannot
7255 // check the route (would force modifying configuration file for this profile)
7256 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7257 break;
7258 }
Eric Laurente552edb2014-03-10 17:42:56 -07007259 }
François Gaffiec005e562018-11-06 15:04:49 +01007260 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007261 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007262}
7263
François Gaffie11d30102018-11-02 16:09:09 +01007264sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7265 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007266{
François Gaffie11d30102018-11-02 16:09:09 +01007267 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007268
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007269 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007270 if (index >= 0) {
7271 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007272 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007273 ALOGV("getNewInputDevice() device %s forced by patch %d",
7274 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7275 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007276 }
7277 }
7278
Eric Laurent97ac8712018-07-27 18:59:02 -07007279 // Honor explicit routing requests only if no client using default routing is active on this
7280 // input: a specific app can not force routing for other apps by setting a preferred device.
7281 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007282 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7283 if (device != nullptr) {
7284 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007285 }
7286
Eric Laurentdc95a252018-04-12 12:46:56 -07007287 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007288 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007289 audio_attributes_t attributes;
7290 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007291 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007292 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7293 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007294 attributes = topClient->attributes();
7295 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007296 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007297 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007298 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7299 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007300 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007301 }
7302
Francois Gaffie716e1432019-01-14 16:58:59 +01007303 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7304 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007305 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007306 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007307 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007308 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007309
Eric Laurente552edb2014-03-10 17:42:56 -07007310 return device;
7311}
7312
Eric Laurent794fde22016-03-11 09:50:45 -08007313bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7314 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007315 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007316}
7317
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007318status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007319 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007320 if (devices == nullptr) {
7321 return BAD_VALUE;
7322 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007323
Andy Hung6d23c0f2022-02-16 09:37:15 -08007324 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007325 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7326 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007327 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007328 for (const auto& device : curDevices) {
7329 devices->push_back(device->getDeviceTypeAddr());
7330 }
7331 return NO_ERROR;
7332}
7333
Eric Laurente0720872014-03-11 09:30:41 -07007334void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007335 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007336 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007337 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007338 updateDevicesAndOutputs();
7339 break;
7340 default:
7341 break;
7342 }
7343}
7344
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007345uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007346
7347 // skip beacon mute management if a dedicated TTS output is available
7348 if (mTtsOutputAvailable) {
7349 return 0;
7350 }
7351
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007352 switch(event) {
7353 case STARTING_OUTPUT:
7354 mBeaconMuteRefCount++;
7355 break;
7356 case STOPPING_OUTPUT:
7357 if (mBeaconMuteRefCount > 0) {
7358 mBeaconMuteRefCount--;
7359 }
7360 break;
7361 case STARTING_BEACON:
7362 mBeaconPlayingRefCount++;
7363 break;
7364 case STOPPING_BEACON:
7365 if (mBeaconPlayingRefCount > 0) {
7366 mBeaconPlayingRefCount--;
7367 }
7368 break;
7369 }
7370
7371 if (mBeaconMuteRefCount > 0) {
7372 // any playback causes beacon to be muted
7373 return setBeaconMute(true);
7374 } else {
7375 // no other playback: unmute when beacon starts playing, mute when it stops
7376 return setBeaconMute(mBeaconPlayingRefCount == 0);
7377 }
7378}
7379
7380uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7381 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7382 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7383 // keep track of muted state to avoid repeating mute/unmute operations
7384 if (mBeaconMuted != mute) {
7385 // mute/unmute AUDIO_STREAM_TTS on all outputs
7386 ALOGV("\t muting %d", mute);
7387 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007388 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7389 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7390 ALOGV("\t no tts volume source available");
7391 return 0;
7392 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007393 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007394 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007395 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007396 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007397 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007398 maxLatency = latency;
7399 }
7400 }
7401 mBeaconMuted = mute;
7402 return maxLatency;
7403 }
7404 return 0;
7405}
7406
Eric Laurente0720872014-03-11 09:30:41 -07007407void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007408{
François Gaffiec005e562018-11-06 15:04:49 +01007409 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007410 mPreviousOutputs = mOutputs;
7411}
7412
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007413uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007414 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007415 uint32_t delayMs)
7416{
7417 // mute/unmute strategies using an incompatible device combination
7418 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7419 // if unmuting, unmute only after the specified delay
7420 if (outputDesc->isDuplicated()) {
7421 return 0;
7422 }
7423
7424 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007425 DeviceVector devices = outputDesc->devices();
7426 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007427
François Gaffiec005e562018-11-06 15:04:49 +01007428 auto productStrategies = mEngine->getOrderedProductStrategies();
7429 for (const auto &productStrategy : productStrategies) {
7430 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7431 DeviceVector curDevices =
7432 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7433 curDevices = curDevices.filter(outputDesc->supportedDevices());
7434 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007435 bool doMute = false;
7436
François Gaffiec005e562018-11-06 15:04:49 +01007437 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007438 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007439 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7440 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007441 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007442 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007443 }
Eric Laurent99401132014-05-07 19:48:15 -07007444 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007445 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007446 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007447 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007448 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007449 continue;
7450 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307451 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007452 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7453 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7454 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007455 if (mute) {
7456 // FIXME: should not need to double latency if volume could be applied
7457 // immediately by the audioflinger mixer. We must account for the delay
7458 // between now and the next time the audioflinger thread for this output
7459 // will process a buffer (which corresponds to one buffer size,
7460 // usually 1/2 or 1/4 of the latency).
7461 if (muteWaitMs < desc->latency() * 2) {
7462 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007463 }
7464 }
7465 }
7466 }
7467 }
7468 }
7469
Eric Laurent99401132014-05-07 19:48:15 -07007470 // temporary mute output if device selection changes to avoid volume bursts due to
7471 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007472 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007473 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007474
Eric Laurentdc462862016-07-19 12:29:53 -07007475 if (muteWaitMs < tempMuteWaitMs) {
7476 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007477 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007478
7479 // If recommended duration is defined, replace temporary mute duration to avoid
7480 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7481 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7482 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7483 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7484 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7485
François Gaffieaaac0fd2018-11-22 17:56:39 +01007486 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7487 // make sure that we do not start the temporary mute period too early in case of
7488 // delayed device change
7489 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7490 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007491 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007492 }
7493 }
7494
Eric Laurente552edb2014-03-10 17:42:56 -07007495 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7496 if (muteWaitMs > delayMs) {
7497 muteWaitMs -= delayMs;
7498 usleep(muteWaitMs * 1000);
7499 return muteWaitMs;
7500 }
7501 return 0;
7502}
7503
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307504uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7505 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007506 const DeviceVector &devices,
7507 bool force,
7508 int delayMs,
7509 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007510 bool requiresMuteCheck, bool requiresVolumeCheck,
7511 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007512{
jiabin3ff8d7d2022-12-13 06:27:44 +00007513 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307514 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7515 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7516 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007517 uint32_t muteWaitMs;
7518
7519 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307520 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007521 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307522 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007523 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007524 return muteWaitMs;
7525 }
Eric Laurente552edb2014-03-10 17:42:56 -07007526
7527 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007528 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007529 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007530 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007531
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307532 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7533 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007534
7535 if (!filteredDevices.isEmpty()) {
7536 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007537 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007538
7539 // if the outputs are not materially active, there is no need to mute.
7540 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007541 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007542 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307543 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7544 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007545 muteWaitMs = 0;
7546 }
Eric Laurente552edb2014-03-10 17:42:56 -07007547
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007548 bool outputRouted = outputDesc->isRouted();
7549
Eric Laurent79ea9582020-06-11 18:49:24 -07007550 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7551 // output profile or if new device is not supported AND previous device(s) is(are) still
7552 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007553 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307554 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7555 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007556 // restore previous device after evaluating strategy mute state
7557 outputDesc->setDevices(prevDevices);
7558 return muteWaitMs;
7559 }
7560
Eric Laurente552edb2014-03-10 17:42:56 -07007561 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007562 // the requested device is AUDIO_DEVICE_NONE
7563 // OR the requested device is the same as current device
7564 // AND force is not specified
7565 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007566 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007567 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307568 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7569 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7570 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007571 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307572 ALOGV("%s %s setting same device on routed output, force apply volumes",
7573 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007574 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7575 }
Eric Laurente552edb2014-03-10 17:42:56 -07007576 return muteWaitMs;
7577 }
7578
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307579 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7580 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007581
Eric Laurente552edb2014-03-10 17:42:56 -07007582 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007583 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007584 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007585 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007586 PatchBuilder patchBuilder;
7587 patchBuilder.addSource(outputDesc);
7588 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7589 for (const auto &filteredDevice : filteredDevices) {
7590 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007591 }
7592
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007593 // Add half reported latency to delayMs when muteWaitMs is null in order
7594 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007595 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7596 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7597 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007598 }
Eric Laurente552edb2014-03-10 17:42:56 -07007599
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007600 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7601 if (!skipMuteDelay) {
7602 // update stream volumes according to new device
7603 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7604 }
Eric Laurente552edb2014-03-10 17:42:56 -07007605
7606 return muteWaitMs;
7607}
7608
Eric Laurentc75307b2015-03-17 15:29:32 -07007609status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007610 int delayMs,
7611 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007612{
Eric Laurent6a94d692014-05-20 11:18:06 -07007613 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007614 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7615 return INVALID_OPERATION;
7616 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007617 if (patchHandle) {
7618 index = mAudioPatches.indexOfKey(*patchHandle);
7619 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007620 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007621 }
7622 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007623 return INVALID_OPERATION;
7624 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007625 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007626 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007627 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007628 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007629 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007630 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007631 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007632 return status;
7633}
7634
7635status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007636 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007637 bool force,
7638 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007639{
7640 status_t status = NO_ERROR;
7641
Eric Laurent1f2f2232014-06-02 12:01:23 -07007642 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007643 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7644 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007645
François Gaffie11d30102018-11-02 16:09:09 +01007646 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007647 PatchBuilder patchBuilder;
7648 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007649 // AUDIO_SOURCE_HOTWORD is for internal use only:
7650 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007651 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7652 auto result = usecase;
7653 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7654 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7655 }
7656 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007657 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007658 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007659 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007660 }
7661 }
7662 return status;
7663}
7664
Eric Laurent6a94d692014-05-20 11:18:06 -07007665status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7666 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007667{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007668 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007669 ssize_t index;
7670 if (patchHandle) {
7671 index = mAudioPatches.indexOfKey(*patchHandle);
7672 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007673 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007674 }
7675 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007676 return INVALID_OPERATION;
7677 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007678 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007679 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007680 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007681 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007682 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007683 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007684 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007685 return status;
7686}
7687
François Gaffie11d30102018-11-02 16:09:09 +01007688sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007689 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007690 audio_format_t& format,
7691 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007692 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007693{
7694 // Choose an input profile based on the requested capture parameters: select the first available
7695 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007696 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007697 //
7698 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7699 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007700
Atneya Nair0f0a8032022-12-12 16:20:12 -08007701 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7702 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7703 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7704
7705 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007706
jiabin2fd710d2022-05-02 23:20:22 +00007707 for (;;) {
7708 sp<IOProfile> firstInexact = nullptr;
7709 uint32_t updatedSamplingRate = 0;
7710 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7711 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7712 for (const auto& hwModule : mHwModules) {
7713 for (const auto& profile : hwModule->getInputProfiles()) {
7714 // profile->log();
7715 //updatedFormat = format;
7716 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7717 &samplingRate /*updatedSamplingRate*/,
7718 format,
7719 &format, /*updatedFormat*/
7720 channelMask,
7721 &channelMask /*updatedChannelMask*/,
7722 // FIXME ugly cast
7723 (audio_output_flags_t) flags,
7724 true /*exactMatchRequiredForInputFlags*/)) {
7725 return profile;
7726 }
7727 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7728 samplingRate,
7729 &updatedSamplingRate,
7730 format,
7731 &updatedFormat,
7732 channelMask,
7733 &updatedChannelMask,
7734 // FIXME ugly cast
7735 (audio_output_flags_t) flags,
7736 false /*exactMatchRequiredForInputFlags*/)) {
7737 firstInexact = profile;
7738 }
7739 }
7740 }
7741
7742 if (firstInexact != nullptr) {
7743 samplingRate = updatedSamplingRate;
7744 format = updatedFormat;
7745 channelMask = updatedChannelMask;
7746 return firstInexact;
7747 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7748 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7749 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7750 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7751 flags = AUDIO_INPUT_FLAG_NONE;
7752 } else { // fail
7753 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7754 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7755 samplingRate, format, channelMask, oriFlags);
7756 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007757 }
7758 }
jiabin2fd710d2022-05-02 23:20:22 +00007759
7760 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007761}
7762
François Gaffieaaac0fd2018-11-22 17:56:39 +01007763float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7764 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007765 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007766 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007767{
jiabin9a3361e2019-10-01 09:38:30 -07007768 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007769
7770 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7771 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7772 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7773 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007774 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7775 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7776 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7777 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7778 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007779 // Verify that the current volume source is not the ringer volume to prevent recursively
7780 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7781 // to the same volume group.
7782 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007783 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7784 mOutputs.isActive(ringVolumeSrc, 0)) {
7785 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007786 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007787 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007788 }
7789
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007790 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007791 if ((volumeSource != callVolumeSrc && (isInCall() ||
7792 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007793 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007794 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7795 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007796 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7797 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7798 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007799 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007800 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007801 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007802 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007803 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007804 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007805 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7806 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7807 // programmatically muted.
7808 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7809 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7810 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007811 bool exemptFromCapping =
7812 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7813 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007814 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7815 volumeSource, volumeDb);
7816 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007817 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7818 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7819 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007820 }
7821 }
Eric Laurente552edb2014-03-10 17:42:56 -07007822 // if a headset is connected, apply the following rules to ring tones and notifications
7823 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007824 // - always attenuate notifications volume by 6dB
7825 // - attenuate ring tones volume by 6dB unless music is not playing and
7826 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007827 // - if music is playing, always limit the volume to current music volume,
7828 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007829 if (!Intersection(deviceTypes,
7830 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7831 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007832 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7833 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007834 ((volumeSource == alarmVolumeSrc ||
7835 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007836 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7837 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7838 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007839 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7840 curves.canBeMuted()) {
7841
Eric Laurente552edb2014-03-10 17:42:56 -07007842 // when the phone is ringing we must consider that music could have been paused just before
7843 // by the music application and behave as if music was active if the last music track was
7844 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007845 // Verify that the current volume source is not the music volume to prevent recursively
7846 // calling to compute volume. This could happen in cases where music and
7847 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7848 if (volumeSource != musicVolumeSrc &&
7849 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7850 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007851 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007852 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007853 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7854 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007855 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007856 float musicVolDb = computeVolume(musicCurves,
7857 musicVolumeSrc,
7858 musicCurves.getVolumeIndex(musicDevice),
7859 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007860 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7861 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7862 if (volumeDb > minVolDb) {
7863 volumeDb = minVolDb;
7864 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007865 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007866 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7867 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7868 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007869 // on A2DP, also ensure notification volume is not too low compared to media when
7870 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007871 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007872 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007873 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7874 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007875 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7876 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007877 }
7878 }
jiabin9a3361e2019-10-01 09:38:30 -07007879 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007880 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007881 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007882 }
7883 }
7884
François Gaffie43c73442018-11-08 08:21:55 +01007885 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007886}
7887
Eric Laurent3839bc02018-07-10 18:33:34 -07007888int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007889 VolumeSource fromVolumeSource,
7890 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007891{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007892 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007893 return srcIndex;
7894 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007895 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7896 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007897 float minSrc = (float)srcCurves.getVolumeIndexMin();
7898 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7899 float minDst = (float)dstCurves.getVolumeIndexMin();
7900 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007901
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007902 // preserve mute request or correct range
7903 if (srcIndex < minSrc) {
7904 if (srcIndex == 0) {
7905 return 0;
7906 }
7907 srcIndex = minSrc;
7908 } else if (srcIndex > maxSrc) {
7909 srcIndex = maxSrc;
7910 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007911 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7912}
7913
François Gaffieaaac0fd2018-11-22 17:56:39 +01007914status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7915 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007916 int index,
7917 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007918 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007919 int delayMs,
7920 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007921{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007922 // do not change actual attributes volume if the attributes is muted
7923 if (outputDesc->isMuted(volumeSource)) {
7924 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7925 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007926 return NO_ERROR;
7927 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007928
Eric Laurentae6e88c2024-01-10 14:42:57 +01007929 bool isVoiceVolSrc;
7930 bool isBtScoVolSrc;
7931 if (!isVolumeConsistentForCalls(
7932 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07007933 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01007934 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07007935 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007936 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01007937
jiabin9a3361e2019-10-01 09:38:30 -07007938 if (deviceTypes.empty()) {
7939 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007940 index = curves.getVolumeIndex(deviceTypes);
7941 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7942 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007943 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007944
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007945 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7946 ALOGE("invalid volume index range");
7947 return BAD_VALUE;
7948 }
7949
jiabin9a3361e2019-10-01 09:38:30 -07007950 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7951 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007952 // Force VoIP volume to max for bluetooth SCO device except if muted
7953 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007954 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007955 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007956 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007957 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007958 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7959 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007960
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007961 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01007962 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007963 }
Eric Laurente552edb2014-03-10 17:42:56 -07007964 return NO_ERROR;
7965}
7966
Eric Laurentae6e88c2024-01-10 14:42:57 +01007967void AudioPolicyManager::setVoiceVolume(
7968 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
7969 float voiceVolume;
7970 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
7971 // by the headset
7972 if (isVoiceVolSrc) {
7973 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
7974 } else {
7975 voiceVolume = index == 0 ? 0.0 : 1.0;
7976 }
7977 if (voiceVolume != mLastVoiceVolume) {
7978 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7979 mLastVoiceVolume = voiceVolume;
7980 }
7981}
7982
7983bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
7984 const DeviceTypeSet& deviceTypes,
7985 bool& isVoiceVolSrc,
7986 bool& isBtScoVolSrc,
7987 const char* caller) {
7988 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7989 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7990 const bool isScoRequested = isScoRequestedForComm();
7991 const bool isHAUsed = isHearingAidUsedForComm();
7992
7993 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7994 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
7995
7996 if ((callVolSrc != btScoVolSrc) &&
7997 ((isVoiceVolSrc && isScoRequested) ||
7998 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7999 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8000 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8001 volumeSource, isScoRequested ? " " : " not ");
8002 return false;
8003 }
8004 return true;
8005}
8006
Eric Laurentc75307b2015-03-17 15:29:32 -07008007void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008008 const DeviceTypeSet& deviceTypes,
8009 int delayMs,
8010 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008011{
jiabincd510522020-01-22 09:40:55 -08008012 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008013 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8014 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8015 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008016 curves.getVolumeIndex(deviceTypes),
8017 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008018 }
8019}
8020
François Gaffiec005e562018-11-06 15:04:49 +01008021void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8022 bool on,
8023 const sp<AudioOutputDescriptor>& outputDesc,
8024 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008025 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008026{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008027 std::vector<VolumeSource> sourcesToMute;
8028 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8029 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8030 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008031 VolumeSource source = toVolumeSource(attributes, false);
8032 if ((source != VOLUME_SOURCE_NONE) &&
8033 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8034 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008035 sourcesToMute.push_back(source);
8036 }
Eric Laurente552edb2014-03-10 17:42:56 -07008037 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008038 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008039 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008040 }
8041
Eric Laurente552edb2014-03-10 17:42:56 -07008042}
8043
François Gaffieaaac0fd2018-11-22 17:56:39 +01008044void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8045 bool on,
8046 const sp<AudioOutputDescriptor>& outputDesc,
8047 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008048 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008049{
jiabin9a3361e2019-10-01 09:38:30 -07008050 if (deviceTypes.empty()) {
8051 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008052 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008053 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008054 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008055 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008056 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008057 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008058 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8059 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008060 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008061 }
8062 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008063 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8064 // ignored
8065 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008066 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008067 if (!outputDesc->isMuted(volumeSource)) {
8068 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008069 return;
8070 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008071 if (outputDesc->decMuteCount(volumeSource) == 0) {
8072 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008073 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008074 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008075 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008076 delayMs);
8077 }
8078 }
8079}
8080
François Gaffie53615e22015-03-19 09:24:12 +01008081bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8082{
François Gaffiec005e562018-11-06 15:04:49 +01008083 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008084 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8085 return true;
8086 }
8087
8088 // has known usage?
8089 switch (paa->usage) {
8090 case AUDIO_USAGE_UNKNOWN:
8091 case AUDIO_USAGE_MEDIA:
8092 case AUDIO_USAGE_VOICE_COMMUNICATION:
8093 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8094 case AUDIO_USAGE_ALARM:
8095 case AUDIO_USAGE_NOTIFICATION:
8096 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8097 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8098 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8099 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8100 case AUDIO_USAGE_NOTIFICATION_EVENT:
8101 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8102 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8103 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8104 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008105 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008106 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008107 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008108 case AUDIO_USAGE_EMERGENCY:
8109 case AUDIO_USAGE_SAFETY:
8110 case AUDIO_USAGE_VEHICLE_STATUS:
8111 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008112 break;
8113 default:
8114 return false;
8115 }
8116 return true;
8117}
8118
François Gaffie2110e042015-03-24 08:41:51 +01008119audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8120{
8121 return mEngine->getForceUse(usage);
8122}
8123
Eric Laurent96d1dda2022-03-14 17:14:19 +01008124bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008125 return isStateInCall(mEngine->getPhoneState());
8126}
8127
Eric Laurent96d1dda2022-03-14 17:14:19 +01008128bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008129 return is_state_in_call(state);
8130}
8131
Eric Laurentf9cccec2022-11-16 19:12:00 +01008132bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008133 audio_mode_t mode = mEngine->getPhoneState();
8134 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008135 || (mode == AUDIO_MODE_CALL_SCREEN)
8136 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008137}
8138
Eric Laurentf9cccec2022-11-16 19:12:00 +01008139bool AudioPolicyManager::isInCallOrScreening() const {
8140 audio_mode_t mode = mEngine->getPhoneState();
8141 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8142}
8143
Eric Laurentd60560a2015-04-10 11:31:20 -07008144void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8145{
8146 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008147 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008148 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008149 sourceDesc->sinkDevice()->equals(deviceDesc))
8150 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008151 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008152 }
8153 }
8154
8155 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8156 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8157 bool release = false;
8158 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8159 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8160 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8161 source->ext.device.type == deviceDesc->type()) {
8162 release = true;
8163 }
8164 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008165 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008166 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8167 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8168 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008169 sink->ext.device.type == deviceDesc->type() &&
8170 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8171 || strncmp(sink->ext.device.address, address,
8172 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008173 release = true;
8174 }
8175 }
8176 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008177 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8178 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008179 }
8180 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008181
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008182 mInputs.clearSessionRoutesForDevice(deviceDesc);
8183
Francois Gaffie716e1432019-01-14 16:58:59 +01008184 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008185}
8186
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008187void AudioPolicyManager::modifySurroundFormats(
8188 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008189 std::unordered_set<audio_format_t> enforcedSurround(
8190 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008191 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008192 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008193 allSurround.insert(pair.first);
8194 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8195 }
Phil Burk09bc4612016-02-24 15:58:15 -08008196
8197 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8198 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008199 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008200 // This is the resulting set of formats depending on the surround mode:
8201 // 'all surround' = allSurround
8202 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8203 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8204 // 'manual surround' = mManualSurroundFormats
8205 // AUTO: formats v 'enforced surround'
8206 // ALWAYS: formats v 'all surround' v 'enforced surround'
8207 // NEVER: formats ^ 'non-surround'
8208 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008209
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008210 std::unordered_set<audio_format_t> formatSet;
8211 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8212 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008213 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008214 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008215 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008216 formatSet.insert(*formatIter);
8217 }
8218 }
8219 } else {
8220 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8221 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008222 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008223
jiabin81772902018-04-02 17:52:27 -07008224 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008225 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008226 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8227 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8228 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008229 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008230 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8231 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8232 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008233 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008234 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008235 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008236 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008237 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008238 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008239}
8240
jiabin06e4bab2019-07-29 10:13:34 -07008241void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8242 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008243 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8244 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8245
8246 // If NEVER, then remove support for channelMasks > stereo.
8247 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008248 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8249 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008250 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008251 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008252 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008253 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008254 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008255 }
8256 }
jiabin81772902018-04-02 17:52:27 -07008257 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8258 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8259 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008260 bool supports5dot1 = false;
8261 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008262 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008263 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8264 supports5dot1 = true;
8265 break;
8266 }
8267 }
8268 // If not then add 5.1 support.
8269 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008270 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008271 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008272 }
Phil Burk09bc4612016-02-24 15:58:15 -08008273 }
8274}
8275
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008276void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008277 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008278 const sp<IOProfile>& profile) {
8279 if (!profile->hasDynamicAudioProfile()) {
8280 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008281 }
François Gaffie112b0af2015-11-19 16:13:25 +01008282
jiabin12537fc2023-10-12 17:56:08 +00008283 audio_port_v7 devicePort;
8284 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008285
jiabin12537fc2023-10-12 17:56:08 +00008286 audio_port_v7 mixPort;
8287 profile->toAudioPort(&mixPort);
8288 mixPort.ext.mix.handle = ioHandle;
8289
8290 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8291 if (status != NO_ERROR) {
8292 ALOGE("%s failed to query the attributes of the mix port", __func__);
8293 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008294 }
jiabin12537fc2023-10-12 17:56:08 +00008295
8296 std::set<audio_format_t> supportedFormats;
8297 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8298 supportedFormats.insert(mixPort.audio_profiles[i].format);
8299 }
8300 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8301 mReportedFormatsMap[devDesc] = formats;
8302
8303 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8304 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8305 modifySurroundFormats(devDesc, &formats);
8306 size_t modifiedNumProfiles = 0;
8307 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8308 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8309 formats.end()) {
8310 // Skip the format that is not present after modifying surround formats.
8311 continue;
8312 }
8313 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8314 sizeof(struct audio_profile));
8315 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8316 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8317 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8318 modifySurroundChannelMasks(&channels);
8319 std::copy(channels.begin(), channels.end(),
8320 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8321 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8322 }
8323 mixPort.num_audio_profiles = modifiedNumProfiles;
8324 }
8325 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008326}
Eric Laurentd60560a2015-04-10 11:31:20 -07008327
Mikhail Naganovdc769682018-05-04 15:34:08 -07008328status_t AudioPolicyManager::installPatch(const char *caller,
8329 audio_patch_handle_t *patchHandle,
8330 AudioIODescriptorInterface *ioDescriptor,
8331 const struct audio_patch *patch,
8332 int delayMs)
8333{
8334 ssize_t index = mAudioPatches.indexOfKey(
8335 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8336 *patchHandle : ioDescriptor->getPatchHandle());
8337 sp<AudioPatch> patchDesc;
8338 status_t status = installPatch(
8339 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8340 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008341 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008342 }
8343 return status;
8344}
8345
8346status_t AudioPolicyManager::installPatch(const char *caller,
8347 ssize_t index,
8348 audio_patch_handle_t *patchHandle,
8349 const struct audio_patch *patch,
8350 int delayMs,
8351 uid_t uid,
8352 sp<AudioPatch> *patchDescPtr)
8353{
8354 sp<AudioPatch> patchDesc;
8355 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8356 if (index >= 0) {
8357 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008358 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008359 }
8360
8361 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8362 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8363 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8364 if (status == NO_ERROR) {
8365 if (index < 0) {
8366 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008367 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008368 } else {
8369 patchDesc->mPatch = *patch;
8370 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008371 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008372 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008373 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008374 }
8375 nextAudioPortGeneration();
8376 mpClientInterface->onAudioPatchListUpdate();
8377 }
8378 if (patchDescPtr) *patchDescPtr = patchDesc;
8379 return status;
8380}
8381
jiabinbce0c1d2020-10-05 11:20:18 -07008382bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8383{
8384 const TrackClientVector activeClients = output->getActiveClients();
8385 if (activeClients.empty()) {
8386 return true;
8387 }
8388 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8389 if (index < 0) {
8390 ALOGE("%s, no audio patch found while there are active clients on output %d",
8391 __func__, output->getId());
8392 return false;
8393 }
8394 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8395 DeviceVector routedDevices;
8396 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8397 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8398 patchDesc->mPatch.sinks[i].id);
8399 if (device == nullptr) {
8400 ALOGE("%s, no audio device found with id(%d)",
8401 __func__, patchDesc->mPatch.sinks[i].id);
8402 return false;
8403 }
8404 routedDevices.add(device);
8405 }
8406 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008407 if (client->isInvalid()) {
8408 // No need to take care about invalidated clients.
8409 continue;
8410 }
jiabinbce0c1d2020-10-05 11:20:18 -07008411 sp<DeviceDescriptor> preferredDevice =
8412 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8413 if (mEngine->getOutputDevicesForAttributes(
8414 client->attributes(), preferredDevice, false) == routedDevices) {
8415 return false;
8416 }
8417 }
8418 return true;
8419}
8420
8421sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008422 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008423 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8424 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008425{
8426 for (const auto& device : devices) {
8427 // TODO: This should be checking if the profile supports the device combo.
8428 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008429 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8430 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008431 return nullptr;
8432 }
8433 }
8434 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8435 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008436 status_t status = desc->open(halConfig, mixerConfig, devices,
8437 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008438 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008439 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008440 return nullptr;
8441 }
jiabin14b50cc2023-12-13 19:01:52 +00008442 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8443 auto portConfig = desc->getConfig();
8444 for (const auto& device : devices) {
8445 device->setPreferredConfig(&portConfig);
8446 }
8447 }
jiabinbce0c1d2020-10-05 11:20:18 -07008448
8449 // Here is where the out_set_parameters() for card & device gets called
8450 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8451 const audio_devices_t deviceType = device->type();
8452 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008453 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008454 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8455 mpClientInterface->setParameters(output, String8(param));
8456 free(param);
8457 }
jiabin12537fc2023-10-12 17:56:08 +00008458 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008459 if (!profile->hasValidAudioProfile()) {
8460 ALOGW("%s() missing param", __func__);
8461 desc->close();
8462 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008463 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8464 // Reopen the output with the best audio profile picked by APM when the profile supports
8465 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008466 desc->close();
8467 output = AUDIO_IO_HANDLE_NONE;
8468 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8469 profile->pickAudioProfile(
8470 config.sample_rate, config.channel_mask, config.format);
8471 config.offload_info.sample_rate = config.sample_rate;
8472 config.offload_info.channel_mask = config.channel_mask;
8473 config.offload_info.format = config.format;
8474
jiabina84c3d32022-12-02 18:59:55 +00008475 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008476 if (status != NO_ERROR) {
8477 return nullptr;
8478 }
8479 }
8480
8481 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008482
baek.kim -61c20122022-07-27 10:05:32 +00008483 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8484 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8485
jiabinbce0c1d2020-10-05 11:20:18 -07008486 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8487 sp<AudioPolicyMix> policyMix;
8488 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8489 policyMix->setOutput(desc);
8490 desc->mPolicyMix = policyMix;
8491 } else {
8492 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008493 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008494 }
8495
baek.kim -61c20122022-07-27 10:05:32 +00008496 } else if (hasPrimaryOutput() && speaker != nullptr
8497 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008498 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8499 // no duplicated output for:
8500 // - direct outputs
8501 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008502 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008503 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8504
8505 //TODO: configure audio effect output stage here
8506
8507 // open a duplicating output thread for the new output and the primary output
8508 sp<SwAudioOutputDescriptor> dupOutputDesc =
8509 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8510 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8511 if (status == NO_ERROR) {
8512 // add duplicated output descriptor
8513 addOutput(duplicatedOutput, dupOutputDesc);
8514 } else {
8515 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8516 mPrimaryOutput->mIoHandle, output);
8517 desc->close();
8518 removeOutput(output);
8519 nextAudioPortGeneration();
8520 return nullptr;
8521 }
8522 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008523 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8524 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8525 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008526 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008527 }
jiabinbce0c1d2020-10-05 11:20:18 -07008528 return desc;
8529}
8530
jiabinf1c73972022-04-14 16:28:52 -07008531status_t AudioPolicyManager::getDevicesForAttributes(
8532 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8533 // Devices are determined in the following precedence:
8534 //
8535 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8536 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8537 //
8538 // If no such dynamic policy then
8539 // 2) Devices containing an active client using setPreferredDevice
8540 // with same strategy as the attributes.
8541 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8542 //
8543 // If no corresponding active client with setPreferredDevice then
8544 // 3) Devices associated with the strategy determined by the attributes
8545 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8546 //
8547 // See related getOutputForAttrInt().
8548
8549 // check dynamic policies but only for primary descriptors (secondary not used for audible
8550 // audio routing, only used for duplication for playback capture)
8551 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008552 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008553 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008554 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8555 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8556 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008557 if (status != OK) {
8558 return status;
8559 }
8560
8561 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8562 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8563 // as they are unaffected by device/stream volume
8564 // (per SwAudioOutputDescriptor::isFixedVolume()).
8565 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8566 ) {
8567 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8568 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8569 devices.add(deviceDesc);
8570 } else {
8571 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8572 // which selects setPreferredDevice if active. This means forVolume call
8573 // will take an active setPreferredDevice, if such exists.
8574
8575 devices = mEngine->getOutputDevicesForAttributes(
8576 attr, nullptr /* preferredDevice */, false /* fromCache */);
8577 }
8578
8579 if (forVolume) {
8580 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8581 // for single volume control in AudioService (such relationship should exist if
8582 // SPEAKER_SAFE is present).
8583 //
8584 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8585 DeviceVector speakerSafeDevices =
8586 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8587 if (!speakerSafeDevices.isEmpty()) {
8588 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8589 devices.remove(speakerSafeDevices);
8590 }
8591 }
8592
8593 return NO_ERROR;
8594}
8595
8596status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8597 AudioProfileVector& audioProfiles,
8598 uint32_t flags,
8599 bool isInput) {
8600 for (const auto& hwModule : mHwModules) {
8601 // the MSD module checks for different conditions
8602 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8603 continue;
8604 }
8605 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8606 : hwModule->getOutputProfiles();
8607 for (const auto& profile : ioProfiles) {
8608 if (!profile->areAllDevicesSupported(devices) ||
8609 !profile->isCompatibleProfileForFlags(
8610 flags, false /*exactMatchRequiredForInputFlags*/)) {
8611 continue;
8612 }
8613 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8614 }
8615 }
8616
8617 if (!isInput) {
8618 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8619 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8620 if (msdModule != nullptr) {
8621 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8622 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8623 for (const auto &profile: msdModule->getOutputProfiles()) {
8624 if (!profile->asAudioPort()->isDirectOutput()) {
8625 continue;
8626 }
8627 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8628 }
8629 } else {
8630 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8631 }
8632 }
8633 }
8634
8635 return NO_ERROR;
8636}
8637
jiabin3ff8d7d2022-12-13 06:27:44 +00008638sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8639 const audio_config_t *config,
8640 audio_output_flags_t flags,
8641 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008642 closeOutput(outputDesc->mIoHandle);
8643 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8644 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8645 if (preferredOutput == nullptr) {
8646 ALOGE("%s failed to reopen output device=%d, caller=%s",
8647 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008648 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008649 return preferredOutput;
8650}
8651
8652void AudioPolicyManager::reopenOutputsWithDevices(
8653 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8654 for (const auto& [output, devices] : outputsToReopen) {
8655 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8656 closeOutput(output);
8657 openOutputWithProfileAndDevice(desc->mProfile, devices);
8658 }
jiabina84c3d32022-12-02 18:59:55 +00008659}
8660
jiabinc44b3462022-12-08 12:52:31 -08008661PortHandleVector AudioPolicyManager::getClientsForStream(
8662 audio_stream_type_t streamType) const {
8663 PortHandleVector clients;
8664 for (size_t i = 0; i < mOutputs.size(); ++i) {
8665 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8666 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8667 }
8668 return clients;
8669}
8670
8671void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8672 PortHandleVector clients;
8673 for (auto stream : streams) {
8674 PortHandleVector clientsForStream = getClientsForStream(stream);
8675 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8676 }
8677 mpClientInterface->invalidateTracks(clients);
8678}
8679
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008680} // namespace android