blob: 47146235b93ba6ee567471e31c1d13d77633a6db [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()) {
jiabin66acc432024-02-06 00:57:36 +00001053 if (curProfile->getCompatibilityScore(devices,
Dorin Drimusecc9f422022-03-09 17:57:40 +01001054 samplingRate, NULL /*updatedSamplingRate*/,
1055 format, NULL /*updatedFormat*/,
1056 channelMask, NULL /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00001057 flags) == IOProfile::NO_MATCH) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001058 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()) {
jiabin66acc432024-02-06 00:57:36 +00004489 if (curProfile->getCompatibilityScore(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004490 config->sample_rate, nullptr /*updatedSamplingRate*/,
4491 config->format, nullptr /*updatedFormat*/,
4492 config->channel_mask, nullptr /*updatedChannelMask*/,
jiabin66acc432024-02-06 00:57:36 +00004493 flags) == IOProfile::NO_MATCH) {
jiabin2b9d5a12021-12-10 01:06:29 +00004494 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()
jiabin66acc432024-02-06 00:57:36 +00004599 && curProfile->getCompatibilityScore(
4600 devices,
4601 mixerAttributes->config.sample_rate,
4602 nullptr /*updatedSamplingRate*/,
4603 mixerAttributes->config.format,
4604 nullptr /*updatedFormat*/,
4605 mixerAttributes->config.channel_mask,
4606 nullptr /*updatedChannelMask*/,
4607 flags,
4608 false /*exactMatchRequiredForInputFlags*/)
4609 != IOProfile::NO_MATCH) {
jiabina84c3d32022-12-02 18:59:55 +00004610 profile = curProfile;
4611 break;
4612 }
4613 }
4614 }
4615 if (profile == nullptr) {
4616 ALOGE("%s, there is no compatible profile found", __func__);
4617 return BAD_VALUE;
4618 }
4619
4620 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4621 sp<PreferredMixerAttributesInfo>::make(
4622 uid, portId, profile, flags, *mixerAttributes);
4623 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4624 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4625
4626 // If 1) there is any client from the preferred mixer configuration owner that is currently
4627 // active and matches the strategy and 2) current output is on the preferred device and the
4628 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4629 // configuration.
4630 std::vector<audio_io_handle_t> outputsToReopen;
4631 for (size_t i = 0; i < mOutputs.size(); i++) {
4632 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004633 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4634 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4635 output->mUsePreferredMixerAttributes = true;
4636 } else {
4637 for (const auto &client: output->getActiveClients()) {
4638 if (client->uid() == uid && client->strategy() == strategy) {
4639 client->setIsInvalid();
4640 outputsToReopen.push_back(output->mIoHandle);
4641 }
jiabina84c3d32022-12-02 18:59:55 +00004642 }
4643 }
4644 }
4645 }
4646 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4647 config.sample_rate = mixerAttributes->config.sample_rate;
4648 config.channel_mask = mixerAttributes->config.channel_mask;
4649 config.format = mixerAttributes->config.format;
4650 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004651 sp<SwAudioOutputDescriptor> desc =
4652 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4653 if (desc == nullptr) {
4654 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4655 continue;
4656 }
4657 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004658 }
4659
4660 return NO_ERROR;
4661}
4662
4663sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004664 audio_port_handle_t devicePortId,
4665 product_strategy_t strategy,
4666 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004667 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4668 if (it == mPreferredMixerAttrInfos.end()) {
4669 return nullptr;
4670 }
jiabind9a58d32023-06-01 17:57:30 +00004671 if (activeBitPerfectPreferred) {
4672 for (auto [strategy, info] : it->second) {
4673 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4674 && info->getActiveClientCount() != 0) {
4675 return info;
4676 }
4677 }
jiabina84c3d32022-12-02 18:59:55 +00004678 }
jiabind9a58d32023-06-01 17:57:30 +00004679 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4680 return strategyMatchedMixerAttrInfoIt == it->second.end()
4681 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004682}
4683
4684status_t AudioPolicyManager::getPreferredMixerAttributes(
4685 const audio_attributes_t *attr,
4686 audio_port_handle_t portId,
4687 audio_mixer_attributes_t* mixerAttributes) {
4688 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4689 portId, mEngine->getProductStrategyForAttributes(*attr));
4690 if (info == nullptr) {
4691 return NAME_NOT_FOUND;
4692 }
4693 *mixerAttributes = info->getMixerAttributes();
4694 return NO_ERROR;
4695}
4696
4697status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4698 audio_port_handle_t portId,
4699 uid_t uid) {
4700 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4701 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4702 if (preferredMixerAttrInfo == nullptr) {
4703 return NAME_NOT_FOUND;
4704 }
4705 if (preferredMixerAttrInfo->getUid() != uid) {
4706 ALOGE("%s, requested uid=%d, owned uid=%d",
4707 __func__, uid, preferredMixerAttrInfo->getUid());
4708 return PERMISSION_DENIED;
4709 }
4710 mPreferredMixerAttrInfos[portId].erase(strategy);
4711 if (mPreferredMixerAttrInfos[portId].empty()) {
4712 mPreferredMixerAttrInfos.erase(portId);
4713 }
4714
4715 // Reconfig existing output
4716 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4717 for (size_t i = 0; i < mOutputs.size(); i++) {
4718 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4719 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4720 }
4721 }
4722 for (const auto output : potentialOutputsToReopen) {
4723 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4724 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4725 preferredMixerAttrInfo->getFlags())) {
4726 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4727 }
4728 }
4729 return NO_ERROR;
4730}
4731
Eric Laurent6a94d692014-05-20 11:18:06 -07004732status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4733 audio_port_type_t type,
4734 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004735 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004736 unsigned int *generation)
4737{
jiabin19cdba52020-11-24 11:28:58 -08004738 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4739 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004740 return BAD_VALUE;
4741 }
4742 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004743 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004744 *num_ports = 0;
4745 }
4746
4747 size_t portsWritten = 0;
4748 size_t portsMax = *num_ports;
4749 *num_ports = 0;
4750 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004751 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4752 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004753 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004754 for (const auto& dev : mAvailableOutputDevices) {
4755 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004756 continue;
4757 }
4758 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004759 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004760 }
4761 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004762 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004763 }
4764 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004765 for (const auto& dev : mAvailableInputDevices) {
4766 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004767 continue;
4768 }
4769 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004770 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004771 }
4772 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004773 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004774 }
4775 }
4776 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4777 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4778 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4779 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4780 }
4781 *num_ports += mInputs.size();
4782 }
4783 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004784 size_t numOutputs = 0;
4785 for (size_t i = 0; i < mOutputs.size(); i++) {
4786 if (!mOutputs[i]->isDuplicated()) {
4787 numOutputs++;
4788 if (portsWritten < portsMax) {
4789 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4790 }
4791 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004792 }
Eric Laurent84c70242014-06-23 08:46:27 -07004793 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004794 }
4795 }
jiabina84c3d32022-12-02 18:59:55 +00004796
Eric Laurent6a94d692014-05-20 11:18:06 -07004797 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004798 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004799 return NO_ERROR;
4800}
4801
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004802status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4803 std::vector<media::AudioPortFw>* _aidl_return) {
4804 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4805 audio_port_v7 port;
4806 dev->toAudioPort(&port);
4807 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4808 _aidl_return->push_back(std::move(aidlPort));
4809 return OK;
4810 };
4811
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004812 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004813 for (const auto& dev : module->getDeclaredDevices()) {
4814 if (role == media::AudioPortRole::NONE ||
4815 ((role == media::AudioPortRole::SOURCE)
4816 == audio_is_input_device(dev->type()))) {
4817 RETURN_STATUS_IF_ERROR(pushPort(dev));
4818 }
4819 }
4820 }
4821 return OK;
4822}
4823
jiabin19cdba52020-11-24 11:28:58 -08004824status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004825{
Eric Laurent99fcae42018-05-17 16:59:18 -07004826 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4827 return BAD_VALUE;
4828 }
4829 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4830 if (dev != 0) {
4831 dev->toAudioPort(port);
4832 return NO_ERROR;
4833 }
4834 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4835 if (dev != 0) {
4836 dev->toAudioPort(port);
4837 return NO_ERROR;
4838 }
4839 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4840 if (out != 0) {
4841 out->toAudioPort(port);
4842 return NO_ERROR;
4843 }
4844 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4845 if (in != 0) {
4846 in->toAudioPort(port);
4847 return NO_ERROR;
4848 }
4849 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004850}
4851
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004852status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4853 audio_patch_handle_t *handle,
4854 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004855{
François Gaffieafd4cea2019-11-18 15:50:22 +01004856 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004857 if (handle == NULL || patch == NULL) {
4858 return BAD_VALUE;
4859 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004860 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004861 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004862 return BAD_VALUE;
4863 }
4864 // only one source per audio patch supported for now
4865 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004866 return INVALID_OPERATION;
4867 }
Eric Laurent874c42872014-08-08 15:13:39 -07004868 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004869 return INVALID_OPERATION;
4870 }
Eric Laurent874c42872014-08-08 15:13:39 -07004871 for (size_t i = 0; i < patch->num_sinks; i++) {
4872 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4873 return INVALID_OPERATION;
4874 }
4875 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004876
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004877 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4878 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4879 if (srcDevice == nullptr || sinkDevice == nullptr) {
4880 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4881 return BAD_VALUE;
4882 }
4883 ALOGV("%s between source %s and sink %s", __func__,
4884 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4885 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4886 // Default attributes, default volume priority, not to infer with non raw audio patches.
4887 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4888 const struct audio_port_config *source = &patch->sources[0];
4889 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004890 new SourceClientDescriptor(
4891 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4892 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4893 true);
4894 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004895
4896 status_t status =
4897 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4898
4899 if (status != NO_ERROR) {
4900 return INVALID_OPERATION;
4901 }
4902 mAudioSources.add(portId, sourceDesc);
4903 return NO_ERROR;
4904}
4905
4906status_t AudioPolicyManager::connectAudioSourceToSink(
4907 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4908 const struct audio_patch *patch,
4909 audio_patch_handle_t &handle,
4910 uid_t uid, uint32_t delayMs)
4911{
4912 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4913 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4914 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4915 return INVALID_OPERATION;
4916 }
4917 sourceDesc->connect(handle, sinkDevice);
4918 if (isMsdPatch(handle)) {
4919 return NO_ERROR;
4920 }
4921 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4922 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4923 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4924 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4925 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4926 goto FailurePatchAdded;
4927 }
4928 status = swOutput->start();
4929 if (status != NO_ERROR) {
4930 goto FailureSourceAdded;
4931 }
4932 swOutput->addClient(sourceDesc);
4933 status = startSource(swOutput, sourceDesc, &delayMs);
4934 if (status != NO_ERROR) {
4935 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4936 goto FailureSourceActive;
4937 }
4938 if (delayMs != 0) {
4939 usleep(delayMs * 1000);
4940 }
4941 return NO_ERROR;
4942
4943FailureSourceActive:
4944 swOutput->stop();
4945 releaseOutput(sourceDesc->portId());
4946FailureSourceAdded:
4947 sourceDesc->setSwOutput(nullptr);
4948FailurePatchAdded:
4949 releaseAudioPatchInternal(handle);
4950 return INVALID_OPERATION;
4951}
4952
4953status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4954 audio_patch_handle_t *handle,
4955 uid_t uid, uint32_t delayMs,
4956 const sp<SourceClientDescriptor>& sourceDesc)
4957{
4958 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004959 sp<AudioPatch> patchDesc;
4960 ssize_t index = mAudioPatches.indexOfKey(*handle);
4961
François Gaffieafd4cea2019-11-18 15:50:22 +01004962 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4963 patch->sources[0].role,
4964 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004965#if LOG_NDEBUG == 0
4966 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004967 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4968 patch->sinks[i].role,
4969 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004970 }
4971#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004972
4973 if (index >= 0) {
4974 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004975 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4976 __func__, mUidCached, patchDesc->getUid(), uid);
4977 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004978 return INVALID_OPERATION;
4979 }
4980 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004981 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004982 }
4983
4984 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004985 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004986 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004987 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004988 return BAD_VALUE;
4989 }
Eric Laurent84c70242014-06-23 08:46:27 -07004990 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4991 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004992 if (patchDesc != 0) {
4993 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004994 ALOGV("%s source id differs for patch current id %d new id %d",
4995 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004996 return BAD_VALUE;
4997 }
4998 }
Eric Laurent874c42872014-08-08 15:13:39 -07004999 DeviceVector devices;
5000 for (size_t i = 0; i < patch->num_sinks; i++) {
5001 // Only support mix to devices connection
5002 // TODO add support for mix to mix connection
5003 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005004 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005005 return INVALID_OPERATION;
5006 }
5007 sp<DeviceDescriptor> devDesc =
5008 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5009 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005010 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005011 return BAD_VALUE;
5012 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005013
jiabin66acc432024-02-06 00:57:36 +00005014 if (outputDesc->mProfile->getCompatibilityScore(
5015 DeviceVector(devDesc),
5016 patch->sources[0].sample_rate,
5017 nullptr, // updatedSamplingRate
5018 patch->sources[0].format,
5019 nullptr, // updatedFormat
5020 patch->sources[0].channel_mask,
5021 nullptr, // updatedChannelMask
5022 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/) == IOProfile::NO_MATCH) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005023 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005024 return INVALID_OPERATION;
5025 }
5026 devices.add(devDesc);
5027 }
5028 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005029 return INVALID_OPERATION;
5030 }
Eric Laurent874c42872014-08-08 15:13:39 -07005031
Eric Laurent6a94d692014-05-20 11:18:06 -07005032 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005033 ALOGV("%s setting device %s on output %d",
5034 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305035 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005036 index = mAudioPatches.indexOfKey(*handle);
5037 if (index >= 0) {
5038 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005039 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005040 }
5041 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005042 patchDesc->setUid(uid);
5043 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005044 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005045 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005046 return INVALID_OPERATION;
5047 }
5048 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5049 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5050 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005051 // only one sink supported when connecting an input device to a mix
5052 if (patch->num_sinks > 1) {
5053 return INVALID_OPERATION;
5054 }
François Gaffie53615e22015-03-19 09:24:12 +01005055 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005056 if (inputDesc == NULL) {
5057 return BAD_VALUE;
5058 }
5059 if (patchDesc != 0) {
5060 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5061 return BAD_VALUE;
5062 }
5063 }
François Gaffie11d30102018-11-02 16:09:09 +01005064 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005065 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005066 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005067 return BAD_VALUE;
5068 }
5069
jiabin66acc432024-02-06 00:57:36 +00005070 if (inputDesc->mProfile->getCompatibilityScore(
5071 DeviceVector(device),
5072 patch->sinks[0].sample_rate,
5073 nullptr, /*updatedSampleRate*/
5074 patch->sinks[0].format,
5075 nullptr, /*updatedFormat*/
5076 patch->sinks[0].channel_mask,
5077 nullptr, /*updatedChannelMask*/
5078 // FIXME for the parameter type,
5079 // and the NONE
5080 (audio_output_flags_t)
5081 AUDIO_INPUT_FLAG_NONE) == IOProfile::NO_MATCH) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005082 return INVALID_OPERATION;
5083 }
5084 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005085 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005086 device->toString().c_str(), inputDesc->mIoHandle);
5087 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005088 index = mAudioPatches.indexOfKey(*handle);
5089 if (index >= 0) {
5090 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005091 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005092 }
5093 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005094 patchDesc->setUid(uid);
5095 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005096 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005097 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005098 return INVALID_OPERATION;
5099 }
5100 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5101 // device to device connection
5102 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005103 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005104 return BAD_VALUE;
5105 }
5106 }
François Gaffie11d30102018-11-02 16:09:09 +01005107 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005108 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005109 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005110 return BAD_VALUE;
5111 }
Eric Laurent874c42872014-08-08 15:13:39 -07005112
Eric Laurent6a94d692014-05-20 11:18:06 -07005113 //update source and sink with our own data as the data passed in the patch may
5114 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005115 PatchBuilder patchBuilder;
5116 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005117
5118 // if first sink is to MSD, establish single MSD patch
5119 if (getMsdAudioOutDevices().contains(
5120 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5121 ALOGV("%s patching to MSD", __FUNCTION__);
5122 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5123 goto installPatch;
5124 }
5125
François Gaffieafd4cea2019-11-18 15:50:22 +01005126 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5127 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005128
Eric Laurent874c42872014-08-08 15:13:39 -07005129 for (size_t i = 0; i < patch->num_sinks; i++) {
5130 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005131 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005132 return INVALID_OPERATION;
5133 }
François Gaffie11d30102018-11-02 16:09:09 +01005134 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005135 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005136 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005137 return BAD_VALUE;
5138 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005139 audio_port_config sinkPortConfig = {};
5140 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5141 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005142
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005143 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5144 // volume management purpose (tracking activity)
5145 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5146 // in config XML to reach the sink so that is can be declared as available.
5147 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005148 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005149 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005150 // take care of dynamic routing for SwOutput selection,
5151 audio_attributes_t attributes = sourceDesc->attributes();
5152 audio_stream_type_t stream = sourceDesc->stream();
5153 audio_attributes_t resultAttr;
5154 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5155 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005156 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5157 config.channel_mask =
5158 (audio_channel_mask_get_representation(sourceMask)
5159 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5160 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005161 config.format = sourceDesc->config().format;
5162 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5163 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5164 bool isRequestedDeviceForExclusiveUse = false;
5165 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005166 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005167 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005168 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5169 &stream, sourceDesc->uid(), &config, &flags,
5170 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005171 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005172 if (output == AUDIO_IO_HANDLE_NONE) {
5173 ALOGV("%s no output for device %s",
5174 __FUNCTION__, sinkDevice->toString().c_str());
5175 return INVALID_OPERATION;
5176 }
5177 outputDesc = mOutputs.valueFor(output);
5178 if (outputDesc->isDuplicated()) {
5179 ALOGE("%s output is duplicated", __func__);
5180 return INVALID_OPERATION;
5181 }
François Gaffie7e39df22022-04-26 12:48:49 +02005182 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5183 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005184 } else {
5185 // Same for "raw patches" aka created from createAudioPatch API
5186 SortedVector<audio_io_handle_t> outputs =
5187 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5188 // if the sink device is reachable via an opened output stream, request to
5189 // go via this output stream by adding a second source to the patch
5190 // description
5191 output = selectOutput(outputs);
5192 if (output == AUDIO_IO_HANDLE_NONE) {
5193 ALOGE("%s no output available for internal patch sink", __func__);
5194 return INVALID_OPERATION;
5195 }
5196 outputDesc = mOutputs.valueFor(output);
5197 if (outputDesc->isDuplicated()) {
5198 ALOGV("%s output for device %s is duplicated",
5199 __func__, sinkDevice->toString().c_str());
5200 return INVALID_OPERATION;
5201 }
François Gaffie7e39df22022-04-26 12:48:49 +02005202 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005203 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005204 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005205 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005206 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005207 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005208 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5209 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005210 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5211 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005212 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005213 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005214 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005215 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005216 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005217 return INVALID_OPERATION;
5218 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005219 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005220 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005221 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005222 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005223 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005224 srcMixPortConfig.ext.mix.usecase.stream =
5225 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005226 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5227 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005228 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005229 }
Eric Laurent83b88082014-06-20 18:31:16 -07005230 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005231 }
5232 // TODO: check from routing capabilities in config file and other conflicting patches
5233
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005234installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005235 status_t status = installPatch(
5236 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005237 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005238 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005239 return INVALID_OPERATION;
5240 }
5241 } else {
5242 return BAD_VALUE;
5243 }
5244 } else {
5245 return BAD_VALUE;
5246 }
5247 return NO_ERROR;
5248}
5249
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005250status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005251{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005252 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005253 ssize_t index = mAudioPatches.indexOfKey(handle);
5254
5255 if (index < 0) {
5256 return BAD_VALUE;
5257 }
5258 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005259 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5260 __func__, mUidCached, patchDesc->getUid(), uid);
5261 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005262 return INVALID_OPERATION;
5263 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005264 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5265 for (size_t i = 0; i < mAudioSources.size(); i++) {
5266 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5267 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5268 portId = sourceDesc->portId();
5269 break;
5270 }
5271 }
5272 return portId != AUDIO_PORT_HANDLE_NONE ?
5273 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005274}
Eric Laurent6a94d692014-05-20 11:18:06 -07005275
François Gaffieafd4cea2019-11-18 15:50:22 +01005276status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005277 uint32_t delayMs,
5278 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005279{
5280 ALOGV("%s patch %d", __func__, handle);
5281 if (mAudioPatches.indexOfKey(handle) < 0) {
5282 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5283 return BAD_VALUE;
5284 }
5285 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005286 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005287 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005289 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005290 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005291 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 return BAD_VALUE;
5293 }
5294
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305295 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005296 getNewOutputDevices(outputDesc, true /*fromCache*/),
5297 true,
5298 0,
5299 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5301 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005302 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005303 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005304 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005305 return BAD_VALUE;
5306 }
5307 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005308 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005309 true,
5310 NULL);
5311 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005312 status_t status =
5313 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5314 ALOGV("%s patch panel returned %d patchHandle %d",
5315 __func__, status, patchDesc->getAfHandle());
5316 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005317 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005318 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005319 // SW or HW Bridge
5320 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5321 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005322 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005323 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5324 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5325 outputDesc = sourceDesc->swOutput().promote();
5326 }
5327 if (outputDesc == nullptr) {
5328 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5329 // releaseOutput has already called closeOutput in case of direct output
5330 return NO_ERROR;
5331 }
François Gaffie7e39df22022-04-26 12:48:49 +02005332 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005333 // While using a HwBridge, force reconsidering device only if not reusing an existing
5334 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005335 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005336 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5337 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5338 // Reconsider device only for cases:
5339 // 1 / Active Output
5340 // 2 / Inactive Output previously hosting HwBridge
5341 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5342 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5343 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305344 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005345 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5346 outputDesc->devices(),
5347 force,
5348 0,
5349 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005350 } else {
5351 return BAD_VALUE;
5352 }
5353 } else {
5354 return BAD_VALUE;
5355 }
5356 return NO_ERROR;
5357}
5358
5359status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5360 struct audio_patch *patches,
5361 unsigned int *generation)
5362{
François Gaffie53615e22015-03-19 09:24:12 +01005363 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005364 return BAD_VALUE;
5365 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005366 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005367 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005368}
5369
Eric Laurente1715a42014-05-20 11:30:42 -07005370status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005371{
Eric Laurente1715a42014-05-20 11:30:42 -07005372 ALOGV("setAudioPortConfig()");
5373
5374 if (config == NULL) {
5375 return BAD_VALUE;
5376 }
5377 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5378 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005379 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5380 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005381 }
5382
Eric Laurenta121f902014-06-03 13:32:54 -07005383 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005384 if (config->type == AUDIO_PORT_TYPE_MIX) {
5385 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005386 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005387 if (outputDesc == NULL) {
5388 return BAD_VALUE;
5389 }
Eric Laurent84c70242014-06-23 08:46:27 -07005390 ALOG_ASSERT(!outputDesc->isDuplicated(),
5391 "setAudioPortConfig() called on duplicated output %d",
5392 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005393 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005394 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005395 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005396 if (inputDesc == NULL) {
5397 return BAD_VALUE;
5398 }
Eric Laurenta121f902014-06-03 13:32:54 -07005399 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005400 } else {
5401 return BAD_VALUE;
5402 }
5403 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5404 sp<DeviceDescriptor> deviceDesc;
5405 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5406 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5407 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5408 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5409 } else {
5410 return BAD_VALUE;
5411 }
5412 if (deviceDesc == NULL) {
5413 return BAD_VALUE;
5414 }
Eric Laurenta121f902014-06-03 13:32:54 -07005415 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005416 } else {
5417 return BAD_VALUE;
5418 }
5419
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005420 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005421 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5422 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005423 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005424 audioPortConfig->toAudioPortConfig(&newConfig, config);
5425 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005426 }
Eric Laurenta121f902014-06-03 13:32:54 -07005427 if (status != NO_ERROR) {
5428 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005429 }
Eric Laurente1715a42014-05-20 11:30:42 -07005430
5431 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005432}
5433
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005434void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5435{
Eric Laurentd60560a2015-04-10 11:31:20 -07005436 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005437 clearAudioPatches(uid);
5438 clearSessionRoutes(uid);
5439}
5440
Eric Laurent6a94d692014-05-20 11:18:06 -07005441void AudioPolicyManager::clearAudioPatches(uid_t uid)
5442{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005443 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005444 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005445 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005446 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005447 }
5448 }
5449}
5450
François Gaffiec005e562018-11-06 15:04:49 +01005451void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005452{
François Gaffiec005e562018-11-06 15:04:49 +01005453 // Take the first attributes following the product strategy as it is used to retrieve the routed
5454 // device. All attributes wihin a strategy follows the same "routing strategy"
5455 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5456 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005457 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005458 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005459 for (size_t j = 0; j < mOutputs.size(); j++) {
5460 if (mOutputs.keyAt(j) == ouptutToSkip) {
5461 continue;
5462 }
5463 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005464 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005465 continue;
5466 }
5467 // If the default device for this strategy is on another output mix,
5468 // invalidate all tracks in this strategy to force re connection.
5469 // Otherwise select new device on the output mix.
5470 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005471 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005472 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005473 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5474 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5475 // If the device is using preferred mixer attributes, the output need to reopen
5476 // with default configuration when the new selected devices are different from
5477 // current routing devices.
5478 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5479 continue;
5480 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305481 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005482 }
5483 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005484 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005485}
5486
5487void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5488{
5489 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005490 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005491 for (size_t i = 0; i < mOutputs.size(); i++) {
5492 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005493 for (const auto& client : outputDesc->getClientIterable()) {
5494 if (client->hasPreferredDevice() && client->uid() == uid) {
5495 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005496 auto clientStrategy = client->strategy();
5497 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5498 end(affectedStrategies)) {
5499 continue;
5500 }
5501 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005502 }
5503 }
5504 }
5505 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005506 for (const auto& strategy : affectedStrategies) {
5507 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005508 }
5509
5510 // remove input routes associated with this uid
5511 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005512 for (size_t i = 0; i < mInputs.size(); i++) {
5513 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005514 for (const auto& client : inputDesc->getClientIterable()) {
5515 if (client->hasPreferredDevice() && client->uid() == uid) {
5516 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5517 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005518 }
5519 }
5520 }
5521 // reroute inputs if necessary
5522 SortedVector<audio_io_handle_t> inputsToClose;
5523 for (size_t i = 0; i < mInputs.size(); i++) {
5524 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005525 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005526 inputsToClose.add(inputDesc->mIoHandle);
5527 }
5528 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005529 for (const auto& input : inputsToClose) {
5530 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005531 }
5532}
5533
Eric Laurentd60560a2015-04-10 11:31:20 -07005534void AudioPolicyManager::clearAudioSources(uid_t uid)
5535{
5536 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005537 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5538 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005539 stopAudioSource(mAudioSources.keyAt(i));
5540 }
5541 }
5542}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005543
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005544status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5545 audio_io_handle_t *ioHandle,
5546 audio_devices_t *device)
5547{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005548 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5549 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005550 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005551 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5552 if (deviceDesc == nullptr) {
5553 return INVALID_OPERATION;
5554 }
5555 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005556
François Gaffiedf372692015-03-19 10:43:27 +01005557 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005558}
5559
Eric Laurentd60560a2015-04-10 11:31:20 -07005560status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005561 const audio_attributes_t *attributes,
5562 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005563 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005564{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005565 ALOGV("%s", __FUNCTION__);
5566 *portId = AUDIO_PORT_HANDLE_NONE;
5567
5568 if (source == NULL || attributes == NULL || portId == NULL) {
5569 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5570 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005571 return BAD_VALUE;
5572 }
5573
Eric Laurentd60560a2015-04-10 11:31:20 -07005574 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5575 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005576 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5577 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005578 return INVALID_OPERATION;
5579 }
5580
François Gaffie11d30102018-11-02 16:09:09 +01005581 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005582 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005583 String8(source->ext.device.address),
5584 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005585 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005586 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005587 return BAD_VALUE;
5588 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005589
jiabin4ef93452019-09-10 14:29:54 -07005590 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005591
François Gaffieaaac0fd2018-11-22 17:56:39 +01005592 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005593 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005594 mEngine->getStreamTypeForAttributes(*attributes),
5595 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005596 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005597
5598 status_t status = connectAudioSource(sourceDesc);
5599 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005600 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005601 }
5602 return status;
5603}
5604
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005605status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005606{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005607 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005608
5609 // make sure we only have one patch per source.
5610 disconnectAudioSource(sourceDesc);
5611
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005612 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005613 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5614 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5615 sourceDesc->srcDevice()->type(),
5616 String8(sourceDesc->srcDevice()->address().c_str()),
5617 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005618 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005619 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005620 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005621 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005622 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5623 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5624 return INVALID_OPERATION;
5625 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005626 PatchBuilder patchBuilder;
5627 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5628 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005629
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005630 return connectAudioSourceToSink(
5631 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005632}
5633
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005634status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005635{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005636 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5637 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005638 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005639 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005640 return BAD_VALUE;
5641 }
5642 status_t status = disconnectAudioSource(sourceDesc);
5643
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005644 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005645 return status;
5646}
5647
Andy Hung2ddee192015-12-18 17:34:44 -08005648status_t AudioPolicyManager::setMasterMono(bool mono)
5649{
5650 if (mMasterMono == mono) {
5651 return NO_ERROR;
5652 }
5653 mMasterMono = mono;
5654 // if enabling mono we close all offloaded devices, which will invalidate the
5655 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5656 // for recreating the new AudioTrack as non-offloaded PCM.
5657 //
5658 // If disabling mono, we leave all tracks as is: we don't know which clients
5659 // and tracks are able to be recreated as offloaded. The next "song" should
5660 // play back offloaded.
5661 if (mMasterMono) {
5662 Vector<audio_io_handle_t> offloaded;
5663 for (size_t i = 0; i < mOutputs.size(); ++i) {
5664 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5665 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5666 offloaded.push(desc->mIoHandle);
5667 }
5668 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005669 for (const auto& handle : offloaded) {
5670 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005671 }
5672 }
5673 // update master mono for all remaining outputs
5674 for (size_t i = 0; i < mOutputs.size(); ++i) {
5675 updateMono(mOutputs.keyAt(i));
5676 }
5677 return NO_ERROR;
5678}
5679
5680status_t AudioPolicyManager::getMasterMono(bool *mono)
5681{
5682 *mono = mMasterMono;
5683 return NO_ERROR;
5684}
5685
Eric Laurentac9cef52017-06-09 15:46:26 -07005686float AudioPolicyManager::getStreamVolumeDB(
5687 audio_stream_type_t stream, int index, audio_devices_t device)
5688{
jiabin9a3361e2019-10-01 09:38:30 -07005689 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005690}
5691
jiabin81772902018-04-02 17:52:27 -07005692status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5693 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005694 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005695{
Kriti Dang6537def2021-03-02 13:46:59 +01005696 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5697 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005698 return BAD_VALUE;
5699 }
Kriti Dang6537def2021-03-02 13:46:59 +01005700 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5701 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005702
5703 size_t formatsWritten = 0;
5704 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005705
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005706 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005707 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5708 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005709 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005710 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005711 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005712 bool formatEnabled = true;
5713 switch (forceUse) {
5714 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005715 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005716 break;
5717 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5718 formatEnabled = false;
5719 break;
5720 default: // AUTO or ALWAYS => true
5721 break;
jiabin81772902018-04-02 17:52:27 -07005722 }
5723 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5724 }
jiabin81772902018-04-02 17:52:27 -07005725 }
5726 return NO_ERROR;
5727}
5728
Kriti Dang6537def2021-03-02 13:46:59 +01005729status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5730 audio_format_t *surroundFormats) {
5731 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5732 return BAD_VALUE;
5733 }
5734 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5735 __func__, *numSurroundFormats, surroundFormats);
5736
5737 size_t formatsWritten = 0;
5738 size_t formatsMax = *numSurroundFormats;
5739 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5740
5741 // Return formats from all device profiles that have already been resolved by
5742 // checkOutputsForDevice().
5743 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5744 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5745 audio_devices_t deviceType = device->type();
5746 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5747 // returns formats reported by HDMI devices.
5748 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5749 continue;
5750 }
5751 // Formats reported by sink devices
5752 std::unordered_set<audio_format_t> formatset;
5753 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5754 formatset.insert(it->second.begin(), it->second.end());
5755 }
5756
5757 // Formats hard-coded in the in policy configuration file (if any).
5758 FormatVector encodedFormats = device->encodedFormats();
5759 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5760 // Filter the formats which are supported by the vendor hardware.
5761 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005762 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005763 formats.insert(*it);
5764 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005765 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005766 if (pair.second.count(*it) != 0) {
5767 formats.insert(pair.first);
5768 break;
5769 }
5770 }
5771 }
5772 }
5773 }
5774 *numSurroundFormats = formats.size();
5775 for (const auto& format: formats) {
5776 if (formatsWritten < formatsMax) {
5777 surroundFormats[formatsWritten++] = format;
5778 }
5779 }
5780 return NO_ERROR;
5781}
5782
jiabin81772902018-04-02 17:52:27 -07005783status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5784{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005785 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005786 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5787 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005788 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005789 return BAD_VALUE;
5790 }
5791
Mikhail Naganov100f0122018-11-29 11:22:16 -08005792 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5793 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005794 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005795 return INVALID_OPERATION;
5796 }
5797
Mikhail Naganov100f0122018-11-29 11:22:16 -08005798 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005799 return NO_ERROR;
5800 }
5801
Mikhail Naganov100f0122018-11-29 11:22:16 -08005802 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005803 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005804 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005805 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005806 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005807 }
5808 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005809 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005810 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005811 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005812 }
5813 }
5814
5815 sp<SwAudioOutputDescriptor> outputDesc;
5816 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005817 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5818 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005819 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5820 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005821 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005822 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005823 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5824 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5825 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005826 name.c_str(),
5827 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005828 if (status != NO_ERROR) {
5829 continue;
5830 }
5831 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5832 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5833 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005834 name.c_str(),
5835 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005836 profileUpdated |= (status == NO_ERROR);
5837 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005838 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005839 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005840 AUDIO_DEVICE_IN_HDMI);
5841 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5842 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005843 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005844 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005845 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5846 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5847 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005848 name.c_str(),
5849 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005850 if (status != NO_ERROR) {
5851 continue;
5852 }
5853 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5854 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5855 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005856 name.c_str(),
5857 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005858 profileUpdated |= (status == NO_ERROR);
5859 }
5860
jiabin81772902018-04-02 17:52:27 -07005861 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005862 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005863 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005864 }
5865
5866 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5867}
5868
Eric Laurent5ada82e2019-08-29 17:53:54 -07005869void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005870{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005871 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005872 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005873 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005874 }
5875}
5876
jiabin6012f912018-11-02 17:06:30 -07005877bool AudioPolicyManager::isHapticPlaybackSupported()
5878{
5879 for (const auto& hwModule : mHwModules) {
5880 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5881 for (const auto &outProfile : outputProfiles) {
5882 struct audio_port audioPort;
5883 outProfile->toAudioPort(&audioPort);
5884 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5885 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5886 return true;
5887 }
5888 }
5889 }
5890 }
5891 return false;
5892}
5893
Carter Hsu325a8eb2022-01-19 19:56:51 +08005894bool AudioPolicyManager::isUltrasoundSupported()
5895{
5896 bool hasUltrasoundOutput = false;
5897 bool hasUltrasoundInput = false;
5898 for (const auto& hwModule : mHwModules) {
5899 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5900 if (!hasUltrasoundOutput) {
5901 for (const auto &outProfile : outputProfiles) {
5902 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5903 hasUltrasoundOutput = true;
5904 break;
5905 }
5906 }
5907 }
5908
5909 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5910 if (!hasUltrasoundInput) {
5911 for (const auto &inputProfile : inputProfiles) {
5912 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5913 hasUltrasoundInput = true;
5914 break;
5915 }
5916 }
5917 }
5918
5919 if (hasUltrasoundOutput && hasUltrasoundInput)
5920 return true;
5921 }
5922 return false;
5923}
5924
Atneya Nair698f5ef2022-12-15 16:15:09 -08005925bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5926{
5927 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5928 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5929 for (const auto& hwModule : mHwModules) {
5930 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5931 for (const auto &inputProfile : inputProfiles) {
5932 if ((inputProfile->getFlags() & mask) == mask) {
5933 return true;
5934 }
5935 }
5936 }
5937 return false;
5938}
5939
Eric Laurent8340e672019-11-06 11:01:08 -08005940bool AudioPolicyManager::isCallScreenModeSupported()
5941{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005942 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005943}
5944
5945
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005946status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005947{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005948 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005949 if (!sourceDesc->isConnected()) {
5950 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5951 return NO_ERROR;
5952 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005953 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5954 if (swOutput != 0) {
5955 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005956 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005957 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005958 }
jiabinbce0c1d2020-10-05 11:20:18 -07005959 if (releaseOutput(sourceDesc->portId())) {
5960 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5961 // no need to release audio patch here but just return NO_ERROR.
5962 return NO_ERROR;
5963 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005964 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005965 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005966 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005967 // close Hwoutput and remove from mHwOutputs
5968 } else {
5969 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5970 }
5971 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005972 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005973 sourceDesc->disconnect();
5974 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005975}
5976
François Gaffiec005e562018-11-06 15:04:49 +01005977sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5978 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005979{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005980 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005981 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005982 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005983 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005984 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5985 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005986 source = sourceDesc;
5987 break;
5988 }
5989 }
5990 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005991}
5992
Eric Laurentb4f42a92022-01-17 17:37:31 +01005993bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005994 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005995 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005996{
5997 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5998 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005999 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006000 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02006001 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
6002 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
6003 return false;
6004 }
6005 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6006 return false;
6007 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006008 }
6009
Eric Laurentd332bc82023-08-04 11:45:23 +02006010 // The caller can have the audio config criteria ignored by either passing a null ptr or
6011 // the AUDIO_CONFIG_INITIALIZER value.
6012 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006013 // some positional channel masks and PCM format and for stereo if low latency performance
6014 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006015
6016 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006017 const bool channel_mask_spatialized =
6018 com_android_media_audio_stereo_spatialization()
6019 ? audio_channel_mask_contains_stereo(config->channel_mask)
6020 : audio_is_channel_mask_spatialized(config->channel_mask);
6021 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006022 return false;
6023 }
6024 if (!audio_is_linear_pcm(config->format)) {
6025 return false;
6026 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006027 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6028 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6029 return false;
6030 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006031 }
6032
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006033 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006034 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006035 if (profile == nullptr) {
6036 return false;
6037 }
6038
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006039 return true;
6040}
6041
6042void AudioPolicyManager::checkVirtualizerClientRoutes() {
6043 std::set<audio_stream_type_t> streamsToInvalidate;
6044 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006045 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6046 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006047 audio_attributes_t attr = client->attributes();
6048 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6049 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6050 audio_config_base_t clientConfig = client->config();
6051 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006052 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006053 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006054 streamsToInvalidate.insert(client->stream());
6055 }
6056 }
6057 }
6058
jiabinc44b3462022-12-08 12:52:31 -08006059 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006060}
6061
Eric Laurente191d1b2022-04-15 11:59:25 +02006062
6063bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6064 const sp<SwAudioOutputDescriptor>& outputDesc) {
6065 if (outputDesc->isDuplicated()) {
6066 return false;
6067 }
6068 DeviceVector devices = outputDesc->supportedDevices();
6069 for (size_t i = 0; i < mOutputs.size(); i++) {
6070 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6071 if (desc == outputDesc || desc->isDuplicated()) {
6072 continue;
6073 }
6074 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6075 if (!sharedDevices.isEmpty()
6076 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6077 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6078 return false;
6079 }
6080 }
6081 return true;
6082}
6083
6084
Eric Laurentfa0f6742021-08-17 18:39:44 +02006085status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006086 const audio_attributes_t *attr,
6087 audio_io_handle_t *output) {
6088 *output = AUDIO_IO_HANDLE_NONE;
6089
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006090 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6091 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6092 audio_config_t *configPtr = nullptr;
6093 audio_config_t config;
6094 if (mixerConfig != nullptr) {
6095 config = audio_config_initializer(mixerConfig);
6096 configPtr = &config;
6097 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006098 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006099 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006100 return BAD_VALUE;
6101 }
6102
6103 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006104 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006105 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006106 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006107 return BAD_VALUE;
6108 }
6109
Eric Laurente191d1b2022-04-15 11:59:25 +02006110 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006111 for (size_t i = 0; i < mOutputs.size(); i++) {
6112 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006113 if (!desc->isDuplicated()
6114 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6115 spatializerOutputs.push_back(desc);
6116 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006117 }
6118 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006119 mSpatializerOutput.clear();
6120 bool outputsChanged = false;
6121 for (const auto& desc : spatializerOutputs) {
6122 if (desc->mProfile == profile
6123 && (configPtr == nullptr
6124 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6125 mSpatializerOutput = desc;
6126 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6127 } else {
6128 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6129 " and devices %s", __func__, desc->mIoHandle,
6130 configPtr != nullptr ? configPtr->channel_mask : 0,
6131 devices.toString().c_str());
6132 closeOutput(desc->mIoHandle);
6133 outputsChanged = true;
6134 }
Eric Laurent39095982021-08-24 18:29:27 +02006135 }
6136
Eric Laurente191d1b2022-04-15 11:59:25 +02006137 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006138 sp<SwAudioOutputDescriptor> desc =
6139 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006140 if (desc != nullptr) {
6141 mSpatializerOutput = desc;
6142 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006143 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006144 }
6145
6146 checkVirtualizerClientRoutes();
6147
Eric Laurente191d1b2022-04-15 11:59:25 +02006148 if (outputsChanged) {
6149 mPreviousOutputs = mOutputs;
6150 mpClientInterface->onAudioPortListUpdate();
6151 }
6152
6153 if (mSpatializerOutput == nullptr) {
6154 ALOGV("%s could not open spatializer output with requested config", __func__);
6155 return BAD_VALUE;
6156 }
Eric Laurent39095982021-08-24 18:29:27 +02006157 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006158 ALOGV("%s returning new spatializer output %d", __func__, *output);
6159 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006160}
6161
Eric Laurentfa0f6742021-08-17 18:39:44 +02006162status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6163 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006164 return INVALID_OPERATION;
6165 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006166 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006167 return BAD_VALUE;
6168 }
Eric Laurent39095982021-08-24 18:29:27 +02006169
Eric Laurente191d1b2022-04-15 11:59:25 +02006170 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6171 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6172 closeOutput(mSpatializerOutput->mIoHandle);
6173 //from now on mSpatializerOutput is null
6174 checkVirtualizerClientRoutes();
6175 }
Eric Laurent39095982021-08-24 18:29:27 +02006176
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006177 return NO_ERROR;
6178}
6179
Eric Laurente552edb2014-03-10 17:42:56 -07006180// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006181// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006182// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006183uint32_t AudioPolicyManager::nextAudioPortGeneration()
6184{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006185 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006186}
6187
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006188AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006189 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006190 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006191 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006192 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006193 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006194 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006195 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006196 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006197 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006198 mAudioPortGeneration(1),
6199 mBeaconMuteRefCount(0),
6200 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006201 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006202 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006203 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006204 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006205{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006206}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006207
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006208status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006209 if (mEngine == nullptr) {
6210 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006211 }
6212 mEngine->setObserver(this);
6213 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006214 if (status != NO_ERROR) {
6215 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6216 return status;
6217 }
François Gaffie2110e042015-03-24 08:41:51 +01006218
jiabin29230182023-04-04 21:02:36 +00006219 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6220 // at the end of this function.
6221 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006222 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6223 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6224
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006225 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006226 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006227 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006228
Eric Laurent3a4311c2014-03-17 12:00:47 -07006229 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006230 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6231 defaultOutputDevice == nullptr ||
6232 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6233 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6234 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006235 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006236 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006237 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006238
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006239 // Silence ALOGV statements
6240 property_set("log.tag." LOG_TAG, "D");
6241
Eric Laurente552edb2014-03-10 17:42:56 -07006242 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006243 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006244}
6245
Eric Laurente0720872014-03-11 09:30:41 -07006246AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006247{
Eric Laurente552edb2014-03-10 17:42:56 -07006248 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006249 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006250 }
6251 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006252 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006253 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006254 mAvailableOutputDevices.clear();
6255 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006256 mOutputs.clear();
6257 mInputs.clear();
6258 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006259 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006260 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006261}
6262
Eric Laurente0720872014-03-11 09:30:41 -07006263status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006264{
Eric Laurent87ffa392015-05-22 10:32:38 -07006265 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006266}
6267
Eric Laurente552edb2014-03-10 17:42:56 -07006268// ---
6269
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006270void AudioPolicyManager::onNewAudioModulesAvailable()
6271{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006272 DeviceVector newDevices;
6273 onNewAudioModulesAvailableInt(&newDevices);
6274 if (!newDevices.empty()) {
6275 nextAudioPortGeneration();
6276 mpClientInterface->onAudioPortListUpdate();
6277 }
6278}
6279
6280void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6281{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006282 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006283 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6284 continue;
6285 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006286 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006287 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6288 handle != AUDIO_MODULE_HANDLE_NONE) {
6289 hwModule->setHandle(handle);
6290 } else {
6291 ALOGW("could not load HW module %s", hwModule->getName());
6292 continue;
6293 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006294 }
6295 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006296 // open all output streams needed to access attached devices.
6297 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006298 // This also validates mAvailableOutputDevices list
6299 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6300 if (!outProfile->canOpenNewIo()) {
6301 ALOGE("Invalid Output profile max open count %u for profile %s",
6302 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6303 continue;
6304 }
6305 if (!outProfile->hasSupportedDevices()) {
6306 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6307 continue;
6308 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006309 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6310 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006311 mTtsOutputAvailable = true;
6312 }
6313
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006314 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006315 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006316 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006317 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6318 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006319 } else {
6320 // choose first device present in profile's SupportedDevices also part of
6321 // mAvailableOutputDevices.
6322 if (availProfileDevices.isEmpty()) {
6323 continue;
6324 }
6325 supportedDevice = availProfileDevices.itemAt(0);
6326 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006327 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006328 continue;
6329 }
6330 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6331 mpClientInterface);
6332 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006333 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6334 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006335 AUDIO_STREAM_DEFAULT,
6336 AUDIO_OUTPUT_FLAG_NONE, &output);
6337 if (status != NO_ERROR) {
6338 ALOGW("Cannot open output stream for devices %s on hw module %s",
6339 supportedDevice->toString().c_str(), hwModule->getName());
6340 continue;
6341 }
6342 for (const auto &device : availProfileDevices) {
6343 // give a valid ID to an attached device once confirmed it is reachable
6344 if (!device->isAttached()) {
6345 device->attach(hwModule);
6346 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006347 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006348 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006349 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6350 }
6351 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006352 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006353 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6354 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006355 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006356 }
Eric Laurent39095982021-08-24 18:29:27 +02006357 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006358 outputDesc->close();
6359 } else {
6360 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306361 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006362 DeviceVector(supportedDevice),
6363 true,
6364 0,
6365 NULL);
6366 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006367 }
6368 // open input streams needed to access attached devices to validate
6369 // mAvailableInputDevices list
6370 for (const auto& inProfile : hwModule->getInputProfiles()) {
6371 if (!inProfile->canOpenNewIo()) {
6372 ALOGE("Invalid Input profile max open count %u for profile %s",
6373 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6374 continue;
6375 }
6376 if (!inProfile->hasSupportedDevices()) {
6377 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6378 continue;
6379 }
6380 // chose first device present in profile's SupportedDevices also part of
6381 // available input devices
6382 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006383 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006384 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006385 ALOGV("%s: Input device list is empty! for profile %s",
6386 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006387 continue;
6388 }
6389 sp<AudioInputDescriptor> inputDesc =
6390 new AudioInputDescriptor(inProfile, mpClientInterface);
6391
6392 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6393 status_t status = inputDesc->open(nullptr,
6394 availProfileDevices.itemAt(0),
6395 AUDIO_SOURCE_MIC,
6396 AUDIO_INPUT_FLAG_NONE,
6397 &input);
6398 if (status != NO_ERROR) {
6399 ALOGW("Cannot open input stream for device %s on hw module %s",
6400 availProfileDevices.toString().c_str(),
6401 hwModule->getName());
6402 continue;
6403 }
6404 for (const auto &device : availProfileDevices) {
6405 // give a valid ID to an attached device once confirmed it is reachable
6406 if (!device->isAttached()) {
6407 device->attach(hwModule);
6408 device->importAudioPortAndPickAudioProfile(inProfile, true);
6409 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006410 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006411 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6412 }
6413 }
6414 inputDesc->close();
6415 }
6416 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006417
6418 // Check if spatializer outputs can be closed until used.
6419 // mOutputs vector never contains duplicated outputs at this point.
6420 std::vector<audio_io_handle_t> outputsClosed;
6421 for (size_t i = 0; i < mOutputs.size(); i++) {
6422 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6423 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6424 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6425 outputsClosed.push_back(desc->mIoHandle);
6426 desc->close();
6427 }
6428 }
6429 for (auto output : outputsClosed) {
6430 removeOutput(output);
6431 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006432}
6433
Eric Laurent98e38192018-02-15 18:31:53 -08006434void AudioPolicyManager::addOutput(audio_io_handle_t output,
6435 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006436{
Eric Laurent1c333e22014-05-20 10:48:17 -07006437 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006438 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006439 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006440 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006441 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006442}
6443
François Gaffie53615e22015-03-19 09:24:12 +01006444void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6445{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006446 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6447 ALOGV("%s: removing primary output", __func__);
6448 mPrimaryOutput = nullptr;
6449 }
François Gaffie53615e22015-03-19 09:24:12 +01006450 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006451 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006452}
6453
Eric Laurent98e38192018-02-15 18:31:53 -08006454void AudioPolicyManager::addInput(audio_io_handle_t input,
6455 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006456{
Eric Laurent1c333e22014-05-20 10:48:17 -07006457 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006458 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006459}
Eric Laurente552edb2014-03-10 17:42:56 -07006460
François Gaffie11d30102018-11-02 16:09:09 +01006461status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006462 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006463 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006464{
François Gaffie11d30102018-11-02 16:09:09 +01006465 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006466 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006467 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006468
François Gaffie11d30102018-11-02 16:09:09 +01006469 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006470 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006471 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006472 }
Eric Laurente552edb2014-03-10 17:42:56 -07006473
Eric Laurent3b73df72014-03-11 09:06:29 -07006474 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006475 // first call getAudioPort to get the supported attributes from the HAL
6476 struct audio_port_v7 port = {};
6477 device->toAudioPort(&port);
6478 status_t status = mpClientInterface->getAudioPort(&port);
6479 if (status == NO_ERROR) {
6480 device->importAudioPort(port);
6481 }
6482
6483 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006484 for (size_t i = 0; i < mOutputs.size(); i++) {
6485 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006486 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006487 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006488 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6489 mOutputs.keyAt(i), device->toString().c_str());
6490 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006491 }
6492 }
6493 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006494 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006495 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006496 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6497 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006498 if (profile->supportsDevice(device)) {
6499 profiles.add(profile);
6500 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6501 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006502 }
6503 }
6504 }
6505
Eric Laurent7b279bb2015-12-14 10:18:23 -08006506 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006507
Eric Laurente552edb2014-03-10 17:42:56 -07006508 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006509 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006510 return BAD_VALUE;
6511 }
6512
6513 // open outputs for matching profiles if needed. Direct outputs are also opened to
6514 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6515 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006516 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006517
6518 // nothing to do if one output is already opened for this profile
6519 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006520 for (j = 0; j < outputs.size(); j++) {
6521 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006522 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006523 // matching profile: save the sample rates, format and channel masks supported
6524 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006525 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006526 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006527 }
Eric Laurente552edb2014-03-10 17:42:56 -07006528 break;
6529 }
6530 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006531 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006532 continue;
6533 }
6534
Eric Laurent3974e3b2017-12-07 17:58:43 -08006535 if (!profile->canOpenNewIo()) {
6536 ALOGW("Max Output number %u already opened for this profile %s",
6537 profile->maxOpenCount, profile->getTagName().c_str());
6538 continue;
6539 }
6540
Eric Laurent83efe1c2017-07-09 16:51:08 -07006541 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006542 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006543 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6544 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006545 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006546 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006547 profiles.removeAt(profile_index);
6548 profile_index--;
6549 } else {
6550 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006551 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006552 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006553 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6554 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006555 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006556 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006557
François Gaffie11d30102018-11-02 16:09:09 +01006558 if (device_distinguishes_on_address(deviceType)) {
6559 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6560 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306561 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6562 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006563 }
Eric Laurente552edb2014-03-10 17:42:56 -07006564 ALOGV("checkOutputsForDevice(): adding output %d", output);
6565 }
6566 }
6567
6568 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006569 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006570 return BAD_VALUE;
6571 }
Eric Laurentd4692962014-05-05 18:13:44 -07006572 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006573 // check if one opened output is not needed any more after disconnecting one device
6574 for (size_t i = 0; i < mOutputs.size(); i++) {
6575 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006576 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006577 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006578 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006579 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006580 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006581 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006582 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6583 mOutputs.keyAt(i));
6584 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006585 }
Eric Laurente552edb2014-03-10 17:42:56 -07006586 }
6587 }
Eric Laurentd4692962014-05-05 18:13:44 -07006588 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006589 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006590 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6591 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006592 if (!profile->supportsDevice(device)) {
6593 continue;
6594 }
6595 ALOGV("checkOutputsForDevice(): "
6596 "clearing direct output profile %zu on module %s",
6597 j, hwModule->getName());
6598 profile->clearAudioProfiles();
6599 if (!profile->hasDynamicAudioProfile()) {
6600 continue;
6601 }
6602 // When a device is disconnected, if there is an IOProfile that contains dynamic
6603 // profiles and supports the disconnected device, call getAudioPort to repopulate
6604 // the capabilities of the devices that is supported by the IOProfile.
6605 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6606 if (supportedDevice == device ||
6607 !mAvailableOutputDevices.contains(supportedDevice)) {
6608 continue;
6609 }
6610 struct audio_port_v7 port;
6611 supportedDevice->toAudioPort(&port);
6612 status_t status = mpClientInterface->getAudioPort(&port);
6613 if (status == NO_ERROR) {
6614 supportedDevice->importAudioPort(port);
6615 }
Eric Laurente552edb2014-03-10 17:42:56 -07006616 }
6617 }
6618 }
6619 }
6620 return NO_ERROR;
6621}
6622
François Gaffie11d30102018-11-02 16:09:09 +01006623status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006624 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006625{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006626 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006627
François Gaffie11d30102018-11-02 16:09:09 +01006628 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006629 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006630 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006631 }
6632
Eric Laurentd4692962014-05-05 18:13:44 -07006633 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006634 // first call getAudioPort to get the supported attributes from the HAL
6635 struct audio_port_v7 port = {};
6636 device->toAudioPort(&port);
6637 status_t status = mpClientInterface->getAudioPort(&port);
6638 if (status == NO_ERROR) {
6639 device->importAudioPort(port);
6640 }
6641
Eric Laurent0dd51852019-04-19 18:18:58 -07006642 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006643 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006644 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006645 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006646 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006647 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006648 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006649
François Gaffie11d30102018-11-02 16:09:09 +01006650 if (profile->supportsDevice(device)) {
6651 profiles.add(profile);
6652 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6653 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006654 }
6655 }
6656 }
6657
Eric Laurent0dd51852019-04-19 18:18:58 -07006658 if (profiles.isEmpty()) {
6659 ALOGW("%s: No input profile available for device %s",
6660 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006661 return BAD_VALUE;
6662 }
6663
6664 // open inputs for matching profiles if needed. Direct inputs are also opened to
6665 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6666 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6667
Eric Laurent1c333e22014-05-20 10:48:17 -07006668 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006669
Eric Laurentd4692962014-05-05 18:13:44 -07006670 // nothing to do if one input is already opened for this profile
6671 size_t input_index;
6672 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6673 desc = mInputs.valueAt(input_index);
6674 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006675 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006676 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006677 }
Eric Laurentd4692962014-05-05 18:13:44 -07006678 break;
6679 }
6680 }
6681 if (input_index != mInputs.size()) {
6682 continue;
6683 }
6684
Eric Laurent3974e3b2017-12-07 17:58:43 -08006685 if (!profile->canOpenNewIo()) {
6686 ALOGW("Max Input number %u already opened for this profile %s",
6687 profile->maxOpenCount, profile->getTagName().c_str());
6688 continue;
6689 }
6690
Eric Laurentfe231122017-11-17 17:48:06 -08006691 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006692 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006693 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006694
Eric Laurentcf2c0212014-07-25 16:20:43 -07006695 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006696 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006697 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006698 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006699 mpClientInterface->setParameters(input, String8(param));
6700 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006701 }
jiabin12537fc2023-10-12 17:56:08 +00006702 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006703 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006704 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006705 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006706 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006707 }
6708
Eric Laurent0dd51852019-04-19 18:18:58 -07006709 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006710 addInput(input, desc);
6711 }
6712 } // endif input != 0
6713
Eric Laurentcf2c0212014-07-25 16:20:43 -07006714 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006715 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006716 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006717 profiles.removeAt(profile_index);
6718 profile_index--;
6719 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006720 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006721 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006722 }
Eric Laurentd4692962014-05-05 18:13:44 -07006723 ALOGV("checkInputsForDevice(): adding input %d", input);
6724 }
6725 } // end scan profiles
6726
6727 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006728 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006729 return BAD_VALUE;
6730 }
6731 } else {
6732 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006733 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006734 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006735 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006736 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006737 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006738 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006739 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006740 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6741 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006742 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006743 }
6744 }
6745 }
6746 } // end disconnect
6747
6748 return NO_ERROR;
6749}
6750
6751
Eric Laurente0720872014-03-11 09:30:41 -07006752void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006753{
6754 ALOGV("closeOutput(%d)", output);
6755
François Gaffie1c878552018-11-22 16:53:21 +01006756 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6757 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006758 ALOGW("closeOutput() unknown output %d", output);
6759 return;
6760 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006761 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006762 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006763
Eric Laurente552edb2014-03-10 17:42:56 -07006764 // look for duplicated outputs connected to the output being removed.
6765 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006766 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6767 if (dupOutput->isDuplicated() &&
6768 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6769 sp<SwAudioOutputDescriptor> remainingOutput =
6770 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006771 // As all active tracks on duplicated output will be deleted,
6772 // and as they were also referenced on the other output, the reference
6773 // count for their stream type must be adjusted accordingly on
6774 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006775 const bool wasActive = remainingOutput->isActive();
6776 // Note: no-op on the closing output where all clients has already been set inactive
6777 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006778 // stop() will be a no op if the output is still active but is needed in case all
6779 // active streams refcounts where cleared above
6780 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006781 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006782 }
Eric Laurente552edb2014-03-10 17:42:56 -07006783 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6784 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6785
6786 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006787 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006788 }
6789 }
6790
Eric Laurent05b90f82014-08-27 15:32:29 -07006791 nextAudioPortGeneration();
6792
François Gaffie1c878552018-11-22 16:53:21 +01006793 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006794 if (index >= 0) {
6795 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006796 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6797 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006798 mAudioPatches.removeItemsAt(index);
6799 mpClientInterface->onAudioPatchListUpdate();
6800 }
6801
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006802 if (closingOutputWasActive) {
6803 closingOutput->stop();
6804 }
François Gaffie1c878552018-11-22 16:53:21 +01006805 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006806 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6807 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6808 for (const auto device : closingOutput->devices()) {
6809 device->setPreferredConfig(nullptr);
6810 }
6811 }
Eric Laurente552edb2014-03-10 17:42:56 -07006812
François Gaffie53615e22015-03-19 09:24:12 +01006813 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006814 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006815 if (closingOutput == mSpatializerOutput) {
6816 mSpatializerOutput.clear();
6817 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006818
6819 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6820 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006821 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006822 bool directOutputOpen = false;
6823 for (size_t i = 0; i < mOutputs.size(); i++) {
6824 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6825 directOutputOpen = true;
6826 break;
6827 }
6828 }
6829 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006830 ALOGV("no direct outputs open, reset MSD patches");
6831 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6832 // how output devices for patching are resolved. Avoid by caching and reusing the
6833 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6834 // devices to patch to. This may be complicated by the fact that devices may become
6835 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006836 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006837 }
6838 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006839}
6840
6841void AudioPolicyManager::closeInput(audio_io_handle_t input)
6842{
6843 ALOGV("closeInput(%d)", input);
6844
6845 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6846 if (inputDesc == NULL) {
6847 ALOGW("closeInput() unknown input %d", input);
6848 return;
6849 }
6850
Eric Laurent6a94d692014-05-20 11:18:06 -07006851 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006852
François Gaffie11d30102018-11-02 16:09:09 +01006853 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006854 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006855 if (index >= 0) {
6856 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006857 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6858 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006859 mAudioPatches.removeItemsAt(index);
6860 mpClientInterface->onAudioPatchListUpdate();
6861 }
6862
François Gaffie6ebbce02023-07-19 13:27:53 +02006863 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006864 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006865 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006866
François Gaffie11d30102018-11-02 16:09:09 +01006867 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6868 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006869 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006870 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006871 }
Eric Laurente552edb2014-03-10 17:42:56 -07006872}
6873
François Gaffie11d30102018-11-02 16:09:09 +01006874SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6875 const DeviceVector &devices,
6876 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006877{
6878 SortedVector<audio_io_handle_t> outputs;
6879
François Gaffie11d30102018-11-02 16:09:09 +01006880 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006881 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006882 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006883 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006884 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006885 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006886 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006887 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006888 outputs.add(openOutputs.keyAt(i));
6889 }
6890 }
6891 return outputs;
6892}
6893
Mikhail Naganov37977152018-07-11 15:54:44 -07006894void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6895{
6896 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6897 // output is suspended before any tracks are moved to it
6898 checkA2dpSuspend();
6899 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006900 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006901 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006902 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006903 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006904 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6905 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6906 // configuration changes will ultimately be rerouted correctly. We can still avoid
6907 // unnecessary rerouting by caching and reusing the arguments to
6908 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6909 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006910 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006911 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006912 // an event that changed routing likely occurred, inform upper layers
6913 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006914}
6915
François Gaffiec005e562018-11-06 15:04:49 +01006916bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6917 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006918{
François Gaffiec005e562018-11-06 15:04:49 +01006919 return mEngine->getProductStrategyForAttributes(lAttr) ==
6920 mEngine->getProductStrategyForAttributes(rAttr);
6921}
6922
Francois Gaffieff1eb522020-05-06 18:37:04 +02006923void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6924{
6925 for (size_t i = 0; i < mAudioSources.size(); i++) {
6926 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6927 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006928 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006929 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006930 connectAudioSource(sourceDesc);
6931 }
6932 }
6933}
6934
6935void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6936{
6937 for (size_t i = 0; i < mAudioSources.size(); i++) {
6938 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6939 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6940 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6941 disconnectAudioSource(sourceDesc);
6942 }
6943 }
6944}
6945
François Gaffiec005e562018-11-06 15:04:49 +01006946void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6947{
6948 auto psId = mEngine->getProductStrategyForAttributes(attr);
6949
6950 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6951 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006952
François Gaffie11d30102018-11-02 16:09:09 +01006953 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6954 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006955
Eric Laurentc209fe42020-06-05 18:11:23 -07006956 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006957 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006958 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006959 // take into account dynamic audio policies related changes: if a client is now associated
6960 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006961 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006962 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6963 if (desc->isDuplicated()) {
6964 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006965 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006966 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6967 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6968 continue;
6969 }
6970 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006971 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006972 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6973 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6974 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006975 if (status != OK) {
6976 continue;
6977 }
yucliuf4de36d2020-09-14 14:57:56 -07006978 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006979 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006980 maxLatency = desc->latency();
6981 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006982 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006983 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006984 }
6985 }
6986
Eric Laurent56ed8842022-11-15 16:04:41 +01006987 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006988 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6989 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006990 for (audio_io_handle_t srcOut : srcOutputs) {
6991 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006992 if (desc == nullptr) continue;
6993
6994 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006995 maxLatency = desc->latency();
6996 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006997
Eric Laurent56ed8842022-11-15 16:04:41 +01006998 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006999 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07007000 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07007001 // a client on a non direct outputs has necessarily a linear PCM format
7002 // so we can call selectOutput() safely
7003 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
7004 client->flags(),
7005 client->config().format,
7006 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007007 client->config().sample_rate,
7008 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007009 if (newOutput != srcOut) {
7010 invalidate = true;
7011 break;
7012 }
7013 } else {
7014 sp<IOProfile> profile = getProfileForOutput(newDevices,
7015 client->config().sample_rate,
7016 client->config().format,
7017 client->config().channel_mask,
7018 client->flags(),
7019 true /* directOnly */);
7020 if (profile != desc->mProfile) {
7021 invalidate = true;
7022 break;
7023 }
7024 }
7025 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007026 // mute strategy while moving tracks from one output to another
7027 if (invalidate) {
7028 invalidatedOutputs.push_back(desc);
7029 if (desc->isStrategyActive(psId)) {
7030 setStrategyMute(psId, true, desc);
7031 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7032 newDevices.types());
7033 }
Eric Laurente552edb2014-03-10 17:42:56 -07007034 }
François Gaffiec005e562018-11-06 15:04:49 +01007035 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007036 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007037 connectAudioSource(source);
7038 }
Eric Laurente552edb2014-03-10 17:42:56 -07007039 }
7040
Eric Laurent56ed8842022-11-15 16:04:41 +01007041 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7042 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7043 std::to_string(srcOutputs[0]).c_str(),
7044 std::to_string(dstOutputs[0]).c_str());
7045
François Gaffiec005e562018-11-06 15:04:49 +01007046 // Move effects associated to this stream from previous output to new output
7047 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007048 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007049 }
François Gaffiec005e562018-11-06 15:04:49 +01007050 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007051 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007052 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007053 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007054 desc->setTracksInvalidatedStatusByStrategy(psId);
7055 }
Eric Laurente552edb2014-03-10 17:42:56 -07007056 }
7057 }
7058}
7059
Eric Laurente0720872014-03-11 09:30:41 -07007060void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007061{
François Gaffiec005e562018-11-06 15:04:49 +01007062 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7063 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7064 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007065 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007066 }
Eric Laurente552edb2014-03-10 17:42:56 -07007067}
7068
Kevin Rocard153f92d2018-12-18 18:33:28 -08007069void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007070 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007071 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007072 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007073 for (size_t i = 0; i < mOutputs.size(); i++) {
7074 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7075 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007076 sp<AudioPolicyMix> primaryMix;
7077 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007078 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007079 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7080 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7081 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007082 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7083 for (auto &secondaryMix : secondaryMixes) {
7084 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7085 if (outputDesc != nullptr &&
7086 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7087 secondaryDescs.push_back(outputDesc);
7088 }
7089 }
7090
jiabinc44b3462022-12-08 12:52:31 -08007091 if (status != OK &&
7092 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7093 // When it failed to query secondary output, only invalidate the client that is not
7094 // MMAP. The reason is that MMAP stream will not support secondary output.
7095 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007096 } else if (!std::equal(
7097 client->getSecondaryOutputs().begin(),
7098 client->getSecondaryOutputs().end(),
7099 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007100 if (!audio_is_linear_pcm(client->config().format)) {
7101 // If the format is not PCM, the tracks should be invalidated to get correct
7102 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007103 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007104 } else {
7105 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7106 std::vector<audio_io_handle_t> secondaryOutputIds;
7107 for (const auto &secondaryDesc: secondaryDescs) {
7108 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7109 weakSecondaryDescs.push_back(secondaryDesc);
7110 }
7111 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7112 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007113 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007114 }
7115 }
7116 }
jiabin10a03f12021-05-07 23:46:28 +00007117 if (!trackSecondaryOutputs.empty()) {
7118 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7119 }
jiabinc44b3462022-12-08 12:52:31 -08007120 if (!clientsToInvalidate.empty()) {
7121 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7122 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007123 }
7124}
7125
Eric Laurent2517af32020-11-25 15:31:27 +01007126bool AudioPolicyManager::isScoRequestedForComm() const {
7127 AudioDeviceTypeAddrVector devices;
7128 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7129 for (const auto &device : devices) {
7130 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7131 return true;
7132 }
7133 }
7134 return false;
7135}
7136
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007137bool AudioPolicyManager::isHearingAidUsedForComm() const {
7138 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7139 true /*fromCache*/);
7140 for (const auto &device : devices) {
7141 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7142 return true;
7143 }
7144 }
7145 return false;
7146}
7147
7148
Eric Laurente0720872014-03-11 09:30:41 -07007149void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007150{
François Gaffie53615e22015-03-19 09:24:12 +01007151 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007152 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007153 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007154 return;
7155 }
7156
Eric Laurent3a4311c2014-03-17 12:00:47 -07007157 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007158 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7159 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007160 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007161
7162 // if suspended, restore A2DP output if:
7163 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007164 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007165 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007166 //
Eric Laurentf732e072016-08-03 19:30:28 -07007167 // if not suspended, suspend A2DP output if:
7168 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007169 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007170 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007171 //
7172 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007173 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007174 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007175 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007176 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007177
7178 mpClientInterface->restoreOutput(a2dpOutput);
7179 mA2dpSuspended = false;
7180 }
7181 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007182 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007183 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007184 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007185 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007186
7187 mpClientInterface->suspendOutput(a2dpOutput);
7188 mA2dpSuspended = true;
7189 }
7190 }
7191}
7192
François Gaffie11d30102018-11-02 16:09:09 +01007193DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7194 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007195{
François Gaffiedb1755b2023-09-01 11:50:35 +02007196 if (outputDesc == nullptr) {
7197 return DeviceVector{};
7198 }
François Gaffie11d30102018-11-02 16:09:09 +01007199
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007200 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007201 if (index >= 0) {
7202 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007203 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007204 ALOGV("%s device %s forced by patch %d", __func__,
7205 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7206 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007207 }
7208 }
7209
Dean Wheatley514b4312020-06-17 21:45:00 +10007210 // Do not retrieve engine device for outputs through MSD
7211 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7212 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7213 return outputDesc->devices();
7214 }
7215
Eric Laurent97ac8712018-07-27 18:59:02 -07007216 // Honor explicit routing requests only if no client using default routing is active on this
7217 // input: a specific app can not force routing for other apps by setting a preferred device.
7218 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007219 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007220 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007221 if (device != nullptr) {
7222 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007223 }
7224
François Gaffiea807ef92018-11-05 10:44:33 +01007225 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7226 // of setForceUse / Default Bus device here
7227 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7228 if (device != nullptr) {
7229 return DeviceVector(device);
7230 }
7231
François Gaffiedb1755b2023-09-01 11:50:35 +02007232 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007233 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7234 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7235 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307236 auto hasStreamActive = [&](auto stream) {
7237 return hasStream(streams, stream) && isStreamActive(stream, 0);
7238 };
Eric Laurent484e9272018-06-07 17:29:23 -07007239
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307240 auto doGetOutputDevicesForVoice = [&]() {
7241 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007242 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307243 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007244 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7245 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307246 };
7247
7248 // With low-latency playing on speaker, music on WFD, when the first low-latency
7249 // output is stopped, getNewOutputDevices checks for a product strategy
7250 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007251 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307252 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7253 // stream is associated to the output descriptor.
7254 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7255 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7256 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7257 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007258 // Retrieval of devices for voice DL is done on primary output profile, cannot
7259 // check the route (would force modifying configuration file for this profile)
7260 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7261 break;
7262 }
Eric Laurente552edb2014-03-10 17:42:56 -07007263 }
François Gaffiec005e562018-11-06 15:04:49 +01007264 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007265 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007266}
7267
François Gaffie11d30102018-11-02 16:09:09 +01007268sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7269 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007270{
François Gaffie11d30102018-11-02 16:09:09 +01007271 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007272
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007273 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007274 if (index >= 0) {
7275 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007276 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007277 ALOGV("getNewInputDevice() device %s forced by patch %d",
7278 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7279 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007280 }
7281 }
7282
Eric Laurent97ac8712018-07-27 18:59:02 -07007283 // Honor explicit routing requests only if no client using default routing is active on this
7284 // input: a specific app can not force routing for other apps by setting a preferred device.
7285 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007286 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7287 if (device != nullptr) {
7288 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007289 }
7290
Eric Laurentdc95a252018-04-12 12:46:56 -07007291 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007292 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007293 audio_attributes_t attributes;
7294 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007295 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007296 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7297 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007298 attributes = topClient->attributes();
7299 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007300 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007301 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007302 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7303 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007304 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007305 }
7306
Francois Gaffie716e1432019-01-14 16:58:59 +01007307 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7308 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007309 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007310 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007311 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007312 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007313
Eric Laurente552edb2014-03-10 17:42:56 -07007314 return device;
7315}
7316
Eric Laurent794fde22016-03-11 09:50:45 -08007317bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7318 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007319 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007320}
7321
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007322status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007323 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007324 if (devices == nullptr) {
7325 return BAD_VALUE;
7326 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007327
Andy Hung6d23c0f2022-02-16 09:37:15 -08007328 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007329 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7330 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007331 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007332 for (const auto& device : curDevices) {
7333 devices->push_back(device->getDeviceTypeAddr());
7334 }
7335 return NO_ERROR;
7336}
7337
Eric Laurente0720872014-03-11 09:30:41 -07007338void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007339 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007340 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007341 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007342 updateDevicesAndOutputs();
7343 break;
7344 default:
7345 break;
7346 }
7347}
7348
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007349uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007350
7351 // skip beacon mute management if a dedicated TTS output is available
7352 if (mTtsOutputAvailable) {
7353 return 0;
7354 }
7355
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007356 switch(event) {
7357 case STARTING_OUTPUT:
7358 mBeaconMuteRefCount++;
7359 break;
7360 case STOPPING_OUTPUT:
7361 if (mBeaconMuteRefCount > 0) {
7362 mBeaconMuteRefCount--;
7363 }
7364 break;
7365 case STARTING_BEACON:
7366 mBeaconPlayingRefCount++;
7367 break;
7368 case STOPPING_BEACON:
7369 if (mBeaconPlayingRefCount > 0) {
7370 mBeaconPlayingRefCount--;
7371 }
7372 break;
7373 }
7374
7375 if (mBeaconMuteRefCount > 0) {
7376 // any playback causes beacon to be muted
7377 return setBeaconMute(true);
7378 } else {
7379 // no other playback: unmute when beacon starts playing, mute when it stops
7380 return setBeaconMute(mBeaconPlayingRefCount == 0);
7381 }
7382}
7383
7384uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7385 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7386 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7387 // keep track of muted state to avoid repeating mute/unmute operations
7388 if (mBeaconMuted != mute) {
7389 // mute/unmute AUDIO_STREAM_TTS on all outputs
7390 ALOGV("\t muting %d", mute);
7391 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007392 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7393 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7394 ALOGV("\t no tts volume source available");
7395 return 0;
7396 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007397 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007398 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007399 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007400 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007401 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007402 maxLatency = latency;
7403 }
7404 }
7405 mBeaconMuted = mute;
7406 return maxLatency;
7407 }
7408 return 0;
7409}
7410
Eric Laurente0720872014-03-11 09:30:41 -07007411void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007412{
François Gaffiec005e562018-11-06 15:04:49 +01007413 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007414 mPreviousOutputs = mOutputs;
7415}
7416
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007417uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007418 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007419 uint32_t delayMs)
7420{
7421 // mute/unmute strategies using an incompatible device combination
7422 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7423 // if unmuting, unmute only after the specified delay
7424 if (outputDesc->isDuplicated()) {
7425 return 0;
7426 }
7427
7428 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007429 DeviceVector devices = outputDesc->devices();
7430 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007431
François Gaffiec005e562018-11-06 15:04:49 +01007432 auto productStrategies = mEngine->getOrderedProductStrategies();
7433 for (const auto &productStrategy : productStrategies) {
7434 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7435 DeviceVector curDevices =
7436 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7437 curDevices = curDevices.filter(outputDesc->supportedDevices());
7438 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007439 bool doMute = false;
7440
François Gaffiec005e562018-11-06 15:04:49 +01007441 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007442 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007443 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7444 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007445 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007446 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007447 }
Eric Laurent99401132014-05-07 19:48:15 -07007448 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007449 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007450 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007451 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007452 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007453 continue;
7454 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307455 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007456 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7457 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7458 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007459 if (mute) {
7460 // FIXME: should not need to double latency if volume could be applied
7461 // immediately by the audioflinger mixer. We must account for the delay
7462 // between now and the next time the audioflinger thread for this output
7463 // will process a buffer (which corresponds to one buffer size,
7464 // usually 1/2 or 1/4 of the latency).
7465 if (muteWaitMs < desc->latency() * 2) {
7466 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007467 }
7468 }
7469 }
7470 }
7471 }
7472 }
7473
Eric Laurent99401132014-05-07 19:48:15 -07007474 // temporary mute output if device selection changes to avoid volume bursts due to
7475 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007476 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007477 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007478
Eric Laurentdc462862016-07-19 12:29:53 -07007479 if (muteWaitMs < tempMuteWaitMs) {
7480 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007481 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007482
7483 // If recommended duration is defined, replace temporary mute duration to avoid
7484 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7485 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7486 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7487 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7488 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7489
François Gaffieaaac0fd2018-11-22 17:56:39 +01007490 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7491 // make sure that we do not start the temporary mute period too early in case of
7492 // delayed device change
7493 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7494 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007495 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007496 }
7497 }
7498
Eric Laurente552edb2014-03-10 17:42:56 -07007499 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7500 if (muteWaitMs > delayMs) {
7501 muteWaitMs -= delayMs;
7502 usleep(muteWaitMs * 1000);
7503 return muteWaitMs;
7504 }
7505 return 0;
7506}
7507
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307508uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7509 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007510 const DeviceVector &devices,
7511 bool force,
7512 int delayMs,
7513 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007514 bool requiresMuteCheck, bool requiresVolumeCheck,
7515 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007516{
jiabin3ff8d7d2022-12-13 06:27:44 +00007517 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307518 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7519 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7520 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007521 uint32_t muteWaitMs;
7522
7523 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307524 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007525 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307526 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007527 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007528 return muteWaitMs;
7529 }
Eric Laurente552edb2014-03-10 17:42:56 -07007530
7531 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007532 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007533 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007534 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007535
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307536 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7537 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007538
7539 if (!filteredDevices.isEmpty()) {
7540 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007541 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007542
7543 // if the outputs are not materially active, there is no need to mute.
7544 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007545 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007546 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307547 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7548 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007549 muteWaitMs = 0;
7550 }
Eric Laurente552edb2014-03-10 17:42:56 -07007551
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007552 bool outputRouted = outputDesc->isRouted();
7553
Eric Laurent79ea9582020-06-11 18:49:24 -07007554 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7555 // output profile or if new device is not supported AND previous device(s) is(are) still
7556 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007557 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307558 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7559 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007560 // restore previous device after evaluating strategy mute state
7561 outputDesc->setDevices(prevDevices);
7562 return muteWaitMs;
7563 }
7564
Eric Laurente552edb2014-03-10 17:42:56 -07007565 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007566 // the requested device is AUDIO_DEVICE_NONE
7567 // OR the requested device is the same as current device
7568 // AND force is not specified
7569 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007570 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007571 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307572 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7573 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7574 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007575 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307576 ALOGV("%s %s setting same device on routed output, force apply volumes",
7577 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007578 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7579 }
Eric Laurente552edb2014-03-10 17:42:56 -07007580 return muteWaitMs;
7581 }
7582
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307583 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7584 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007585
Eric Laurente552edb2014-03-10 17:42:56 -07007586 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007587 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007588 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007589 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007590 PatchBuilder patchBuilder;
7591 patchBuilder.addSource(outputDesc);
7592 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7593 for (const auto &filteredDevice : filteredDevices) {
7594 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007595 }
7596
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007597 // Add half reported latency to delayMs when muteWaitMs is null in order
7598 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007599 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7600 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7601 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007602 }
Eric Laurente552edb2014-03-10 17:42:56 -07007603
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007604 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7605 if (!skipMuteDelay) {
7606 // update stream volumes according to new device
7607 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7608 }
Eric Laurente552edb2014-03-10 17:42:56 -07007609
7610 return muteWaitMs;
7611}
7612
Eric Laurentc75307b2015-03-17 15:29:32 -07007613status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007614 int delayMs,
7615 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007616{
Eric Laurent6a94d692014-05-20 11:18:06 -07007617 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007618 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7619 return INVALID_OPERATION;
7620 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007621 if (patchHandle) {
7622 index = mAudioPatches.indexOfKey(*patchHandle);
7623 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007624 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007625 }
7626 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007627 return INVALID_OPERATION;
7628 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007629 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007630 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007631 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007632 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007633 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007634 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007635 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007636 return status;
7637}
7638
7639status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007640 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007641 bool force,
7642 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007643{
7644 status_t status = NO_ERROR;
7645
Eric Laurent1f2f2232014-06-02 12:01:23 -07007646 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007647 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7648 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007649
François Gaffie11d30102018-11-02 16:09:09 +01007650 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007651 PatchBuilder patchBuilder;
7652 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007653 // AUDIO_SOURCE_HOTWORD is for internal use only:
7654 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007655 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7656 auto result = usecase;
7657 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7658 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7659 }
7660 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007661 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007662 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007663 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007664 }
7665 }
7666 return status;
7667}
7668
Eric Laurent6a94d692014-05-20 11:18:06 -07007669status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7670 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007671{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007672 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007673 ssize_t index;
7674 if (patchHandle) {
7675 index = mAudioPatches.indexOfKey(*patchHandle);
7676 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007677 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007678 }
7679 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007680 return INVALID_OPERATION;
7681 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007682 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007683 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007684 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007685 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007686 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007687 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007688 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007689 return status;
7690}
7691
François Gaffie11d30102018-11-02 16:09:09 +01007692sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007693 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007694 audio_format_t& format,
7695 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007696 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007697{
7698 // Choose an input profile based on the requested capture parameters: select the first available
7699 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007700 // The flags can be ignored if it doesn't contain a much match flag.
Eric Laurente552edb2014-03-10 17:42:56 -07007701
Atneya Nair0f0a8032022-12-12 16:20:12 -08007702 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7703 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7704 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7705
7706 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007707
jiabin2fd710d2022-05-02 23:20:22 +00007708 for (;;) {
7709 sp<IOProfile> firstInexact = nullptr;
7710 uint32_t updatedSamplingRate = 0;
7711 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7712 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7713 for (const auto& hwModule : mHwModules) {
7714 for (const auto& profile : hwModule->getInputProfiles()) {
7715 // profile->log();
7716 //updatedFormat = format;
jiabin66acc432024-02-06 00:57:36 +00007717 if (profile->getCompatibilityScore(
7718 DeviceVector(device),
7719 samplingRate,
7720 &updatedSamplingRate,
7721 format,
7722 &updatedFormat,
7723 channelMask,
7724 &updatedChannelMask,
7725 // FIXME ugly cast
7726 (audio_output_flags_t) flags,
7727 true /*exactMatchRequiredForInputFlags*/) == IOProfile::EXACT_MATCH) {
7728 samplingRate = updatedSamplingRate;
7729 format = updatedFormat;
7730 channelMask = updatedChannelMask;
jiabin2fd710d2022-05-02 23:20:22 +00007731 return profile;
7732 }
jiabin66acc432024-02-06 00:57:36 +00007733 if (firstInexact == nullptr
7734 && profile->getCompatibilityScore(
7735 DeviceVector(device),
7736 samplingRate,
7737 &updatedSamplingRate,
7738 format,
7739 &updatedFormat,
7740 channelMask,
7741 &updatedChannelMask,
7742 // FIXME ugly cast
7743 (audio_output_flags_t) flags,
7744 false /*exactMatchRequiredForInputFlags*/)
7745 != IOProfile::NO_MATCH) {
jiabin2fd710d2022-05-02 23:20:22 +00007746 firstInexact = profile;
7747 }
7748 }
7749 }
7750
7751 if (firstInexact != nullptr) {
7752 samplingRate = updatedSamplingRate;
7753 format = updatedFormat;
7754 channelMask = updatedChannelMask;
7755 return firstInexact;
7756 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7757 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7758 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7759 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7760 flags = AUDIO_INPUT_FLAG_NONE;
7761 } else { // fail
7762 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7763 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7764 samplingRate, format, channelMask, oriFlags);
7765 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007766 }
7767 }
jiabin2fd710d2022-05-02 23:20:22 +00007768
7769 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007770}
7771
François Gaffieaaac0fd2018-11-22 17:56:39 +01007772float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7773 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007774 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007775 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007776{
jiabin9a3361e2019-10-01 09:38:30 -07007777 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007778
7779 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7780 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7781 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7782 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007783 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7784 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7785 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7786 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7787 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007788 // Verify that the current volume source is not the ringer volume to prevent recursively
7789 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7790 // to the same volume group.
7791 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007792 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7793 mOutputs.isActive(ringVolumeSrc, 0)) {
7794 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007795 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007796 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007797 }
7798
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007799 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007800 if ((volumeSource != callVolumeSrc && (isInCall() ||
7801 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007802 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007803 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7804 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007805 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7806 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7807 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007808 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007809 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007810 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007811 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007812 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007813 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007814 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7815 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7816 // programmatically muted.
7817 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7818 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7819 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007820 bool exemptFromCapping =
7821 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7822 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007823 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7824 volumeSource, volumeDb);
7825 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007826 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7827 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7828 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007829 }
7830 }
Eric Laurente552edb2014-03-10 17:42:56 -07007831 // if a headset is connected, apply the following rules to ring tones and notifications
7832 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007833 // - always attenuate notifications volume by 6dB
7834 // - attenuate ring tones volume by 6dB unless music is not playing and
7835 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007836 // - if music is playing, always limit the volume to current music volume,
7837 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007838 if (!Intersection(deviceTypes,
7839 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7840 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007841 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7842 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007843 ((volumeSource == alarmVolumeSrc ||
7844 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007845 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7846 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7847 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007848 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7849 curves.canBeMuted()) {
7850
Eric Laurente552edb2014-03-10 17:42:56 -07007851 // when the phone is ringing we must consider that music could have been paused just before
7852 // by the music application and behave as if music was active if the last music track was
7853 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007854 // Verify that the current volume source is not the music volume to prevent recursively
7855 // calling to compute volume. This could happen in cases where music and
7856 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7857 if (volumeSource != musicVolumeSrc &&
7858 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7859 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007860 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007861 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007862 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7863 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007864 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007865 float musicVolDb = computeVolume(musicCurves,
7866 musicVolumeSrc,
7867 musicCurves.getVolumeIndex(musicDevice),
7868 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007869 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7870 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7871 if (volumeDb > minVolDb) {
7872 volumeDb = minVolDb;
7873 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007874 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007875 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7876 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7877 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007878 // on A2DP, also ensure notification volume is not too low compared to media when
7879 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007880 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007881 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007882 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7883 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007884 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7885 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007886 }
7887 }
jiabin9a3361e2019-10-01 09:38:30 -07007888 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007889 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007890 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007891 }
7892 }
7893
François Gaffie43c73442018-11-08 08:21:55 +01007894 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007895}
7896
Eric Laurent3839bc02018-07-10 18:33:34 -07007897int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007898 VolumeSource fromVolumeSource,
7899 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007900{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007901 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007902 return srcIndex;
7903 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007904 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7905 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007906 float minSrc = (float)srcCurves.getVolumeIndexMin();
7907 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7908 float minDst = (float)dstCurves.getVolumeIndexMin();
7909 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007910
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007911 // preserve mute request or correct range
7912 if (srcIndex < minSrc) {
7913 if (srcIndex == 0) {
7914 return 0;
7915 }
7916 srcIndex = minSrc;
7917 } else if (srcIndex > maxSrc) {
7918 srcIndex = maxSrc;
7919 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007920 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7921}
7922
François Gaffieaaac0fd2018-11-22 17:56:39 +01007923status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7924 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007925 int index,
7926 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007927 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007928 int delayMs,
7929 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007930{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007931 // do not change actual attributes volume if the attributes is muted
7932 if (outputDesc->isMuted(volumeSource)) {
7933 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7934 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007935 return NO_ERROR;
7936 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007937
Eric Laurentae6e88c2024-01-10 14:42:57 +01007938 bool isVoiceVolSrc;
7939 bool isBtScoVolSrc;
7940 if (!isVolumeConsistentForCalls(
7941 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07007942 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01007943 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07007944 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007945 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01007946
jiabin9a3361e2019-10-01 09:38:30 -07007947 if (deviceTypes.empty()) {
7948 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007949 index = curves.getVolumeIndex(deviceTypes);
7950 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7951 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007952 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007953
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007954 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7955 ALOGE("invalid volume index range");
7956 return BAD_VALUE;
7957 }
7958
jiabin9a3361e2019-10-01 09:38:30 -07007959 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7960 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007961 // Force VoIP volume to max for bluetooth SCO device except if muted
7962 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007963 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007964 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007965 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007966 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007967 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7968 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007969
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007970 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01007971 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007972 }
Eric Laurente552edb2014-03-10 17:42:56 -07007973 return NO_ERROR;
7974}
7975
Eric Laurentae6e88c2024-01-10 14:42:57 +01007976void AudioPolicyManager::setVoiceVolume(
7977 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
7978 float voiceVolume;
7979 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
7980 // by the headset
7981 if (isVoiceVolSrc) {
7982 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
7983 } else {
7984 voiceVolume = index == 0 ? 0.0 : 1.0;
7985 }
7986 if (voiceVolume != mLastVoiceVolume) {
7987 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7988 mLastVoiceVolume = voiceVolume;
7989 }
7990}
7991
7992bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
7993 const DeviceTypeSet& deviceTypes,
7994 bool& isVoiceVolSrc,
7995 bool& isBtScoVolSrc,
7996 const char* caller) {
7997 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7998 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7999 const bool isScoRequested = isScoRequestedForComm();
8000 const bool isHAUsed = isHearingAidUsedForComm();
8001
8002 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
8003 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
8004
8005 if ((callVolSrc != btScoVolSrc) &&
8006 ((isVoiceVolSrc && isScoRequested) ||
8007 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
8008 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
8009 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
8010 volumeSource, isScoRequested ? " " : " not ");
8011 return false;
8012 }
8013 return true;
8014}
8015
Eric Laurentc75307b2015-03-17 15:29:32 -07008016void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008017 const DeviceTypeSet& deviceTypes,
8018 int delayMs,
8019 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008020{
jiabincd510522020-01-22 09:40:55 -08008021 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008022 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8023 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8024 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008025 curves.getVolumeIndex(deviceTypes),
8026 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008027 }
8028}
8029
François Gaffiec005e562018-11-06 15:04:49 +01008030void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8031 bool on,
8032 const sp<AudioOutputDescriptor>& outputDesc,
8033 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008034 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008035{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008036 std::vector<VolumeSource> sourcesToMute;
8037 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8038 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8039 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008040 VolumeSource source = toVolumeSource(attributes, false);
8041 if ((source != VOLUME_SOURCE_NONE) &&
8042 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8043 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008044 sourcesToMute.push_back(source);
8045 }
Eric Laurente552edb2014-03-10 17:42:56 -07008046 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008047 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008048 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008049 }
8050
Eric Laurente552edb2014-03-10 17:42:56 -07008051}
8052
François Gaffieaaac0fd2018-11-22 17:56:39 +01008053void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8054 bool on,
8055 const sp<AudioOutputDescriptor>& outputDesc,
8056 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008057 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008058{
jiabin9a3361e2019-10-01 09:38:30 -07008059 if (deviceTypes.empty()) {
8060 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008061 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008062 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008063 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008064 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008065 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008066 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008067 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8068 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008069 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008070 }
8071 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008072 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8073 // ignored
8074 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008075 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008076 if (!outputDesc->isMuted(volumeSource)) {
8077 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008078 return;
8079 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008080 if (outputDesc->decMuteCount(volumeSource) == 0) {
8081 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008082 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008083 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008084 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008085 delayMs);
8086 }
8087 }
8088}
8089
François Gaffie53615e22015-03-19 09:24:12 +01008090bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8091{
François Gaffiec005e562018-11-06 15:04:49 +01008092 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008093 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8094 return true;
8095 }
8096
8097 // has known usage?
8098 switch (paa->usage) {
8099 case AUDIO_USAGE_UNKNOWN:
8100 case AUDIO_USAGE_MEDIA:
8101 case AUDIO_USAGE_VOICE_COMMUNICATION:
8102 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8103 case AUDIO_USAGE_ALARM:
8104 case AUDIO_USAGE_NOTIFICATION:
8105 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8106 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8107 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8108 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8109 case AUDIO_USAGE_NOTIFICATION_EVENT:
8110 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8111 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8112 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8113 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008114 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008115 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008116 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008117 case AUDIO_USAGE_EMERGENCY:
8118 case AUDIO_USAGE_SAFETY:
8119 case AUDIO_USAGE_VEHICLE_STATUS:
8120 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008121 break;
8122 default:
8123 return false;
8124 }
8125 return true;
8126}
8127
François Gaffie2110e042015-03-24 08:41:51 +01008128audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8129{
8130 return mEngine->getForceUse(usage);
8131}
8132
Eric Laurent96d1dda2022-03-14 17:14:19 +01008133bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008134 return isStateInCall(mEngine->getPhoneState());
8135}
8136
Eric Laurent96d1dda2022-03-14 17:14:19 +01008137bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008138 return is_state_in_call(state);
8139}
8140
Eric Laurentf9cccec2022-11-16 19:12:00 +01008141bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008142 audio_mode_t mode = mEngine->getPhoneState();
8143 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008144 || (mode == AUDIO_MODE_CALL_SCREEN)
8145 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008146}
8147
Eric Laurentf9cccec2022-11-16 19:12:00 +01008148bool AudioPolicyManager::isInCallOrScreening() const {
8149 audio_mode_t mode = mEngine->getPhoneState();
8150 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8151}
8152
Eric Laurentd60560a2015-04-10 11:31:20 -07008153void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8154{
8155 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008156 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008157 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008158 sourceDesc->sinkDevice()->equals(deviceDesc))
8159 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008160 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008161 }
8162 }
8163
8164 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8165 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8166 bool release = false;
8167 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8168 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8169 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8170 source->ext.device.type == deviceDesc->type()) {
8171 release = true;
8172 }
8173 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008174 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008175 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8176 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8177 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008178 sink->ext.device.type == deviceDesc->type() &&
8179 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8180 || strncmp(sink->ext.device.address, address,
8181 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008182 release = true;
8183 }
8184 }
8185 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008186 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8187 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008188 }
8189 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008190
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008191 mInputs.clearSessionRoutesForDevice(deviceDesc);
8192
Francois Gaffie716e1432019-01-14 16:58:59 +01008193 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008194}
8195
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008196void AudioPolicyManager::modifySurroundFormats(
8197 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008198 std::unordered_set<audio_format_t> enforcedSurround(
8199 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008200 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008201 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008202 allSurround.insert(pair.first);
8203 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8204 }
Phil Burk09bc4612016-02-24 15:58:15 -08008205
8206 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8207 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008208 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008209 // This is the resulting set of formats depending on the surround mode:
8210 // 'all surround' = allSurround
8211 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8212 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8213 // 'manual surround' = mManualSurroundFormats
8214 // AUTO: formats v 'enforced surround'
8215 // ALWAYS: formats v 'all surround' v 'enforced surround'
8216 // NEVER: formats ^ 'non-surround'
8217 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008218
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008219 std::unordered_set<audio_format_t> formatSet;
8220 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8221 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008222 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008223 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008224 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008225 formatSet.insert(*formatIter);
8226 }
8227 }
8228 } else {
8229 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8230 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008231 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008232
jiabin81772902018-04-02 17:52:27 -07008233 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008234 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008235 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8236 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8237 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008238 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008239 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8240 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8241 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008242 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008243 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008244 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008245 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008246 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008247 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008248}
8249
jiabin06e4bab2019-07-29 10:13:34 -07008250void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8251 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008252 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8253 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8254
8255 // If NEVER, then remove support for channelMasks > stereo.
8256 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008257 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8258 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008259 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008260 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008261 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008262 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008263 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008264 }
8265 }
jiabin81772902018-04-02 17:52:27 -07008266 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8267 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8268 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008269 bool supports5dot1 = false;
8270 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008271 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008272 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8273 supports5dot1 = true;
8274 break;
8275 }
8276 }
8277 // If not then add 5.1 support.
8278 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008279 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008280 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008281 }
Phil Burk09bc4612016-02-24 15:58:15 -08008282 }
8283}
8284
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008285void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008286 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008287 const sp<IOProfile>& profile) {
8288 if (!profile->hasDynamicAudioProfile()) {
8289 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008290 }
François Gaffie112b0af2015-11-19 16:13:25 +01008291
jiabin12537fc2023-10-12 17:56:08 +00008292 audio_port_v7 devicePort;
8293 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008294
jiabin12537fc2023-10-12 17:56:08 +00008295 audio_port_v7 mixPort;
8296 profile->toAudioPort(&mixPort);
8297 mixPort.ext.mix.handle = ioHandle;
8298
8299 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8300 if (status != NO_ERROR) {
8301 ALOGE("%s failed to query the attributes of the mix port", __func__);
8302 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008303 }
jiabin12537fc2023-10-12 17:56:08 +00008304
8305 std::set<audio_format_t> supportedFormats;
8306 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8307 supportedFormats.insert(mixPort.audio_profiles[i].format);
8308 }
8309 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8310 mReportedFormatsMap[devDesc] = formats;
8311
8312 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8313 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8314 modifySurroundFormats(devDesc, &formats);
8315 size_t modifiedNumProfiles = 0;
8316 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8317 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8318 formats.end()) {
8319 // Skip the format that is not present after modifying surround formats.
8320 continue;
8321 }
8322 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8323 sizeof(struct audio_profile));
8324 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8325 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8326 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8327 modifySurroundChannelMasks(&channels);
8328 std::copy(channels.begin(), channels.end(),
8329 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8330 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8331 }
8332 mixPort.num_audio_profiles = modifiedNumProfiles;
8333 }
8334 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008335}
Eric Laurentd60560a2015-04-10 11:31:20 -07008336
Mikhail Naganovdc769682018-05-04 15:34:08 -07008337status_t AudioPolicyManager::installPatch(const char *caller,
8338 audio_patch_handle_t *patchHandle,
8339 AudioIODescriptorInterface *ioDescriptor,
8340 const struct audio_patch *patch,
8341 int delayMs)
8342{
8343 ssize_t index = mAudioPatches.indexOfKey(
8344 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8345 *patchHandle : ioDescriptor->getPatchHandle());
8346 sp<AudioPatch> patchDesc;
8347 status_t status = installPatch(
8348 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8349 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008350 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008351 }
8352 return status;
8353}
8354
8355status_t AudioPolicyManager::installPatch(const char *caller,
8356 ssize_t index,
8357 audio_patch_handle_t *patchHandle,
8358 const struct audio_patch *patch,
8359 int delayMs,
8360 uid_t uid,
8361 sp<AudioPatch> *patchDescPtr)
8362{
8363 sp<AudioPatch> patchDesc;
8364 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8365 if (index >= 0) {
8366 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008367 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008368 }
8369
8370 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8371 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8372 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8373 if (status == NO_ERROR) {
8374 if (index < 0) {
8375 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008376 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008377 } else {
8378 patchDesc->mPatch = *patch;
8379 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008380 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008381 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008382 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008383 }
8384 nextAudioPortGeneration();
8385 mpClientInterface->onAudioPatchListUpdate();
8386 }
8387 if (patchDescPtr) *patchDescPtr = patchDesc;
8388 return status;
8389}
8390
jiabinbce0c1d2020-10-05 11:20:18 -07008391bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8392{
8393 const TrackClientVector activeClients = output->getActiveClients();
8394 if (activeClients.empty()) {
8395 return true;
8396 }
8397 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8398 if (index < 0) {
8399 ALOGE("%s, no audio patch found while there are active clients on output %d",
8400 __func__, output->getId());
8401 return false;
8402 }
8403 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8404 DeviceVector routedDevices;
8405 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8406 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8407 patchDesc->mPatch.sinks[i].id);
8408 if (device == nullptr) {
8409 ALOGE("%s, no audio device found with id(%d)",
8410 __func__, patchDesc->mPatch.sinks[i].id);
8411 return false;
8412 }
8413 routedDevices.add(device);
8414 }
8415 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008416 if (client->isInvalid()) {
8417 // No need to take care about invalidated clients.
8418 continue;
8419 }
jiabinbce0c1d2020-10-05 11:20:18 -07008420 sp<DeviceDescriptor> preferredDevice =
8421 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8422 if (mEngine->getOutputDevicesForAttributes(
8423 client->attributes(), preferredDevice, false) == routedDevices) {
8424 return false;
8425 }
8426 }
8427 return true;
8428}
8429
8430sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008431 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008432 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8433 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008434{
8435 for (const auto& device : devices) {
8436 // TODO: This should be checking if the profile supports the device combo.
8437 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008438 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8439 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008440 return nullptr;
8441 }
8442 }
8443 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8444 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008445 status_t status = desc->open(halConfig, mixerConfig, devices,
8446 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008447 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008448 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008449 return nullptr;
8450 }
jiabin14b50cc2023-12-13 19:01:52 +00008451 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8452 auto portConfig = desc->getConfig();
8453 for (const auto& device : devices) {
8454 device->setPreferredConfig(&portConfig);
8455 }
8456 }
jiabinbce0c1d2020-10-05 11:20:18 -07008457
8458 // Here is where the out_set_parameters() for card & device gets called
8459 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8460 const audio_devices_t deviceType = device->type();
8461 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008462 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008463 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8464 mpClientInterface->setParameters(output, String8(param));
8465 free(param);
8466 }
jiabin12537fc2023-10-12 17:56:08 +00008467 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008468 if (!profile->hasValidAudioProfile()) {
8469 ALOGW("%s() missing param", __func__);
8470 desc->close();
8471 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008472 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8473 // Reopen the output with the best audio profile picked by APM when the profile supports
8474 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008475 desc->close();
8476 output = AUDIO_IO_HANDLE_NONE;
8477 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8478 profile->pickAudioProfile(
8479 config.sample_rate, config.channel_mask, config.format);
8480 config.offload_info.sample_rate = config.sample_rate;
8481 config.offload_info.channel_mask = config.channel_mask;
8482 config.offload_info.format = config.format;
8483
jiabina84c3d32022-12-02 18:59:55 +00008484 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008485 if (status != NO_ERROR) {
8486 return nullptr;
8487 }
8488 }
8489
8490 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008491
baek.kim -61c20122022-07-27 10:05:32 +00008492 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8493 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8494
jiabinbce0c1d2020-10-05 11:20:18 -07008495 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8496 sp<AudioPolicyMix> policyMix;
8497 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8498 policyMix->setOutput(desc);
8499 desc->mPolicyMix = policyMix;
8500 } else {
8501 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008502 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008503 }
8504
baek.kim -61c20122022-07-27 10:05:32 +00008505 } else if (hasPrimaryOutput() && speaker != nullptr
8506 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008507 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8508 // no duplicated output for:
8509 // - direct outputs
8510 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008511 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008512 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8513
8514 //TODO: configure audio effect output stage here
8515
8516 // open a duplicating output thread for the new output and the primary output
8517 sp<SwAudioOutputDescriptor> dupOutputDesc =
8518 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8519 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8520 if (status == NO_ERROR) {
8521 // add duplicated output descriptor
8522 addOutput(duplicatedOutput, dupOutputDesc);
8523 } else {
8524 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8525 mPrimaryOutput->mIoHandle, output);
8526 desc->close();
8527 removeOutput(output);
8528 nextAudioPortGeneration();
8529 return nullptr;
8530 }
8531 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008532 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8533 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8534 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008535 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008536 }
jiabinbce0c1d2020-10-05 11:20:18 -07008537 return desc;
8538}
8539
jiabinf1c73972022-04-14 16:28:52 -07008540status_t AudioPolicyManager::getDevicesForAttributes(
8541 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8542 // Devices are determined in the following precedence:
8543 //
8544 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8545 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8546 //
8547 // If no such dynamic policy then
8548 // 2) Devices containing an active client using setPreferredDevice
8549 // with same strategy as the attributes.
8550 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8551 //
8552 // If no corresponding active client with setPreferredDevice then
8553 // 3) Devices associated with the strategy determined by the attributes
8554 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8555 //
8556 // See related getOutputForAttrInt().
8557
8558 // check dynamic policies but only for primary descriptors (secondary not used for audible
8559 // audio routing, only used for duplication for playback capture)
8560 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008561 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008562 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008563 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8564 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8565 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008566 if (status != OK) {
8567 return status;
8568 }
8569
8570 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8571 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8572 // as they are unaffected by device/stream volume
8573 // (per SwAudioOutputDescriptor::isFixedVolume()).
8574 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8575 ) {
8576 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8577 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8578 devices.add(deviceDesc);
8579 } else {
8580 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8581 // which selects setPreferredDevice if active. This means forVolume call
8582 // will take an active setPreferredDevice, if such exists.
8583
8584 devices = mEngine->getOutputDevicesForAttributes(
8585 attr, nullptr /* preferredDevice */, false /* fromCache */);
8586 }
8587
8588 if (forVolume) {
8589 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8590 // for single volume control in AudioService (such relationship should exist if
8591 // SPEAKER_SAFE is present).
8592 //
8593 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8594 DeviceVector speakerSafeDevices =
8595 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8596 if (!speakerSafeDevices.isEmpty()) {
8597 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8598 devices.remove(speakerSafeDevices);
8599 }
8600 }
8601
8602 return NO_ERROR;
8603}
8604
8605status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8606 AudioProfileVector& audioProfiles,
8607 uint32_t flags,
8608 bool isInput) {
8609 for (const auto& hwModule : mHwModules) {
8610 // the MSD module checks for different conditions
8611 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8612 continue;
8613 }
8614 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8615 : hwModule->getOutputProfiles();
8616 for (const auto& profile : ioProfiles) {
8617 if (!profile->areAllDevicesSupported(devices) ||
8618 !profile->isCompatibleProfileForFlags(
8619 flags, false /*exactMatchRequiredForInputFlags*/)) {
8620 continue;
8621 }
8622 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8623 }
8624 }
8625
8626 if (!isInput) {
8627 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8628 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8629 if (msdModule != nullptr) {
8630 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8631 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8632 for (const auto &profile: msdModule->getOutputProfiles()) {
8633 if (!profile->asAudioPort()->isDirectOutput()) {
8634 continue;
8635 }
8636 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8637 }
8638 } else {
8639 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8640 }
8641 }
8642 }
8643
8644 return NO_ERROR;
8645}
8646
jiabin3ff8d7d2022-12-13 06:27:44 +00008647sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8648 const audio_config_t *config,
8649 audio_output_flags_t flags,
8650 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008651 closeOutput(outputDesc->mIoHandle);
8652 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8653 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8654 if (preferredOutput == nullptr) {
8655 ALOGE("%s failed to reopen output device=%d, caller=%s",
8656 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008657 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008658 return preferredOutput;
8659}
8660
8661void AudioPolicyManager::reopenOutputsWithDevices(
8662 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8663 for (const auto& [output, devices] : outputsToReopen) {
8664 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8665 closeOutput(output);
8666 openOutputWithProfileAndDevice(desc->mProfile, devices);
8667 }
jiabina84c3d32022-12-02 18:59:55 +00008668}
8669
jiabinc44b3462022-12-08 12:52:31 -08008670PortHandleVector AudioPolicyManager::getClientsForStream(
8671 audio_stream_type_t streamType) const {
8672 PortHandleVector clients;
8673 for (size_t i = 0; i < mOutputs.size(); ++i) {
8674 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8675 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8676 }
8677 return clients;
8678}
8679
8680void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8681 PortHandleVector clients;
8682 for (auto stream : streams) {
8683 PortHandleVector clientsForStream = getClientsForStream(stream);
8684 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8685 }
8686 mpClientInterface->invalidateTracks(clients);
8687}
8688
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008689} // namespace android