blob: 24744a605e1217abb71bc58fd712a3cb6951d299 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
Eric Laurent7ee14372024-01-23 11:57:46 +010021// to enable VERBOSE logging dynamically.
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090022// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
Atneya Nairb16666a2023-12-11 20:18:33 -080045#include <com_android_media_audioserver.h>
Glenn Kasten76a13442020-07-01 12:10:59 -070046#include <cutils/bitops.h>
Eric Laurente552edb2014-03-10 17:42:56 -070047#include <cutils/properties.h>
Eric Laurent3b73df72014-03-11 09:06:29 -070048#include <media/AudioParameter.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070049#include <policy.h>
Andy Hung4ef19fa2018-05-15 19:35:29 -070050#include <private/android_filesystem_config.h>
Mikhail Naganovcbc8f612016-10-11 18:05:13 -070051#include <system/audio.h>
Mikhail Naganov27cf37c2020-04-14 14:47:01 -070052#include <system/audio_config.h>
jiabinebb6af42020-06-09 17:31:17 -070053#include <system/audio_effects/effect_hapticgenerator.h>
Mikhail Naganov946c0032020-10-21 13:04:58 -070054#include <utils/Log.h>
55
Eric Laurentd4692962014-05-05 18:13:44 -070056#include "AudioPolicyManager.h"
François Gaffiea8ecc2c2015-11-09 16:10:40 +010057#include "TypeConverter.h"
Eric Laurente552edb2014-03-10 17:42:56 -070058
Eric Laurent3b73df72014-03-11 09:06:29 -070059namespace android {
Eric Laurente552edb2014-03-10 17:42:56 -070060
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010061using android::media::audio::common::AudioDevice;
62using android::media::audio::common::AudioDeviceAddress;
63using android::media::audio::common::AudioPortDeviceExt;
64using android::media::audio::common::AudioPortExt;
Svet Ganov3e5f14f2021-05-13 22:51:08 +000065using content::AttributionSourceState;
Philip P. Moltmannbda45752020-07-17 16:41:18 -070066
Eric Laurentdc462862016-07-19 12:29:53 -070067//FIXME: workaround for truncated touch sounds
68// to be removed when the problem is handled by system UI
69#define TOUCH_SOUND_FIXED_DELAY_MS 100
Jean-Michel Trivi719a9872017-08-05 13:51:35 -070070
71// Largest difference in dB on earpiece in call between the voice volume and another
72// media / notification / system volume.
73constexpr float IN_CALL_EARPIECE_HEADROOM_DB = 3.f;
74
jiabin06e4bab2019-07-29 10:13:34 -070075template <typename T>
76bool operator== (const SortedVector<T> &left, const SortedVector<T> &right)
77{
78 if (left.size() != right.size()) {
79 return false;
80 }
81 for (size_t index = 0; index < right.size(); index++) {
82 if (left[index] != right[index]) {
83 return false;
84 }
85 }
86 return true;
87}
88
89template <typename T>
90bool operator!= (const SortedVector<T> &left, const SortedVector<T> &right)
91{
92 return !(left == right);
93}
94
Eric Laurente552edb2014-03-10 17:42:56 -070095// ----------------------------------------------------------------------------
96// AudioPolicyInterface implementation
97// ----------------------------------------------------------------------------
98
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010099status_t AudioPolicyManager::setDeviceConnectionState(audio_policy_dev_state_t state,
100 const android::media::audio::common::AudioPort& port, audio_format_t encodedFormat) {
101 status_t status = setDeviceConnectionStateInt(state, port, encodedFormat);
jiabina7b43792018-02-15 16:04:46 -0800102 nextAudioPortGeneration();
103 return status;
Eric Laurentc73ca6e2014-12-12 14:34:22 -0800104}
105
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100106status_t AudioPolicyManager::setDeviceConnectionState(audio_devices_t device,
107 audio_policy_dev_state_t state,
108 const char* device_address,
109 const char* device_name,
110 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800111 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100112 if (status_t status = deviceToAudioPort(device, device_address, device_name, &aidlPort);
113 status == OK) {
114 return setDeviceConnectionState(state, aidlPort.hal, encodedFormat);
115 } else {
116 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
117 return status;
118 }
119}
120
François Gaffie11d30102018-11-02 16:09:09 +0100121void AudioPolicyManager::broadcastDeviceConnectionState(const sp<DeviceDescriptor> &device,
jiabinc0048632023-04-27 22:04:31 +0000122 media::DeviceConnectedState state)
François Gaffie44481e72016-04-20 07:49:57 +0200123{
Mikhail Naganov516d3982022-02-01 23:53:59 +0000124 audio_port_v7 devicePort;
125 device->toAudioPort(&devicePort);
jiabinc0048632023-04-27 22:04:31 +0000126 if (status_t status = mpClientInterface->setDeviceConnectedState(&devicePort, state);
Mikhail Naganov516d3982022-02-01 23:53:59 +0000127 status != OK) {
jiabinc0048632023-04-27 22:04:31 +0000128 ALOGE("Error %d while setting connected state for device %s", state,
Mikhail Naganov516d3982022-02-01 23:53:59 +0000129 device->getDeviceTypeAddr().toString(false).c_str());
130 }
François Gaffie44481e72016-04-20 07:49:57 +0200131}
132
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100133status_t AudioPolicyManager::setDeviceConnectionStateInt(
134 audio_policy_dev_state_t state, const android::media::audio::common::AudioPort& port,
135 audio_format_t encodedFormat) {
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100136 if (port.ext.getTag() != AudioPortExt::device) {
137 return BAD_VALUE;
138 }
139 audio_devices_t device_type;
140 std::string device_address;
141 if (status_t status = aidl2legacy_AudioDevice_audio_device(
142 port.ext.get<AudioPortExt::device>().device, &device_type, &device_address);
143 status != OK) {
144 return status;
145 };
146 const char* device_name = port.name.c_str();
147 // connect/disconnect only 1 device at a time
148 if (!audio_is_output_device(device_type) && !audio_is_input_device(device_type))
149 return BAD_VALUE;
150
151 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
152 device_type, device_address.c_str(), device_name, encodedFormat,
153 state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
Mikhail Naganovddc5f312022-06-11 00:47:52 +0000154 if (device == nullptr) {
155 return INVALID_OPERATION;
156 }
157 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
158 device->setExtraAudioDescriptors(port.extraAudioDescriptors);
159 }
160 return setDeviceConnectionStateInt(device, state);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100161}
162
François Gaffie11d30102018-11-02 16:09:09 +0100163status_t AudioPolicyManager::setDeviceConnectionStateInt(audio_devices_t deviceType,
Eric Laurenta1d525f2015-01-29 13:36:45 -0800164 audio_policy_dev_state_t state,
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100165 const char* device_address,
166 const char* device_name,
167 audio_format_t encodedFormat) {
Atneya Nair638a6e42022-12-18 16:45:15 -0800168 media::AudioPortFw aidlPort;
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100169 if (status_t status = deviceToAudioPort(deviceType, device_address, device_name, &aidlPort);
170 status == OK) {
171 return setDeviceConnectionStateInt(state, aidlPort.hal, encodedFormat);
172 } else {
173 ALOGE("Failed to convert to AudioPort Parcelable: %s", statusToString(status).c_str());
174 return status;
175 }
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700176}
Paul McLeane743a472015-01-28 11:07:31 -0800177
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700178status_t AudioPolicyManager::setDeviceConnectionStateInt(const sp<DeviceDescriptor> &device,
179 audio_policy_dev_state_t state)
180{
Eric Laurente552edb2014-03-10 17:42:56 -0700181 // handle output devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700182 if (audio_is_output_device(device->type())) {
Eric Laurentd4692962014-05-05 18:13:44 -0700183 SortedVector <audio_io_handle_t> outputs;
184
François Gaffie11d30102018-11-02 16:09:09 +0100185 ssize_t index = mAvailableOutputDevices.indexOf(device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700186
Eric Laurente552edb2014-03-10 17:42:56 -0700187 // save a copy of the opened output descriptors before any output is opened or closed
188 // by checkOutputsForDevice(). This will be needed by checkOutputForAllStrategies()
189 mPreviousOutputs = mOutputs;
Eric Laurent96d1dda2022-03-14 17:14:19 +0100190
191 bool wasLeUnicastActive = isLeUnicastActive();
192
Eric Laurente552edb2014-03-10 17:42:56 -0700193 switch (state)
194 {
195 // handle output device connection
Eric Laurent3ae5f312015-02-03 17:12:08 -0800196 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700197 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100198 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700199 return INVALID_OPERATION;
200 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800201 ALOGV("%s() connecting device %s format %x",
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700202 __func__, device->toString().c_str(), device->getEncodedFormat());
Eric Laurente552edb2014-03-10 17:42:56 -0700203
Eric Laurente552edb2014-03-10 17:42:56 -0700204 // register new device as available
Francois Gaffie993f3902019-04-10 15:39:27 +0200205 if (mAvailableOutputDevices.add(device) < 0) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700206 return NO_MEMORY;
Eric Laurente552edb2014-03-10 17:42:56 -0700207 }
208
François Gaffie44481e72016-04-20 07:49:57 +0200209 // Before checking outputs, broadcast connect event to allow HAL to retrieve dynamic
210 // parameters on newly connected devices (instead of opening the outputs...)
jiabinc0048632023-04-27 22:04:31 +0000211 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200212
François Gaffie11d30102018-11-02 16:09:09 +0100213 if (checkOutputsForDevice(device, state, outputs) != NO_ERROR) {
214 mAvailableOutputDevices.remove(device);
François Gaffie44481e72016-04-20 07:49:57 +0200215
Francois Gaffie716e1432019-01-14 16:58:59 +0100216 mHwModules.cleanUpForDevice(device);
217
jiabinc0048632023-04-27 22:04:31 +0000218 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700219 return INVALID_OPERATION;
220 }
François Gaffie2110e042015-03-24 08:41:51 +0100221
jiabin1c4794b2020-05-05 10:08:05 -0700222 // Populate encapsulation information when a output device is connected.
223 device->setEncapsulationInfoFromHal(mpClientInterface);
224
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -0700225 // outputs should never be empty here
226 ALOG_ASSERT(outputs.size() != 0, "setDeviceConnectionState():"
227 "checkOutputsForDevice() returned no outputs but status OK");
François Gaffie11d30102018-11-02 16:09:09 +0100228 ALOGV("%s() checkOutputsForDevice() returned %zu outputs", __func__, outputs.size());
Eric Laurent3ae5f312015-02-03 17:12:08 -0800229
Eric Laurent3ae5f312015-02-03 17:12:08 -0800230 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700231 // handle output device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700232 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700233 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100234 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700235 return INVALID_OPERATION;
236 }
237
François Gaffie11d30102018-11-02 16:09:09 +0100238 ALOGV("%s() disconnecting output device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700239
jiabinc0048632023-04-27 22:04:31 +0000240 // Notify the HAL to prepare to disconnect device
241 broadcastDeviceConnectionState(
242 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700243
Eric Laurente552edb2014-03-10 17:42:56 -0700244 // remove device from available output devices
François Gaffie11d30102018-11-02 16:09:09 +0100245 mAvailableOutputDevices.remove(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700246
Francois Gaffieba2cf0f2018-12-12 16:40:25 +0100247 mOutputs.clearSessionRoutesForDevice(device);
248
François Gaffie11d30102018-11-02 16:09:09 +0100249 checkOutputsForDevice(device, state, outputs);
François Gaffie2110e042015-03-24 08:41:51 +0100250
jiabinc0048632023-04-27 22:04:31 +0000251 // Send Disconnect to HALs
252 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
253
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800254 // Reset active device codec
255 device->setEncodedFormat(AUDIO_FORMAT_DEFAULT);
256
Kriti Dangef6be8f2020-11-05 11:58:19 +0100257 // remove device from mReportedFormatsMap cache
258 mReportedFormatsMap.erase(device);
259
jiabina84c3d32022-12-02 18:59:55 +0000260 // remove preferred mixer configurations
261 mPreferredMixerAttrInfos.erase(device->getId());
262
Eric Laurente552edb2014-03-10 17:42:56 -0700263 } break;
264
265 default:
François Gaffie11d30102018-11-02 16:09:09 +0100266 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700267 return BAD_VALUE;
268 }
269
Eric Laurent736a1022019-03-27 18:28:46 -0700270 // Propagate device availability to Engine
271 setEngineDeviceConnectionState(device, state);
272
Eric Laurentae970022019-01-29 14:25:04 -0800273 // No need to evaluate playback routing when connecting a remote submix
274 // output device used by a dynamic policy of type recorder as no
275 // playback use case is affected.
276 bool doCheckForDeviceAndOutputChanges = true;
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700277 if (device->type() == AUDIO_DEVICE_OUT_REMOTE_SUBMIX && device->address() != "0") {
Eric Laurentae970022019-01-29 14:25:04 -0800278 for (audio_io_handle_t output : outputs) {
279 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Mikhail Naganovbfac5832019-03-05 16:55:28 -0800280 sp<AudioPolicyMix> policyMix = desc->mPolicyMix.promote();
281 if (policyMix != nullptr
282 && policyMix->mMixType == MIX_TYPE_RECORDERS
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +0000283 && device->address() == policyMix->mDeviceAddress.c_str()) {
Eric Laurentae970022019-01-29 14:25:04 -0800284 doCheckForDeviceAndOutputChanges = false;
285 break;
286 }
287 }
288 }
289
290 auto checkCloseOutputs = [&]() {
Mikhail Naganov37977152018-07-11 15:54:44 -0700291 // outputs must be closed after checkOutputForAllStrategies() is executed
292 if (!outputs.isEmpty()) {
293 for (audio_io_handle_t output : outputs) {
294 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
François Gaffie11d30102018-11-02 16:09:09 +0100295 // close unused outputs after device disconnection or direct outputs that have
296 // been opened by checkOutputsForDevice() to query dynamic parameters
Eric Laurente191d1b2022-04-15 11:59:25 +0200297 // "outputs" vector never contains duplicated outputs
Eric Laurentcad6c0d2021-07-13 15:12:39 +0200298 if ((state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE)
299 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != 0) &&
Eric Laurente191d1b2022-04-15 11:59:25 +0200300 (desc->mDirectOpenCount == 0))
301 || (((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) &&
302 !isOutputOnlyAvailableRouteToSomeDevice(desc))) {
Francois Gaffieff1eb522020-05-06 18:37:04 +0200303 clearAudioSourcesForOutput(output);
Mikhail Naganov37977152018-07-11 15:54:44 -0700304 closeOutput(output);
305 }
Eric Laurente552edb2014-03-10 17:42:56 -0700306 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700307 // check A2DP again after closing A2DP output to reset mA2dpSuspended if needed
308 return true;
Eric Laurente552edb2014-03-10 17:42:56 -0700309 }
Mikhail Naganov37977152018-07-11 15:54:44 -0700310 return false;
Eric Laurentae970022019-01-29 14:25:04 -0800311 };
312
313 if (doCheckForDeviceAndOutputChanges) {
314 checkForDeviceAndOutputChanges(checkCloseOutputs);
315 } else {
316 checkCloseOutputs();
317 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100318 (void)updateCallRouting(false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +0100319 const DeviceVector msdOutDevices = getMsdAudioOutDevices();
jiabinbce0c1d2020-10-05 11:20:18 -0700320 const DeviceVector activeMediaDevices =
321 mEngine->getActiveMediaDevices(mAvailableOutputDevices);
jiabin3ff8d7d2022-12-13 06:27:44 +0000322 std::map<audio_io_handle_t, DeviceVector> outputsToReopenWithDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700323 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700324 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Jaideep Sharma89b5b852020-11-23 16:41:33 +0530325 if (desc->isActive() && ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
326 (desc != mPrimaryOutput))) {
François Gaffie11d30102018-11-02 16:09:09 +0100327 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700328 // do not force device change on duplicated output because if device is 0, it will
329 // also force a device 0 for the two outputs it is duplicated to which may override
330 // a valid device selection on those outputs.
François Gaffie11d30102018-11-02 16:09:09 +0100331 bool force = (msdOutDevices.isEmpty() || msdOutDevices != desc->devices())
Mikhail Naganov15be9d22017-11-08 14:18:13 +1100332 && !desc->isDuplicated()
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700333 && (!device_distinguishes_on_address(device->type())
Eric Laurentc2730ba2014-07-20 15:47:07 -0700334 // always force when disconnecting (a non-duplicated device)
335 || (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE));
jiabin3ff8d7d2022-12-13 06:27:44 +0000336 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
337 // If the device is using preferred mixer attributes, the output need to reopen
338 // with default configuration when the new selected devices are different from
339 // current routing devices
340 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), newDevices);
341 continue;
342 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530343 setOutputDevices(__func__, desc, newDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700344 }
jiabinbce0c1d2020-10-05 11:20:18 -0700345 if (!desc->isDuplicated() && desc->mProfile->hasDynamicAudioProfile() &&
jiabin498d2152021-04-02 00:26:46 +0000346 !activeMediaDevices.empty() && desc->devices() != activeMediaDevices &&
jiabinbce0c1d2020-10-05 11:20:18 -0700347 desc->supportsDevicesForPlayback(activeMediaDevices)) {
348 // Reopen the output to query the dynamic profiles when there is not active
349 // clients or all active clients will be rerouted. Otherwise, set the flag
350 // `mPendingReopenToQueryProfiles` in the SwOutputDescriptor so that the output
351 // can be reopened to query dynamic profiles when all clients are inactive.
352 if (areAllActiveTracksRerouted(desc)) {
jiabin3ff8d7d2022-12-13 06:27:44 +0000353 outputsToReopenWithDevices.emplace(mOutputs.keyAt(i), activeMediaDevices);
jiabinbce0c1d2020-10-05 11:20:18 -0700354 } else {
355 desc->mPendingReopenToQueryProfiles = true;
356 }
357 }
358 if (!desc->supportsDevicesForPlayback(activeMediaDevices)) {
359 // Clear the flag that previously set for re-querying profiles.
360 desc->mPendingReopenToQueryProfiles = false;
361 }
362 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000363 reopenOutputsWithDevices(outputsToReopenWithDevices);
Eric Laurente552edb2014-03-10 17:42:56 -0700364
Eric Laurentd60560a2015-04-10 11:31:20 -0700365 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100366 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700367 }
368
Eric Laurent96d1dda2022-03-14 17:14:19 +0100369 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, 0);
370
Eric Laurent72aa32f2014-05-30 18:51:48 -0700371 mpClientInterface->onAudioPortListUpdate();
Eric Laurentb71e58b2014-05-29 16:08:11 -0700372 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700373 } // end if is output device
374
Eric Laurente552edb2014-03-10 17:42:56 -0700375 // handle input devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -0700376 if (audio_is_input_device(device->type())) {
François Gaffie11d30102018-11-02 16:09:09 +0100377 ssize_t index = mAvailableInputDevices.indexOf(device);
Eric Laurente552edb2014-03-10 17:42:56 -0700378 switch (state)
379 {
380 // handle input device connection
Eric Laurent3b73df72014-03-11 09:06:29 -0700381 case AUDIO_POLICY_DEVICE_STATE_AVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700382 if (index >= 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100383 ALOGW("%s() device already connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700384 return INVALID_OPERATION;
385 }
Eric Laurent0dd51852019-04-19 18:18:58 -0700386
387 if (mAvailableInputDevices.add(device) < 0) {
388 return NO_MEMORY;
389 }
390
François Gaffie44481e72016-04-20 07:49:57 +0200391 // Before checking intputs, broadcast connect event to allow HAL to retrieve dynamic
392 // parameters on newly connected devices (instead of opening the inputs...)
jiabinc0048632023-04-27 22:04:31 +0000393 broadcastDeviceConnectionState(device, media::DeviceConnectedState::CONNECTED);
François Gaffie44481e72016-04-20 07:49:57 +0200394
Eric Laurent0dd51852019-04-19 18:18:58 -0700395 if (checkInputsForDevice(device, state) != NO_ERROR) {
396 mAvailableInputDevices.remove(device);
397
jiabinc0048632023-04-27 22:04:31 +0000398 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
Francois Gaffie716e1432019-01-14 16:58:59 +0100399
400 mHwModules.cleanUpForDevice(device);
401
Eric Laurentd4692962014-05-05 18:13:44 -0700402 return INVALID_OPERATION;
403 }
404
Eric Laurentd4692962014-05-05 18:13:44 -0700405 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700406
407 // handle input device disconnection
Eric Laurent3b73df72014-03-11 09:06:29 -0700408 case AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE: {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700409 if (index < 0) {
François Gaffie11d30102018-11-02 16:09:09 +0100410 ALOGW("%s() device not connected: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700411 return INVALID_OPERATION;
412 }
Paul McLean5c477aa2014-08-20 16:47:57 -0700413
François Gaffie11d30102018-11-02 16:09:09 +0100414 ALOGV("%s() disconnecting input device %s", __func__, device->toString().c_str());
Paul McLean5c477aa2014-08-20 16:47:57 -0700415
jiabinc0048632023-04-27 22:04:31 +0000416 // Notify the HAL to prepare to disconnect device
417 broadcastDeviceConnectionState(
418 device, media::DeviceConnectedState::PREPARE_TO_DISCONNECT);
Paul McLean5c477aa2014-08-20 16:47:57 -0700419
François Gaffie11d30102018-11-02 16:09:09 +0100420 mAvailableInputDevices.remove(device);
Eric Laurent0dd51852019-04-19 18:18:58 -0700421
422 checkInputsForDevice(device, state);
Kriti Dangef6be8f2020-11-05 11:58:19 +0100423
jiabinc0048632023-04-27 22:04:31 +0000424 // Set Disconnect to HALs
425 broadcastDeviceConnectionState(device, media::DeviceConnectedState::DISCONNECTED);
426
Kriti Dangef6be8f2020-11-05 11:58:19 +0100427 // remove device from mReportedFormatsMap cache
428 mReportedFormatsMap.erase(device);
Eric Laurentd4692962014-05-05 18:13:44 -0700429 } break;
Eric Laurente552edb2014-03-10 17:42:56 -0700430
431 default:
François Gaffie11d30102018-11-02 16:09:09 +0100432 ALOGE("%s() invalid state: %x", __func__, state);
Eric Laurente552edb2014-03-10 17:42:56 -0700433 return BAD_VALUE;
434 }
435
Eric Laurent736a1022019-03-27 18:28:46 -0700436 // Propagate device availability to Engine
437 setEngineDeviceConnectionState(device, state);
438
Eric Laurent0dd51852019-04-19 18:18:58 -0700439 checkCloseInputs();
Eric Laurent5f5fca52016-08-04 11:48:57 -0700440 // As the input device list can impact the output device selection, update
441 // getDeviceForStrategy() cache
442 updateDevicesAndOutputs();
Eric Laurente552edb2014-03-10 17:42:56 -0700443
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100444 (void)updateCallRouting(false /*fromCache*/);
Francois Gaffiea0e5c992020-09-29 16:05:07 +0200445 // Reconnect Audio Source
446 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
447 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
448 checkAudioSourceForAttributes(attributes);
449 }
Eric Laurentd60560a2015-04-10 11:31:20 -0700450 if (state == AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE) {
François Gaffie11d30102018-11-02 16:09:09 +0100451 cleanUpForDevice(device);
Eric Laurentd60560a2015-04-10 11:31:20 -0700452 }
453
Eric Laurentb52c1522014-05-20 11:27:36 -0700454 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -0700455 return NO_ERROR;
Eric Laurentd4692962014-05-05 18:13:44 -0700456 } // end if is input device
Eric Laurente552edb2014-03-10 17:42:56 -0700457
François Gaffie11d30102018-11-02 16:09:09 +0100458 ALOGW("%s() invalid device: %s", __func__, device->toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -0700459 return BAD_VALUE;
460}
461
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100462status_t AudioPolicyManager::deviceToAudioPort(audio_devices_t device, const char* device_address,
463 const char* device_name,
Atneya Nair638a6e42022-12-18 16:45:15 -0800464 media::AudioPortFw* aidlPort) {
Andy Hung5b9a6112023-08-09 19:56:57 -0700465 const auto devDescr = sp<DeviceDescriptorBase>::make(device, device_address);
466 devDescr->setName(device_name);
467 return devDescr->writeToParcelable(aidlPort);
Nathalie Le Clair88fa2752021-11-23 13:03:41 +0100468}
469
Eric Laurent736a1022019-03-27 18:28:46 -0700470void AudioPolicyManager::setEngineDeviceConnectionState(const sp<DeviceDescriptor> device,
471 audio_policy_dev_state_t state) {
472
473 // the Engine does not have to know about remote submix devices used by dynamic audio policies
474 if (audio_is_remote_submix_device(device->type()) && device->address() != "0") {
475 return;
476 }
477 mEngine->setDeviceConnectionState(device, state);
478}
479
480
Eric Laurente0720872014-03-11 09:30:41 -0700481audio_policy_dev_state_t AudioPolicyManager::getDeviceConnectionState(audio_devices_t device,
François Gaffie53615e22015-03-19 09:24:12 +0100482 const char *device_address)
Eric Laurente552edb2014-03-10 17:42:56 -0700483{
Eric Laurent634b7142016-04-20 13:48:02 -0700484 sp<DeviceDescriptor> devDesc =
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800485 mHwModules.getDeviceDescriptor(device, device_address, "", AUDIO_FORMAT_DEFAULT,
486 false /* allowToCreate */,
Eric Laurent634b7142016-04-20 13:48:02 -0700487 (strlen(device_address) != 0)/*matchAddress*/);
488
489 if (devDesc == 0) {
François Gaffie251c7f02018-11-07 10:41:08 +0100490 ALOGV("getDeviceConnectionState() undeclared device, type %08x, address: %s",
Eric Laurent634b7142016-04-20 13:48:02 -0700491 device, device_address);
492 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
493 }
François Gaffie53615e22015-03-19 09:24:12 +0100494
Eric Laurent3a4311c2014-03-17 12:00:47 -0700495 DeviceVector *deviceVector;
496
Eric Laurente552edb2014-03-10 17:42:56 -0700497 if (audio_is_output_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700498 deviceVector = &mAvailableOutputDevices;
Eric Laurente552edb2014-03-10 17:42:56 -0700499 } else if (audio_is_input_device(device)) {
Eric Laurent3a4311c2014-03-17 12:00:47 -0700500 deviceVector = &mAvailableInputDevices;
501 } else {
François Gaffie11d30102018-11-02 16:09:09 +0100502 ALOGW("%s() invalid device type %08x", __func__, device);
Eric Laurent3a4311c2014-03-17 12:00:47 -0700503 return AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurente552edb2014-03-10 17:42:56 -0700504 }
Eric Laurent634b7142016-04-20 13:48:02 -0700505
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800506 return (deviceVector->getDevice(
507 device, String8(device_address), AUDIO_FORMAT_DEFAULT) != 0) ?
Eric Laurent634b7142016-04-20 13:48:02 -0700508 AUDIO_POLICY_DEVICE_STATE_AVAILABLE : AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE;
Eric Laurenta1d525f2015-01-29 13:36:45 -0800509}
510
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800511status_t AudioPolicyManager::handleDeviceConfigChange(audio_devices_t device,
512 const char *device_address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800513 const char *device_name,
514 audio_format_t encodedFormat)
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800515{
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800516 ALOGV("handleDeviceConfigChange(() device: 0x%X, address %s name %s encodedFormat: 0x%X",
517 device, device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800518
Pavlin Radoslavovc694ff42017-01-09 23:27:29 -0800519 // connect/disconnect only 1 device at a time
520 if (!audio_is_output_device(device) && !audio_is_input_device(device)) return BAD_VALUE;
521
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800522 // Check if the device is currently connected
jiabin9a3361e2019-10-01 09:38:30 -0700523 DeviceVector deviceList = mAvailableOutputDevices.getDevicesFromType(device);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800524 if (deviceList.empty()) {
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800525 // Nothing to do: device is not connected
526 return NO_ERROR;
527 }
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800528 sp<DeviceDescriptor> devDesc = deviceList.itemAt(0);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800529
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700530 // For offloaded A2DP, Hw modules may have the capability to
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800531 // configure codecs.
532 // Handle two specific cases by sending a set parameter to
533 // configure A2DP codecs. No need to toggle device state.
534 // Case 1: A2DP active device switches from primary to primary
535 // module
536 // Case 2: A2DP device config changes on primary module.
Eric Laurent7e3c0832023-11-30 15:04:50 +0100537 if (device_has_encoding_capability(device) && hasPrimaryOutput()) {
jiabin9a3361e2019-10-01 09:38:30 -0700538 sp<HwModule> module = mHwModules.getModuleForDeviceType(device, encodedFormat);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800539 audio_module_handle_t primaryHandle = mPrimaryOutput->getModuleHandle();
540 if (availablePrimaryOutputDevices().contains(devDesc) &&
541 (module != 0 && module->getHandle() == primaryHandle)) {
Eric Laurent7e3c0832023-11-30 15:04:50 +0100542 bool isA2dp = audio_is_a2dp_out_device(device);
543 const String8 supportKey = isA2dp ? String8(AudioParameter::keyReconfigA2dpSupported)
544 : String8(AudioParameter::keyReconfigLeSupported);
545 String8 reply = mpClientInterface->getParameters(AUDIO_IO_HANDLE_NONE, supportKey);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800546 AudioParameter repliedParameters(reply);
Eric Laurent7e3c0832023-11-30 15:04:50 +0100547 int isReconfigSupported;
548 repliedParameters.getInt(supportKey, isReconfigSupported);
549 if (isReconfigSupported) {
550 const String8 key = isA2dp ? String8(AudioParameter::keyReconfigA2dp)
551 : String8(AudioParameter::keyReconfigLe);
552 AudioParameter param;
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800553 param.add(key, String8("true"));
554 mpClientInterface->setParameters(AUDIO_IO_HANDLE_NONE, param.toString());
555 devDesc->setEncodedFormat(encodedFormat);
556 return NO_ERROR;
557 }
Aniket Kumar Lata3432e042018-04-06 14:22:15 -0700558 }
559 }
cnx421bd2dcc42020-07-11 14:58:44 +0800560 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
561 for (size_t i = 0; i < mOutputs.size(); i++) {
562 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
563 // mute media strategies and delay device switch by the largest
564 // This avoid sending the music tail into the earpiece or headset.
565 setStrategyMute(musicStrategy, true, desc);
566 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
567 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
568 nullptr, true /*fromCache*/).types());
569 }
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800570 // Toggle the device state: UNAVAILABLE -> AVAILABLE
571 // This will force reading again the device configuration
Eric Laurent7e3c0832023-11-30 15:04:50 +0100572 status_t status = setDeviceConnectionState(device,
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800573 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800574 device_address, device_name,
575 devDesc->getEncodedFormat());
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800576 if (status != NO_ERROR) {
577 ALOGW("handleDeviceConfigChange() error disabling connection state: %d",
578 status);
579 return status;
580 }
581
582 status = setDeviceConnectionState(device,
583 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -0800584 device_address, device_name, encodedFormat);
Pavlin Radoslavovf862bc62016-12-26 18:57:22 -0800585 if (status != NO_ERROR) {
586 ALOGW("handleDeviceConfigChange() error enabling connection state: %d",
587 status);
588 return status;
589 }
590
591 return NO_ERROR;
592}
593
Pattydd807582021-11-04 21:01:03 +0800594status_t AudioPolicyManager::getHwOffloadFormatsSupportedForBluetoothMedia(
595 audio_devices_t device, std::vector<audio_format_t> *formats)
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800596{
Pattydd807582021-11-04 21:01:03 +0800597 ALOGV("getHwOffloadFormatsSupportedForBluetoothMedia()");
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800598 status_t status = NO_ERROR;
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800599 std::unordered_set<audio_format_t> formatSet;
600 sp<HwModule> primaryModule =
601 mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_PRIMARY);
Aniket Kumar Latafedb5982019-07-03 11:20:36 -0700602 if (primaryModule == nullptr) {
603 ALOGE("%s() unable to get primary module", __func__);
604 return NO_INIT;
605 }
Pattydd807582021-11-04 21:01:03 +0800606
607 DeviceTypeSet audioDeviceSet;
608
609 switch(device) {
610 case AUDIO_DEVICE_OUT_BLUETOOTH_A2DP:
611 audioDeviceSet = getAudioDeviceOutAllA2dpSet();
612 break;
613 case AUDIO_DEVICE_OUT_BLE_HEADSET:
Patty Huang36028df2022-07-06 00:14:12 +0800614 audioDeviceSet = getAudioDeviceOutLeAudioUnicastSet();
615 break;
616 case AUDIO_DEVICE_OUT_BLE_BROADCAST:
617 audioDeviceSet = getAudioDeviceOutLeAudioBroadcastSet();
Pattydd807582021-11-04 21:01:03 +0800618 break;
619 default:
620 ALOGE("%s() device type 0x%08x not supported", __func__, device);
621 return BAD_VALUE;
622 }
623
jiabin9a3361e2019-10-01 09:38:30 -0700624 DeviceVector declaredDevices = primaryModule->getDeclaredDevices().getDevicesFromTypes(
Pattydd807582021-11-04 21:01:03 +0800625 audioDeviceSet);
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800626 for (const auto& device : declaredDevices) {
627 formatSet.insert(device->encodedFormats().begin(), device->encodedFormats().end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800628 }
Aniket Kumar Lata89e82232019-01-19 18:14:10 -0800629 formats->assign(formatSet.begin(), formatSet.end());
Arun Mirpuri11029ad2018-12-19 20:45:19 -0800630 return status;
631}
632
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100633DeviceVector AudioPolicyManager::selectBestRxSinkDevicesForCall(bool fromCache)
634{
635 DeviceVector rxSinkdevices{};
636 rxSinkdevices = mEngine->getOutputDevicesForAttributes(
637 attributes_initializer(AUDIO_USAGE_VOICE_COMMUNICATION), nullptr, fromCache);
638 if (!rxSinkdevices.isEmpty() && mAvailableOutputDevices.contains(rxSinkdevices.itemAt(0))) {
639 auto rxSinkDevice = rxSinkdevices.itemAt(0);
640 auto telephonyRxModule = mHwModules.getModuleForDeviceType(
641 AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
642 // retrieve Rx Source device descriptor
643 sp<DeviceDescriptor> rxSourceDevice = mAvailableInputDevices.getDevice(
644 AUDIO_DEVICE_IN_TELEPHONY_RX, String8(), AUDIO_FORMAT_DEFAULT);
645
646 // RX Telephony and Rx sink devices are declared by Primary Audio HAL
647 if (isPrimaryModule(telephonyRxModule) && (telephonyRxModule->getHalVersionMajor() >= 3) &&
648 telephonyRxModule->supportsPatch(rxSourceDevice, rxSinkDevice)) {
649 ALOGW("%s() device %s using HW Bridge", __func__, rxSinkDevice->toString().c_str());
650 return DeviceVector(rxSinkDevice);
651 }
652 }
653 // Note that despite the fact that getNewOutputDevices() is called on the primary output,
654 // the device returned is not necessarily reachable via this output
655 // (filter later by setOutputDevices())
656 return getNewOutputDevices(mPrimaryOutput, fromCache);
657}
658
659status_t AudioPolicyManager::updateCallRouting(bool fromCache, uint32_t delayMs, uint32_t *waitMs)
660{
François Gaffiedb1755b2023-09-01 11:50:35 +0200661 if (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100662 DeviceVector rxDevices = selectBestRxSinkDevicesForCall(fromCache);
663 return updateCallRoutingInternal(rxDevices, delayMs, waitMs);
664 }
665 return INVALID_OPERATION;
666}
667
668status_t AudioPolicyManager::updateCallRoutingInternal(
669 const DeviceVector &rxDevices, uint32_t delayMs, uint32_t *waitMs)
Eric Laurentc2730ba2014-07-20 15:47:07 -0700670{
671 bool createTxPatch = false;
François Gaffie9eb18552018-11-05 10:33:26 +0100672 bool createRxPatch = false;
Eric Laurentdc462862016-07-19 12:29:53 -0700673 uint32_t muteWaitMs = 0;
François Gaffiedb1755b2023-09-01 11:50:35 +0200674 if (hasPrimaryOutput() &&
jiabin9a3361e2019-10-01 09:38:30 -0700675 mPrimaryOutput->devices().onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_STUB)) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100676 return INVALID_OPERATION;
Eric Laurent87ffa392015-05-22 10:32:38 -0700677 }
François Gaffie11d30102018-11-02 16:09:09 +0100678
Francois Gaffie716e1432019-01-14 16:58:59 +0100679 audio_attributes_t attr = { .source = AUDIO_SOURCE_VOICE_COMMUNICATION };
François Gaffiec005e562018-11-06 15:04:49 +0100680 auto txSourceDevice = mEngine->getInputDeviceForAttributes(attr);
François Gaffiedb1755b2023-09-01 11:50:35 +0200681
682 disconnectTelephonyAudioSource(mCallRxSourceClient);
683 disconnectTelephonyAudioSource(mCallTxSourceClient);
684
685 if (rxDevices.isEmpty()) {
686 ALOGW("%s() no selected output device", __func__);
687 return INVALID_OPERATION;
688 }
Eric Laurentcedd5b52023-03-22 00:03:31 +0000689 if (txSourceDevice == nullptr) {
690 ALOGE("%s() selected input device not available", __func__);
691 return INVALID_OPERATION;
692 }
François Gaffiec005e562018-11-06 15:04:49 +0100693
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100694 ALOGV("%s device rxDevice %s txDevice %s", __func__,
François Gaffie9eb18552018-11-05 10:33:26 +0100695 rxDevices.itemAt(0)->toString().c_str(), txSourceDevice->toString().c_str());
Eric Laurentc2730ba2014-07-20 15:47:07 -0700696
François Gaffie9eb18552018-11-05 10:33:26 +0100697 auto telephonyRxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700698 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_IN_TELEPHONY_RX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100699 auto telephonyTxModule =
jiabin9a3361e2019-10-01 09:38:30 -0700700 mHwModules.getModuleForDeviceType(AUDIO_DEVICE_OUT_TELEPHONY_TX, AUDIO_FORMAT_DEFAULT);
François Gaffie9eb18552018-11-05 10:33:26 +0100701 // retrieve Rx Source and Tx Sink device descriptors
702 sp<DeviceDescriptor> rxSourceDevice =
703 mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_TELEPHONY_RX,
704 String8(),
705 AUDIO_FORMAT_DEFAULT);
706 sp<DeviceDescriptor> txSinkDevice =
707 mAvailableOutputDevices.getDevice(AUDIO_DEVICE_OUT_TELEPHONY_TX,
708 String8(),
709 AUDIO_FORMAT_DEFAULT);
710
711 // RX and TX Telephony device are declared by Primary Audio HAL
712 if (isPrimaryModule(telephonyRxModule) && isPrimaryModule(telephonyTxModule) &&
713 (telephonyRxModule->getHalVersionMajor() >= 3)) {
714 if (rxSourceDevice == 0 || txSinkDevice == 0) {
715 // RX / TX Telephony device(s) is(are) not currently available
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100716 ALOGE("%s() no telephony Tx and/or RX device", __func__);
717 return INVALID_OPERATION;
François Gaffie9eb18552018-11-05 10:33:26 +0100718 }
François Gaffieafd4cea2019-11-18 15:50:22 +0100719 // createAudioPatchInternal now supports both HW / SW bridging
720 createRxPatch = true;
721 createTxPatch = true;
François Gaffie9eb18552018-11-05 10:33:26 +0100722 } else {
723 // If the RX device is on the primary HW module, then use legacy routing method for
724 // voice calls via setOutputDevice() on primary output.
725 // Otherwise, create two audio patches for TX and RX path.
726 createRxPatch = !(availablePrimaryOutputDevices().contains(rxDevices.itemAt(0))) &&
727 (rxSourceDevice != 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700728 // If the TX device is also on the primary HW module, setOutputDevice() will take care
729 // of it due to legacy implementation. If not, create a patch.
François Gaffie9eb18552018-11-05 10:33:26 +0100730 createTxPatch = !(availablePrimaryModuleInputDevices().contains(txSourceDevice)) &&
731 (txSinkDevice != 0);
732 }
733 // Use legacy routing method for voice calls via setOutputDevice() on primary output.
734 // Otherwise, create two audio patches for TX and RX path.
735 if (!createRxPatch) {
François Gaffiedb1755b2023-09-01 11:50:35 +0200736 if (!hasPrimaryOutput()) {
737 ALOGW("%s() no primary output available", __func__);
738 return INVALID_OPERATION;
739 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530740 muteWaitMs = setOutputDevices(__func__, mPrimaryOutput, rxDevices, true, delayMs);
Eric Laurent8ae73122016-04-12 10:13:29 -0700741 } else { // create RX path audio patch
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200742 connectTelephonyRxAudioSource();
juyuchen2224c5a2019-01-21 12:00:58 +0800743 // If the TX device is on the primary HW module but RX device is
744 // on other HW module, SinkMetaData of telephony input should handle it
745 // assuming the device uses audio HAL V5.0 and above
Eric Laurentc2730ba2014-07-20 15:47:07 -0700746 }
Eric Laurent8ae73122016-04-12 10:13:29 -0700747 if (createTxPatch) { // create TX path audio patch
François Gaffieafd4cea2019-11-18 15:50:22 +0100748 // terminate active capture if on the same HW module as the call TX source device
749 // FIXME: would be better to refine to only inputs whose profile connects to the
750 // call TX device but this information is not in the audio patch and logic here must be
751 // symmetric to the one in startInput()
752 for (const auto& activeDesc : mInputs.getActiveInputs()) {
753 if (activeDesc->hasSameHwModuleAs(txSourceDevice)) {
754 closeActiveClients(activeDesc);
755 }
756 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200757 connectTelephonyTxAudioSource(txSourceDevice, txSinkDevice, delayMs);
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800758 }
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100759 if (waitMs != nullptr) {
760 *waitMs = muteWaitMs;
761 }
762 return NO_ERROR;
Mikhail Naganovb567ba02017-12-08 11:16:27 -0800763}
Eric Laurentc2730ba2014-07-20 15:47:07 -0700764
Mikhail Naganov100f0122018-11-29 11:22:16 -0800765bool AudioPolicyManager::isDeviceOfModule(
766 const sp<DeviceDescriptor>& devDesc, const char *moduleId) const {
767 sp<HwModule> module = mHwModules.getModuleFromName(moduleId);
768 if (module != 0) {
769 return mAvailableOutputDevices.getDevicesFromHwModule(module->getHandle())
770 .indexOf(devDesc) != NAME_NOT_FOUND
771 || mAvailableInputDevices.getDevicesFromHwModule(module->getHandle())
772 .indexOf(devDesc) != NAME_NOT_FOUND;
773 }
774 return false;
775}
776
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200777void AudioPolicyManager::connectTelephonyRxAudioSource()
778{
Francois Gaffie601801d2021-06-22 13:27:39 +0200779 disconnectTelephonyAudioSource(mCallRxSourceClient);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200780 const struct audio_port_config source = {
781 .role = AUDIO_PORT_ROLE_SOURCE, .type = AUDIO_PORT_TYPE_DEVICE,
782 .ext.device.type = AUDIO_DEVICE_IN_TELEPHONY_RX, .ext.device.address = ""
783 };
784 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
Eric Laurent541a2002024-01-15 18:11:42 +0100785
786 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
787 status_t status = startAudioSource(&source, &aa, &portId, 0 /*uid*/, true /*internal*/);
788 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
789 mCallRxSourceClient = mAudioSources.valueFor(portId);
Francois Gaffie601801d2021-06-22 13:27:39 +0200790 ALOGE_IF(mCallRxSourceClient == nullptr,
791 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200792}
793
Francois Gaffie601801d2021-06-22 13:27:39 +0200794void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200795{
Francois Gaffie601801d2021-06-22 13:27:39 +0200796 if (clientDesc == nullptr) {
797 return;
798 }
799 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
800 "%s error stopping audio source", __func__);
801 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200802}
803
804void AudioPolicyManager::connectTelephonyTxAudioSource(
805 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
806 uint32_t delayMs)
807{
Francois Gaffie601801d2021-06-22 13:27:39 +0200808 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200809 if (srcDevice == nullptr || sinkDevice == nullptr) {
810 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
811 return;
812 }
813 PatchBuilder patchBuilder;
814 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
815 ALOGV("%s between source %s and sink %s", __func__,
816 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200817 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200818 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
819
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200820 struct audio_port_config source = {};
821 srcDevice->toAudioPortConfig(&source);
Eric Laurent541a2002024-01-15 18:11:42 +0100822 mCallTxSourceClient = new SourceClientDescriptor(
823 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, AUDIO_STREAM_PATCH,
824 mCommunnicationStrategy, toVolumeSource(aa), true);
825 mCallTxSourceClient->setPreferredDeviceId(sinkDevice->getId());
826
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200827 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
828 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200829 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
830 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200831 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
832 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200833 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200834 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200835}
836
Eric Laurente0720872014-03-11 09:30:41 -0700837void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700838{
839 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100840 // store previous phone state for management of sonification strategy below
841 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100842 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100843
844 if (mEngine->setPhoneState(state) != NO_ERROR) {
845 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700846 return;
847 }
François Gaffie2110e042015-03-24 08:41:51 +0100848 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700849 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700850 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700851 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800852 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700853 }
854
François Gaffie2110e042015-03-24 08:41:51 +0100855 /**
856 * Switching to or from incall state or switching between telephony and VoIP lead to force
857 * routing command.
858 */
Eric Laurent74b71512019-11-06 17:21:57 -0800859 bool force = ((isStateInCall(oldState) != isStateInCall(state))
860 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700861
862 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700863 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700864
Eric Laurente552edb2014-03-10 17:42:56 -0700865 int delayMs = 0;
866 if (isStateInCall(state)) {
867 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100868 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
869 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700870 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700871 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700872 // mute media and sonification strategies and delay device switch by the largest
873 // latency of any output where either strategy is active.
874 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100875 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
876 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
877 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700878 (delayMs < (int)desc->latency()*2)) {
879 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700880 }
François Gaffiec005e562018-11-06 15:04:49 +0100881 setStrategyMute(musicStrategy, true, desc);
882 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
883 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
884 nullptr, true /*fromCache*/).types());
885 setStrategyMute(sonificationStrategy, true, desc);
886 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
887 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
888 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700889 }
890 }
891
François Gaffiedb1755b2023-09-01 11:50:35 +0200892 if (state == AUDIO_MODE_IN_CALL) {
893 (void)updateCallRouting(false /*fromCache*/, delayMs);
894 } else {
895 if (oldState == AUDIO_MODE_IN_CALL) {
896 disconnectTelephonyAudioSource(mCallRxSourceClient);
897 disconnectTelephonyAudioSource(mCallTxSourceClient);
898 }
899 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100900 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
901 // force routing command to audio hardware when ending call
902 // even if no device change is needed
903 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
904 rxDevices = mPrimaryOutput->devices();
905 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530906 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700907 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700908 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700909
jiabin3ff8d7d2022-12-13 06:27:44 +0000910 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700911 // reevaluate routing on all outputs in case tracks have been started during the call
912 for (size_t i = 0; i < mOutputs.size(); i++) {
913 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100914 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200915 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
916 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000917 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
918 // If the device is using preferred mixer attributes, the output need to reopen
919 // with default configuration when the new selected devices are different from
920 // current routing devices.
921 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
922 continue;
923 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530924 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200925 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700926 }
927 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000928 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700929
Eric Laurent96d1dda2022-03-14 17:14:19 +0100930 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
931
Eric Laurente552edb2014-03-10 17:42:56 -0700932 if (isStateInCall(state)) {
933 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700934 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800935 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700936 }
937
938 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100939 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
940 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700941}
942
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700943audio_mode_t AudioPolicyManager::getPhoneState() {
944 return mEngine->getPhoneState();
945}
946
Eric Laurente0720872014-03-11 09:30:41 -0700947void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100948 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700949{
François Gaffie2110e042015-03-24 08:41:51 +0100950 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700951 if (config == mEngine->getForceUse(usage)) {
952 return;
953 }
Eric Laurente552edb2014-03-10 17:42:56 -0700954
François Gaffie2110e042015-03-24 08:41:51 +0100955 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
956 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
957 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700958 }
François Gaffie2110e042015-03-24 08:41:51 +0100959 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
960 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
961 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700962
963 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700964 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800965
Eric Laurent22fcda22019-05-17 16:28:47 -0700966 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
967 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800968 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700969 }
970
Eric Laurentdc462862016-07-19 12:29:53 -0700971 //FIXME: workaround for truncated touch sounds
972 // to be removed when the problem is handled by system UI
973 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700974 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
975 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
976 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700977
978 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100979 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700980}
981
Eric Laurente0720872014-03-11 09:30:41 -0700982void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700983{
984 ALOGV("setSystemProperty() property %s, value %s", property, value);
985}
986
Dorin Drimusecc9f422022-03-09 17:57:40 +0100987// Find an MSD output profile compatible with the parameters passed.
988// When "directOnly" is set, restrict search to profiles for direct outputs.
989sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
990 const DeviceVector& devices,
991 uint32_t samplingRate,
992 audio_format_t format,
993 audio_channel_mask_t channelMask,
994 audio_output_flags_t flags,
995 bool directOnly)
996{
997 flags = getRelevantFlags(flags, directOnly);
998
999 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1000 if (msdModule != nullptr) {
1001 // for the msd module check if there are patches to the output devices
1002 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
1003 HwModuleCollection modules;
1004 modules.add(msdModule);
1005 return searchCompatibleProfileHwModules(
1006 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1007 flags, directOnly);
1008 }
1009 }
1010 return nullptr;
1011}
1012
Michael Chana94fbb22018-04-24 14:31:19 +10001013// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1014// search to profiles for direct outputs.
1015sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001016 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001017 uint32_t samplingRate,
1018 audio_format_t format,
1019 audio_channel_mask_t channelMask,
1020 audio_output_flags_t flags,
1021 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001022{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001023 flags = getRelevantFlags(flags, directOnly);
1024
1025 return searchCompatibleProfileHwModules(
1026 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1027}
1028
1029audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1030 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001031 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001032 // only retain flags that will drive the direct output profile selection
1033 // if explicitly requested
1034 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001035 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1037 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001038 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001039 return flags;
1040}
Eric Laurent861a6282015-05-18 15:40:16 -07001041
Dorin Drimusecc9f422022-03-09 17:57:40 +01001042sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1043 const HwModuleCollection& hwModules,
1044 const DeviceVector& devices,
1045 uint32_t samplingRate,
1046 audio_format_t format,
1047 audio_channel_mask_t channelMask,
1048 audio_output_flags_t flags,
1049 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001050 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001051 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001052 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001053 if (!curProfile->isCompatibleProfile(devices,
1054 samplingRate, NULL /*updatedSamplingRate*/,
1055 format, NULL /*updatedFormat*/,
1056 channelMask, NULL /*updatedChannelMask*/,
1057 flags)) {
1058 continue;
1059 }
1060 // reject profiles not corresponding to a device currently available
1061 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1062 continue;
1063 }
1064 // reject profiles if connected device does not support codec
1065 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1066 continue;
1067 }
1068 if (!directOnly) {
1069 return curProfile;
1070 }
1071
1072 // when searching for direct outputs, if several profiles are compatible, give priority
1073 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001074 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001075 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001076 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001077 }
1078 profile = curProfile;
1079 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1080 break;
1081 }
Eric Laurente552edb2014-03-10 17:42:56 -07001082 }
1083 }
Eric Laurent861a6282015-05-18 15:40:16 -07001084 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001085}
1086
Eric Laurentfa0f6742021-08-17 18:39:44 +02001087sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001088 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001089{
1090 for (const auto& hwModule : mHwModules) {
1091 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001092 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001093 continue;
1094 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001095 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001096 // reject profiles not corresponding to a device currently available
1097 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1098 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1099 continue;
1100 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001101 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1102 != devices.size()) {
1103 continue;
1104 }
1105 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001106 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1107 return curProfile;
1108 }
1109 }
1110 return nullptr;
1111}
1112
Eric Laurentf4e63452017-11-06 19:31:46 +00001113audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001114{
François Gaffiec005e562018-11-06 15:04:49 +01001115 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001116
1117 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1118 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1119 // format, flags, etc. This may result in some discrepancy for functions that utilize
1120 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1121 // and AudioSystem::getOutputSamplingRate().
1122
François Gaffie11d30102018-11-02 16:09:09 +01001123 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001124 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1125 if (stream == AUDIO_STREAM_MUSIC &&
1126 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1127 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1128 }
1129 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001130
François Gaffie11d30102018-11-02 16:09:09 +01001131 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1132 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001133 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001134}
1135
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001136status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1137 const audio_attributes_t *srcAttr,
1138 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001139{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001140 if (srcAttr != NULL) {
1141 if (!isValidAttributes(srcAttr)) {
1142 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1143 __func__,
1144 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1145 srcAttr->tags);
1146 return BAD_VALUE;
1147 }
1148 *dstAttr = *srcAttr;
1149 } else {
1150 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1151 ALOGE("%s: invalid stream type", __func__);
1152 return BAD_VALUE;
1153 }
François Gaffiec005e562018-11-06 15:04:49 +01001154 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001155 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001156
1157 // Only honor audibility enforced when required. The client will be
1158 // forced to reconnect if the forced usage changes.
1159 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001160 dstAttr->flags = static_cast<audio_flags_mask_t>(
1161 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001162 }
1163
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001164 return NO_ERROR;
1165}
1166
Kevin Rocard153f92d2018-12-18 18:33:28 -08001167status_t AudioPolicyManager::getOutputForAttrInt(
1168 audio_attributes_t *resultAttr,
1169 audio_io_handle_t *output,
1170 audio_session_t session,
1171 const audio_attributes_t *attr,
1172 audio_stream_type_t *stream,
1173 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001174 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001175 audio_output_flags_t *flags,
1176 audio_port_handle_t *selectedDeviceId,
1177 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001178 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001179 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001180 bool *isSpatialized,
1181 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001182{
François Gaffiec005e562018-11-06 15:04:49 +01001183 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001184 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001185 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001186 const sp<DeviceDescriptor> requestedDevice =
1187 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1188
Eric Laurent8a1095a2019-11-08 14:44:16 -08001189 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001190 *isSpatialized = false;
1191
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001192 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1193 if (status != NO_ERROR) {
1194 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001195 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001196 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001197 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001198 }
François Gaffiec005e562018-11-06 15:04:49 +01001199 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001200
François Gaffiec005e562018-11-06 15:04:49 +01001201 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1202 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001203
Oscar Azucena873d10f2023-01-12 18:34:42 -08001204 bool usePrimaryOutputFromPolicyMixes = false;
1205
Kevin Rocard153f92d2018-12-18 18:33:28 -08001206 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1207 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1208 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001209 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001210 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1211 .channel_mask = config->channel_mask,
1212 .format = config->format,
1213 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001214 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001215 mAvailableOutputDevices, requestedDevice, primaryMix,
1216 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001217 if (status != OK) {
1218 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001219 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001220
Kevin Rocard153f92d2018-12-18 18:33:28 -08001221 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001222 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1223 && !audio_is_linear_pcm(config->format)) {
1224 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001225 return BAD_VALUE;
1226 }
1227 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001228 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001229 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1230 primaryMix->mDeviceAddress,
1231 AUDIO_FORMAT_DEFAULT);
1232 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001233 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001234 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1235 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001236 // if a direct output can be opened to deliver the track's multi-channel content to the
1237 // output rather than being downmixed by the primary output, then use this direct
1238 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1239 // mix.
1240 bool tryDirectForChannelMask = policyDesc != nullptr
1241 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1242 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001243 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001244 audio_io_handle_t newOutput;
1245 status = openDirectOutput(
1246 *stream, session, config,
1247 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001248 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001249 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001250 policyDesc = mOutputs.valueFor(newOutput);
1251 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001252 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001253 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001254 policyDesc = nullptr;
1255 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001256 }
1257 if (policyDesc != nullptr) {
1258 policyDesc->mPolicyMix = primaryMix;
1259 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001260 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1261 : AUDIO_PORT_HANDLE_NONE;
1262 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1263 // Remove direct flag as it is not on a direct output.
1264 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1265 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001266
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001267 ALOGV("getOutputForAttr() returns output %d", *output);
1268 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1269 *outputType = API_OUT_MIX_PLAYBACK;
1270 } else {
1271 *outputType = API_OUTPUT_LEGACY;
1272 }
1273 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001274 } else {
1275 if (policyMixDevice != nullptr) {
1276 ALOGE("%s, try to use primary mix but no output found", __func__);
1277 return INVALID_OPERATION;
1278 }
1279 // Fallback to default engine selection as the selected primary mix device is not
1280 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001281 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001282 }
François Gaffiec005e562018-11-06 15:04:49 +01001283 // Virtual sources must always be dynamicaly or explicitly routed
1284 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1285 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1286 return BAD_VALUE;
1287 }
1288 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1289 // in order to let the choice of the order to future vendor engine
1290 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001291
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001292 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001293 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001294 }
1295
Nadav Barb2f18162018-07-18 13:01:53 +03001296 // Set incall music only if device was explicitly set, and fallback to the device which is
1297 // chosen by the engine if not.
1298 // FIXME: provide a more generic approach which is not device specific and move this back
1299 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001300 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001301 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001302 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001303 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001304 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001305 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001306 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001307 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001308 }
1309 }
1310
François Gaffiec005e562018-11-06 15:04:49 +01001311 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1312 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1313 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001314
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001315 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001316 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001317 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001318 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001319 ALOGV("%s() Using MSD devices %s instead of devices %s",
1320 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001321 } else {
1322 *output = AUDIO_IO_HANDLE_NONE;
1323 }
1324 }
1325 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001326 sp<PreferredMixerAttributesInfo> info = nullptr;
1327 if (outputDevices.size() == 1) {
1328 info = getPreferredMixerAttributesInfo(
1329 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001330 mEngine->getProductStrategyForAttributes(*resultAttr),
1331 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001332 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1333 // and it is currently active.
1334 if (info != nullptr && info->getUid() != uid &&
1335 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1336 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001337 info = nullptr;
1338 }
1339 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001340 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001341 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001342 // The client will be active if the client is currently preferred mixer owner and the
1343 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001344 *isBitPerfect = (info != nullptr
1345 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001346 && info->getUid() == uid
1347 && *output != AUDIO_IO_HANDLE_NONE
1348 // When bit-perfect output is selected for the preferred mixer attributes owner,
1349 // only need to consider the config matches.
1350 && mOutputs.valueFor(*output)->isConfigurationMatched(
1351 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001352 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001353 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001354 AudioProfileVector profiles;
1355 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1356 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001357 const auto channels = profiles[0]->getChannels();
1358 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1359 config->channel_mask = *channels.begin();
1360 }
1361 const auto sampleRates = profiles[0]->getSampleRates();
1362 if (!sampleRates.empty() &&
1363 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1364 config->sample_rate = *sampleRates.begin();
1365 }
jiabinf1c73972022-04-14 16:28:52 -07001366 config->format = profiles[0]->getFormat();
1367 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001368 return INVALID_OPERATION;
1369 }
Paul McLeanaa981192015-03-21 09:55:15 -07001370
François Gaffiec005e562018-11-06 15:04:49 +01001371 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001372 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001373 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001374 *selectedDeviceId = outputDevice->getId();
1375 break;
1376 }
1377 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001378
Eric Laurent8a1095a2019-11-08 14:44:16 -08001379 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1380 *outputType = API_OUTPUT_TELEPHONY_TX;
1381 } else {
1382 *outputType = API_OUTPUT_LEGACY;
1383 }
1384
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001385 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1386
1387 return NO_ERROR;
1388}
1389
1390status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1391 audio_io_handle_t *output,
1392 audio_session_t session,
1393 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001394 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001395 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001396 audio_output_flags_t *flags,
1397 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001398 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001399 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001400 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001401 bool *isSpatialized,
1402 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001403{
1404 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1405 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1406 return INVALID_OPERATION;
1407 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001408 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001409 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001410 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001411 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001412 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001413 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001414 const sp<DeviceDescriptor> requestedDevice =
1415 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1416
1417 // Prevent from storing invalid requested device id in clients
1418 const audio_port_handle_t sanitizedRequestedPortId =
1419 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1420 *selectedDeviceId = sanitizedRequestedPortId;
1421
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001422 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001423 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001424 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1425 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001426 if (status != NO_ERROR) {
1427 return status;
1428 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001429 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001430 if (secondaryOutputs != nullptr) {
1431 for (auto &secondaryMix : secondaryMixes) {
1432 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1433 if (outputDesc != nullptr &&
1434 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1435 secondaryOutputs->push_back(outputDesc->mIoHandle);
1436 weakSecondaryOutputDescs.push_back(outputDesc);
1437 }
1438 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001439 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001440
Eric Laurent8fc147b2018-07-22 19:13:55 -07001441 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001442 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001443 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001444 };
jiabin4ef93452019-09-10 14:29:54 -07001445 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001446
Eric Laurentc209fe42020-06-05 18:11:23 -07001447 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001448 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001449 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001450 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001451 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001452 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001453 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001454 std::move(weakSecondaryOutputDescs),
1455 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001456 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001457
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001458 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1459 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001460
Eric Laurente83b55d2014-11-14 10:06:21 -08001461 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001462}
1463
Eric Laurentc529cf62020-04-17 18:19:10 -07001464status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1465 audio_session_t session,
1466 const audio_config_t *config,
1467 audio_output_flags_t flags,
1468 const DeviceVector &devices,
1469 audio_io_handle_t *output) {
1470
1471 *output = AUDIO_IO_HANDLE_NONE;
1472
1473 // skip direct output selection if the request can obviously be attached to a mixed output
1474 // and not explicitly requested
1475 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1476 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1477 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1478 return NAME_NOT_FOUND;
1479 }
1480
1481 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1482 // This prevents creating an offloaded track and tearing it down immediately after start
1483 // when audioflinger detects there is an active non offloadable effect.
1484 // FIXME: We should check the audio session here but we do not have it in this context.
1485 // This may prevent offloading in rare situations where effects are left active by apps
1486 // in the background.
1487 sp<IOProfile> profile;
1488 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1489 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1490 profile = getProfileForOutput(
1491 devices, config->sample_rate, config->format, config->channel_mask,
1492 flags, true /* directOnly */);
1493 }
1494
1495 if (profile == nullptr) {
1496 return NAME_NOT_FOUND;
1497 }
1498
1499 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1500 for (size_t i = 0; i < mOutputs.size(); i++) {
1501 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1502 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1503 // reuse direct output if currently open by the same client
1504 // and configured with same parameters
1505 if ((config->sample_rate == desc->getSamplingRate()) &&
1506 (config->format == desc->getFormat()) &&
1507 (config->channel_mask == desc->getChannelMask()) &&
1508 (session == desc->mDirectClientSession)) {
1509 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001510 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001511 mOutputs.keyAt(i), session);
1512 *output = mOutputs.keyAt(i);
1513 return NO_ERROR;
1514 }
1515 }
1516 }
1517
1518 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001519 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1520 return NAME_NOT_FOUND;
1521 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1522 // MMAP gracefully handles lack of an exclusive track resource by mixing
1523 // above the audio framework. For AAudio to know that the limit is reached,
1524 // return an error.
1525 return NAME_NOT_FOUND;
1526 } else {
1527 // Close outputs on this profile, if available, to free resources for this request
1528 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1529 const auto desc = mOutputs.valueAt(i);
1530 if (desc->mProfile == profile) {
1531 closeOutput(desc->mIoHandle);
1532 }
1533 }
1534 }
1535 }
1536
1537 // Unable to close streams to find free resources for this request
1538 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001539 return NAME_NOT_FOUND;
1540 }
1541
Atneya Nairb16666a2023-12-11 20:18:33 -08001542 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001543
Michael Chan6fb34492020-12-08 15:44:49 +11001544 // An MSD patch may be using the only output stream that can service this request. Release
1545 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001546 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001547
Eric Laurentf1f22e72021-07-13 14:04:14 +02001548 status_t status =
1549 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001550
1551 // only accept an output with the requested parameters
1552 if (status != NO_ERROR ||
1553 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1554 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1555 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1556 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1557 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1558 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1559 config->channel_mask, outputDesc->getChannelMask());
1560 if (*output != AUDIO_IO_HANDLE_NONE) {
1561 outputDesc->close();
1562 }
1563 // fall back to mixer output if possible when the direct output could not be open
1564 if (audio_is_linear_pcm(config->format) &&
1565 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1566 return NAME_NOT_FOUND;
1567 }
1568 *output = AUDIO_IO_HANDLE_NONE;
1569 return BAD_VALUE;
1570 }
1571 outputDesc->mDirectOpenCount = 1;
1572 outputDesc->mDirectClientSession = session;
1573
1574 addOutput(*output, outputDesc);
1575 mPreviousOutputs = mOutputs;
1576 ALOGV("%s returns new direct output %d", __func__, *output);
1577 mpClientInterface->onAudioPortListUpdate();
1578 return NO_ERROR;
1579}
1580
François Gaffie11d30102018-11-02 16:09:09 +01001581audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1582 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001583 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001584 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001585 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001586 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001587 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001588 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001589 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001590{
Andy Hungc88b0642018-04-27 15:42:35 -07001591 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001592
jiabine375d412019-02-26 12:54:53 -08001593 // Discard haptic channel mask when forcing muting haptic channels.
1594 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001595 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1596 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001597
Eric Laurente552edb2014-03-10 17:42:56 -07001598 // open a direct output if required by specified parameters
1599 //force direct flag if offload flag is set: offloading implies a direct output stream
1600 // and all common behaviors are driven by checking only the direct flag
1601 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001602 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1603 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001604 }
Nadav Bar766fb022018-01-07 12:18:03 +02001605 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1606 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001607 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001608
1609 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1610
Eric Laurente83b55d2014-11-14 10:06:21 -08001611 // only allow deep buffering for music stream type
1612 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001613 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001614 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001615 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001616 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1617 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001618 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001619 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001620 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001621 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001622 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001623 audio_is_linear_pcm(config->format) &&
1624 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001625 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001626 AUDIO_OUTPUT_FLAG_DIRECT);
1627 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001628 }
Eric Laurente552edb2014-03-10 17:42:56 -07001629
Carter Hsua3abb402021-10-26 11:11:20 +08001630 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1631 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1632 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1633 }
1634
Eric Laurentf9230d52024-01-26 18:49:09 +01001635 // Use the spatializer output if the content can be spatialized, no preferred mixer
1636 // was specified and offload or direct playback is not explicitly requested.
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001637 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001638 if (mSpatializerOutput != nullptr
jiabin2462ce82024-01-12 20:37:59 +00001639 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())
Eric Laurentf9230d52024-01-26 18:49:09 +01001640 && prefMixerConfigInfo == nullptr
1641 && ((*flags & (AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD | AUDIO_OUTPUT_FLAG_DIRECT)) == 0)) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001642 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001643 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001644 }
1645
Eric Laurentc529cf62020-04-17 18:19:10 -07001646 audio_config_t directConfig = *config;
1647 directConfig.channel_mask = channelMask;
1648 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1649 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001650 return output;
1651 }
1652
Eric Laurent14cbfca2016-03-17 09:42:16 -07001653 // A request for HW A/V sync cannot fallback to a mixed output because time
1654 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001655 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001656 return AUDIO_IO_HANDLE_NONE;
1657 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001658 // A request for Tuner cannot fallback to a mixed output
1659 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1660 return AUDIO_IO_HANDLE_NONE;
1661 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001662
Eric Laurente552edb2014-03-10 17:42:56 -07001663 // ignoring channel mask due to downmix capability in mixer
1664
1665 // open a non direct output
1666
1667 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001668 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001669 // get which output is suitable for the specified stream. The actual
1670 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001671 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001672 if (prefMixerConfigInfo != nullptr) {
1673 for (audio_io_handle_t outputHandle : outputs) {
1674 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1675 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1676 output = outputHandle;
1677 break;
1678 }
1679 }
1680 if (output == AUDIO_IO_HANDLE_NONE) {
1681 // No output open with the preferred profile. Open a new one.
1682 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1683 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1684 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1685 config.format = prefMixerConfigInfo->getConfigBase().format;
1686 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1687 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1688 &config, prefMixerConfigInfo->getFlags());
1689 if (preferredOutput == nullptr) {
1690 ALOGE("%s failed to open output with preferred mixer config", __func__);
1691 } else {
1692 output = preferredOutput->mIoHandle;
1693 }
1694 }
1695 } else {
1696 // at this stage we should ignore the DIRECT flag as no direct output could be
1697 // found earlier
1698 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1699 output = selectOutput(
1700 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1701 }
Eric Laurente552edb2014-03-10 17:42:56 -07001702 }
François Gaffie11d30102018-11-02 16:09:09 +01001703 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001704 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001705 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001706
Eric Laurente552edb2014-03-10 17:42:56 -07001707 return output;
1708}
1709
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001710sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001711 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1712 mAvailableInputDevices);
1713 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1714}
1715
1716DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1717 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1718 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001719}
1720
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001721const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001722 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001723 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1724 if (msdModule != 0) {
1725 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1726 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1727 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1728 const struct audio_port_config *source = &patch->mPatch.sources[j];
1729 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1730 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001731 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001732 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001733 }
1734 }
1735 }
1736 return msdPatches;
1737}
1738
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001739bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1740 ssize_t index = mAudioPatches.indexOfKey(handle);
1741 if (index < 0) {
1742 return false;
1743 }
1744 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1745 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1746 if (msdModule == nullptr) {
1747 return false;
1748 }
1749 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1750 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1751 return true;
1752 }
1753 index = getMsdOutputPatches().indexOfKey(handle);
1754 if (index < 0) {
1755 return false;
1756 }
1757 return true;
1758}
1759
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001760status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1761 const InputProfileCollection &inputProfiles,
1762 const OutputProfileCollection &outputProfiles,
1763 const sp<DeviceDescriptor> &sourceDevice,
1764 const sp<DeviceDescriptor> &sinkDevice,
1765 AudioProfileVector& sourceProfiles,
1766 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001767 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001768 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001769 return NO_INIT;
1770 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001771 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001772 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001773 return NO_INIT;
1774 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001775 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001776 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1777 inProfile->supportsDevice(sourceDevice)) {
1778 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001779 }
1780 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001781 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001782 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001783 outProfile->supportsDevice(sinkDevice)) {
1784 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001785 }
1786 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001787 return NO_ERROR;
1788}
1789
1790status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1791 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1792 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1793{
Dean Wheatley16809da2022-12-09 14:55:46 +11001794 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1795 static const std::vector<audio_format_t> formatsOrder = {{
1796 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001797 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1798 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001799 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1800 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1801 // preferred).
1802 std::vector<audio_channel_mask_t> masks = {{
1803 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1804 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1805 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1806 // insert index masks (higher counts most preferred) as preferred over position masks
1807 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1808 masks.insert(
1809 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1810 }
1811 return masks;
1812 }();
1813
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001814 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001815 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1816 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001817 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001818 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1819 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001820 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001821 }
1822 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1823 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1824 sinkConfig->format = bestSinkConfig.format;
1825 // For encoded streams force direct flag to prevent downstream mixing.
1826 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1827 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001828 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1829 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001830 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001831 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1832 // raw and IEC61937 framed streams.
1833 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1834 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1835 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001836 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1837 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001838 sourceConfig->channel_mask =
1839 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1840 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1841 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001842 sourceConfig->format = bestSinkConfig.format;
1843 // Copy input stream directly without any processing (e.g. resampling).
1844 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1845 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1846 if (hwAvSync) {
1847 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1848 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1849 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1850 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1851 }
1852 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1853 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1854 sinkConfig->config_mask |= config_mask;
1855 sourceConfig->config_mask |= config_mask;
1856 return NO_ERROR;
1857}
1858
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001859PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1860 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001861{
1862 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001863 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1864 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1865 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1866 if (deviceModule == nullptr) {
1867 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1868 return patchBuilder;
1869 }
1870 const InputProfileCollection inputProfiles = msdIsSource ?
1871 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1872 const OutputProfileCollection outputProfiles = msdIsSource ?
1873 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1874
1875 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1876 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1877 device : getMsdAudioOutDevices().itemAt(0);
1878 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1879
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001880 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1881 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001882 AudioProfileVector sourceProfiles;
1883 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001884 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1885 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001886 for (auto hwAvSync : { true, false }) {
1887 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1888 sourceProfiles, sinkProfiles) != NO_ERROR) {
1889 continue;
1890 }
1891 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1892 &sinkConfig) == NO_ERROR) {
1893 // Found a matching config. Re-create PatchBuilder with this config.
1894 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1895 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001896 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001897 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001898 " supporting PCM format conversion.", __func__);
1899 return patchBuilder;
1900}
1901
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001902status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001903 DeviceVector devices;
1904 if (outputDevices != nullptr && outputDevices->size() > 0) {
1905 devices.add(*outputDevices);
1906 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001907 // Use media strategy for unspecified output device. This should only
1908 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1909 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001910 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001911 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001912 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001913 }
Michael Chan6fb34492020-12-08 15:44:49 +11001914 std::vector<PatchBuilder> patchesToCreate;
1915 for (auto i = 0u; i < devices.size(); ++i) {
1916 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001917 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001918 }
1919 // Retain only the MSD patches associated with outputDevices request.
1920 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001921 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001922 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1923 auto retainedPatch = false;
1924 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1925 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1926 patchesToRemove.removeItemsAt(i);
1927 retainedPatch = true;
1928 break;
1929 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001930 }
Michael Chan6fb34492020-12-08 15:44:49 +11001931 if (retainedPatch) {
1932 it = patchesToCreate.erase(it);
1933 continue;
1934 }
1935 ++it;
1936 }
1937 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1938 return NO_ERROR;
1939 }
1940 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1941 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001942 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001943 }
Michael Chan6fb34492020-12-08 15:44:49 +11001944 status_t status = NO_ERROR;
1945 for (const auto &p : patchesToCreate) {
1946 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1947 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1948 char message[256];
1949 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1950 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1951 currStatus == NO_ERROR ? "Success" : "Error",
1952 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1953 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1954 if (currStatus == NO_ERROR) {
1955 ALOGD("%s", message);
1956 } else {
1957 ALOGE("%s", message);
1958 if (status == NO_ERROR) {
1959 status = currStatus;
1960 }
1961 }
1962 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001963 return status;
1964}
1965
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001966void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1967 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001968 for (size_t i = 0; i < msdPatches.size(); i++) {
1969 const auto& patch = msdPatches[i];
1970 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1971 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1972 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1973 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1974 releaseAudioPatch(patch->getHandle(), mUidCached);
1975 break;
1976 }
1977 }
1978 }
1979}
1980
Dorin Drimus94d94412022-02-02 09:05:02 +01001981bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001982 DeviceVector devicesToCheck =
1983 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001984 AudioPatchCollection msdPatches = getMsdOutputPatches();
1985 for (size_t i = 0; i < msdPatches.size(); i++) {
1986 const auto& patch = msdPatches[i];
1987 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1988 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1989 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1990 const auto& foundDevice = devicesToCheck.getDevice(
1991 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1992 if (foundDevice != nullptr) {
1993 devicesToCheck.remove(foundDevice);
1994 if (devicesToCheck.isEmpty()) {
1995 return true;
1996 }
1997 }
1998 }
1999 }
2000 }
2001 return false;
2002}
2003
Eric Laurente0720872014-03-11 09:30:41 -07002004audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002005 audio_output_flags_t flags,
2006 audio_format_t format,
2007 audio_channel_mask_t channelMask,
2008 uint32_t samplingRate,
2009 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002010{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002011 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2012 "%s called with format %#x", __func__, format);
2013
jiabinebb6af42020-06-09 17:31:17 -07002014 // Return the output that haptic-generating attached to when 1) session id is specified,
2015 // 2) haptic-generating effect exists for given session id and 3) the output that
2016 // haptic-generating effect attached to is in given outputs.
2017 if (sessionId != AUDIO_SESSION_NONE) {
2018 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2019 sessionId, FX_IID_HAPTICGENERATOR);
2020 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2021 return hapticGeneratingOutput;
2022 }
2023 }
2024
Eric Laurent16c66dd2019-05-01 17:54:10 -07002025 // Flags disqualifying an output: the match must happen before calling selectOutput()
2026 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2027 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2028
2029 // Flags expressing a functional request: must be honored in priority over
2030 // other criteria
2031 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2032 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002033 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2034 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002035 // Flags expressing a performance request: have lower priority than serving
2036 // requested sampling rate or channel mask
2037 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2038 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2039 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2040
2041 const audio_output_flags_t functionalFlags =
2042 (audio_output_flags_t)(flags & kFunctionalFlags);
2043 const audio_output_flags_t performanceFlags =
2044 (audio_output_flags_t)(flags & kPerformanceFlags);
2045
2046 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2047
Eric Laurente552edb2014-03-10 17:42:56 -07002048 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002049 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002050 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002051 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002052 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002053 // with tiebreak preferring the minimum number of extra functional flags
2054 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002055 // 3: the output supporting the exact channel mask
2056 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002057 // 5: the output with the highest sampling rate if the requested sample rate is
2058 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002059 // 6: the output with the highest number of requested performance flags
2060 // 7: the output with the bit depth the closest to the requested one
2061 // 8: the primary output
2062 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002063
Eric Laurent16c66dd2019-05-01 17:54:10 -07002064 // matching criteria values in priority order for best matching output so far
2065 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002066
Eric Laurent16c66dd2019-05-01 17:54:10 -07002067 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2068 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2069 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002070
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002071 for (audio_io_handle_t output : outputs) {
2072 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002073 // matching criteria values in priority order for current output
2074 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002075
Eric Laurent16c66dd2019-05-01 17:54:10 -07002076 if (outputDesc->isDuplicated()) {
2077 continue;
2078 }
2079 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2080 continue;
2081 }
Eric Laurent8838a382014-09-08 16:44:28 -07002082
Eric Laurent16c66dd2019-05-01 17:54:10 -07002083 // If haptic channel is specified, use the haptic output if present.
2084 // When using haptic output, same audio format and sample rate are required.
2085 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002086 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002087 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2088 continue;
2089 }
2090 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002091 && format == outputDesc->getFormat()
2092 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002093 currentMatchCriteria[0] = outputHapticChannelCount;
2094 }
2095
2096 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002097 const int matchingFunctionalFlags =
2098 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2099 const int totalFunctionalFlags =
2100 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2101 // Prefer matching functional flags, but subtract unnecessary functional flags.
2102 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002103
2104 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002105 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2106 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002107 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2108 channelCount <= outputChannelCount) {
2109 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002110 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2111 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002112 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002113 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002114 currentMatchCriteria[3] = outputChannelCount;
2115 }
2116
2117 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002118 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002119 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002120 }
2121
2122 // performance flags match
2123 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2124
2125 // format match
2126 if (format != AUDIO_FORMAT_INVALID) {
2127 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002128 PolicyAudioPort::kFormatDistanceMax -
2129 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002130 }
2131
2132 // primary output match
2133 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2134
2135 // compare match criteria by priority then value
2136 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2137 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2138 bestMatchCriteria = currentMatchCriteria;
2139 bestOutput = output;
2140
2141 std::stringstream result;
2142 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2143 std::ostream_iterator<int>(result, " "));
2144 ALOGV("%s new bestOutput %d criteria %s",
2145 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002146 }
2147 }
2148
Eric Laurent16c66dd2019-05-01 17:54:10 -07002149 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002150}
2151
Eric Laurent8fc147b2018-07-22 19:13:55 -07002152status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002153{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002154 ALOGV("%s portId %d", __FUNCTION__, portId);
2155
2156 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2157 if (outputDesc == 0) {
2158 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002159 return BAD_VALUE;
2160 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002161 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002162
Eric Laurent8fc147b2018-07-22 19:13:55 -07002163 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002164 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002165
Eric Laurent733ce942017-12-07 12:18:25 -08002166 status_t status = outputDesc->start();
2167 if (status != NO_ERROR) {
2168 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002169 }
2170
Eric Laurent97ac8712018-07-27 18:59:02 -07002171 uint32_t delayMs;
2172 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002173
2174 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002175 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002176 if (status == DEAD_OBJECT) {
2177 sp<SwAudioOutputDescriptor> desc =
2178 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2179 if (desc == nullptr) {
2180 // This is not common, it may indicate something wrong with the HAL.
2181 ALOGE("%s unable to open output with default config", __func__);
2182 return status;
2183 }
2184 desc->mUsePreferredMixerAttributes = true;
2185 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002186 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002187 }
jiabina84c3d32022-12-02 18:59:55 +00002188
2189 // If the client is the first one active on preferred mixer parameters, reopen the output
2190 // if the current mixer parameters doesn't match the preferred one.
2191 if (outputDesc->devices().size() == 1) {
2192 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2193 outputDesc->devices()[0]->getId(), client->strategy());
2194 if (info != nullptr && info->getUid() == client->uid()) {
2195 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2196 info->getConfigBase(), info->getFlags())) {
2197 stopSource(outputDesc, client);
2198 outputDesc->stop();
2199 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2200 config.channel_mask = info->getConfigBase().channel_mask;
2201 config.sample_rate = info->getConfigBase().sample_rate;
2202 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002203 sp<SwAudioOutputDescriptor> desc =
2204 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2205 if (desc == nullptr) {
2206 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002207 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002208 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002209 // Intentionally return error to let the client side resending request for
2210 // creating and starting.
2211 return DEAD_OBJECT;
2212 }
2213 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002214 if (info->getActiveClientCount() == 1 &&
2215 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2216 // If it is first bit-perfect client, reroute all clients that will be routed to
2217 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2218 PortHandleVector clientsToInvalidate;
2219 for (size_t i = 0; i < mOutputs.size(); i++) {
2220 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002221 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002222 continue;
2223 }
2224 for (const auto& c : mOutputs[i]->getClientIterable()) {
2225 clientsToInvalidate.push_back(c->portId());
2226 }
2227 }
2228 if (!clientsToInvalidate.empty()) {
2229 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2230 __func__);
2231 mpClientInterface->invalidateTracks(clientsToInvalidate);
2232 }
2233 }
jiabina84c3d32022-12-02 18:59:55 +00002234 }
2235 }
2236
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002237 if (client->hasPreferredDevice()) {
2238 // playback activity with preferred device impacts routing occurred, inform upper layers
2239 mpClientInterface->onRoutingUpdated();
2240 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002241 if (delayMs != 0) {
2242 usleep(delayMs * 1000);
2243 }
2244
2245 return status;
2246}
2247
Eric Laurent96d1dda2022-03-14 17:14:19 +01002248bool AudioPolicyManager::isLeUnicastActive() const {
2249 if (isInCall()) {
2250 return true;
2251 }
2252 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2253}
2254
2255bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2256 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2257 return false;
2258 }
2259 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2260 ALOGV("%s active %d", __func__, active);
2261 return active;
2262}
2263
Eric Laurent97ac8712018-07-27 18:59:02 -07002264status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2265 const sp<TrackClientDescriptor>& client,
2266 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002267{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002268 // cannot start playback of STREAM_TTS if any other output is being used
2269 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002270
2271 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002272 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002273 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002274 auto clientStrategy = client->strategy();
2275 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002276 if (stream == AUDIO_STREAM_TTS) {
2277 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002278 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002279 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002280 return INVALID_OPERATION;
2281 } else {
2282 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2283 }
2284 } else {
2285 // some playback other than beacon starts
2286 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2287 }
2288
Eric Laurent77305a62016-07-25 16:39:22 -07002289 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002290 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002291 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002292
François Gaffie11d30102018-11-02 16:09:09 +01002293 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002294 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002295 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002296 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002297 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002298 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002299 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002300 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002301 } else {
2302 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002303 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002304 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2305 AUDIO_FORMAT_DEFAULT);
2306 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2307 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002308 }
2309
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002310 // requiresMuteCheck is false when we can bypass mute strategy.
2311 // It covers a common case when there is no materially active audio
2312 // and muting would result in unnecessary delay and dropped audio.
2313 const uint32_t outputLatencyMs = outputDesc->latency();
2314 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002315 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002316
Eric Laurente552edb2014-03-10 17:42:56 -07002317 // increment usage count for this stream on the requested output:
2318 // NOTE that the usage count is the same for duplicated output and hardware output which is
2319 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002320 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002321
2322 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002323 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002324 // Preferred device may be exclusive, use only if no other active clients on this output
2325 devices = DeviceVector(
2326 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2327 } else {
2328 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2329 }
François Gaffie11d30102018-11-02 16:09:09 +01002330 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002331 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002332 }
2333 }
Eric Laurente552edb2014-03-10 17:42:56 -07002334
François Gaffiec005e562018-11-06 15:04:49 +01002335 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002336 selectOutputForMusicEffects();
2337 }
2338
François Gaffie1c878552018-11-22 16:53:21 +01002339 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002340 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002341 if (devices.isEmpty()) {
2342 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002343 }
François Gaffiec005e562018-11-06 15:04:49 +01002344 bool shouldWait =
2345 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2346 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2347 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002348 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002349 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002350 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002351 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002352 // An output has a shared device if
2353 // - managed by the same hw module
2354 // - supports the currently selected device
2355 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002356 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002357
Eric Laurent77305a62016-07-25 16:39:22 -07002358 // force a device change if any other output is:
2359 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002360 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002361 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002362 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002363 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002364 // change the device currently selected by the other output.
2365 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002366 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002367 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002368 force = true;
2369 }
2370 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002371 // a notification so that audio focus effect can propagate, or that a mute/unmute
2372 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002373 const uint32_t latencyMs = desc->latency();
2374 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2375
2376 if (shouldWait && isActive && (waitMs < latencyMs)) {
2377 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002378 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002379
2380 // Require mute check if another output is on a shared device
2381 // and currently active to have proper drain and avoid pops.
2382 // Note restoring AudioTracks onto this output needs to invoke
2383 // a volume ramp if there is no mute.
2384 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002385 }
2386 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002387
jiabin3ff8d7d2022-12-13 06:27:44 +00002388 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2389 // If the output is open with preferred mixer attributes, but the routed device is
2390 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2391 // changed.
2392 return DEAD_OBJECT;
2393 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002394 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302395 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2396 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002397
Eric Laurente552edb2014-03-10 17:42:56 -07002398 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002399 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002400 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002401 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002402 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002403 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002404 outputDesc->useHwGain() /*force*/)) {
2405 // request AudioService to reinitialize the volume curves asynchronously
2406 ALOGE("checkAndSetVolume failed, requesting volume range init");
2407 mpClientInterface->onVolumeRangeInitRequest();
2408 };
Eric Laurente552edb2014-03-10 17:42:56 -07002409
2410 // update the outputs if starting an output with a stream that can affect notification
2411 // routing
2412 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002413
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002414 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002415 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002416 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002417 }
Eric Laurentdc462862016-07-19 12:29:53 -07002418
2419 if (waitMs > muteWaitMs) {
2420 *delayMs = waitMs - muteWaitMs;
2421 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002422
2423 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2424 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2425 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2426 // change occurs after the MixerThread starts and causes a stream volume
2427 // glitch.
2428 //
2429 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002430 }
Eric Laurentdc462862016-07-19 12:29:53 -07002431
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002432 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002433 mEngine->getForceUse(
2434 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002435 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002436 }
2437
Eric Laurent97ac8712018-07-27 18:59:02 -07002438 // Automatically enable the remote submix input when output is started on a re routing mix
2439 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002440 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2441 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002442 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2443 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2444 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002445 "remote-submix",
2446 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002447 }
2448
Eric Laurent96d1dda2022-03-14 17:14:19 +01002449 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2450
Eric Laurente552edb2014-03-10 17:42:56 -07002451 return NO_ERROR;
2452}
2453
Eric Laurent96d1dda2022-03-14 17:14:19 +01002454void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2455 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2456 bool isUnicastActive = isLeUnicastActive();
2457
2458 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002459 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002460 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2461 for (size_t i = 0; i < mOutputs.size(); i++) {
2462 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2463 if (desc != ignoredOutput && desc->isActive()
2464 && ((isUnicastActive &&
2465 !desc->devices().
2466 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2467 || (wasUnicastActive &&
2468 !desc->devices().getDevicesFromTypes(
2469 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2470 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2471 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002472 if (desc->mUsePreferredMixerAttributes && force) {
2473 // If the device is using preferred mixer attributes, the output need to reopen
2474 // with default configuration when the new selected devices are different from
2475 // current routing devices.
2476 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2477 continue;
2478 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302479 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002480 // re-apply device specific volume if not done by setOutputDevice()
2481 if (!force) {
2482 applyStreamVolumes(desc, newDevices.types(), delayMs);
2483 }
2484 }
2485 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002486 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002487 }
2488}
2489
Eric Laurent8fc147b2018-07-22 19:13:55 -07002490status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002491{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002492 ALOGV("%s portId %d", __FUNCTION__, portId);
2493
2494 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2495 if (outputDesc == 0) {
2496 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002497 return BAD_VALUE;
2498 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002499 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002500
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002501 if (client->hasPreferredDevice(true)) {
2502 // playback activity with preferred device impacts routing occurred, inform upper layers
2503 mpClientInterface->onRoutingUpdated();
2504 }
2505
Eric Laurent97ac8712018-07-27 18:59:02 -07002506 ALOGV("stopOutput() output %d, stream %d, session %d",
2507 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002508
Eric Laurent97ac8712018-07-27 18:59:02 -07002509 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002510
Eric Laurent733ce942017-12-07 12:18:25 -08002511 if (status == NO_ERROR ) {
2512 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002513 } else {
2514 return status;
2515 }
2516
2517 if (outputDesc->devices().size() == 1) {
2518 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2519 outputDesc->devices()[0]->getId(), client->strategy());
2520 if (info != nullptr && info->getUid() == client->uid()) {
2521 info->decreaseActiveClient();
2522 if (info->getActiveClientCount() == 0) {
2523 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2524 }
2525 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002526 }
2527 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002528}
2529
Eric Laurent97ac8712018-07-27 18:59:02 -07002530status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2531 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002532{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002533 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002534 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002535 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002536 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002537
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002538 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2539
François Gaffie1c878552018-11-22 16:53:21 +01002540 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2541 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002542 // Automatically disable the remote submix input when output is stopped on a
2543 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002544 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002545 if (isSingleDeviceType(
2546 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002547 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002548 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002549 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2550 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002551 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002552 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002553 }
2554 }
2555 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002556 if (client->hasPreferredDevice(true) &&
2557 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002558 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002559 forceDeviceUpdate = true;
2560 }
2561
Eric Laurente552edb2014-03-10 17:42:56 -07002562 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002563 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002564
Eric Laurente552edb2014-03-10 17:42:56 -07002565 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002566 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002567 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002568 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002569
2570 // If the routing does not change, if an output is routed on a device using HwGain
2571 // (aka setAudioPortConfig) and there are still active clients following different
2572 // volume group(s), force reapply volume
2573 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2574 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2575
Eric Laurente552edb2014-03-10 17:42:56 -07002576 // delay the device switch by twice the latency because stopOutput() is executed when
2577 // the track stop() command is received and at that time the audio track buffer can
2578 // still contain data that needs to be drained. The latency only covers the audio HAL
2579 // and kernel buffers. Also the latency does not always include additional delay in the
2580 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302581 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002582 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002583
2584 // force restoring the device selection on other active outputs if it differs from the
2585 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002586 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002587 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002588 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002589 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002590 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002591 desc->isActive() &&
2592 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002593 (newDevices != desc->devices())) {
2594 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2595 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002596
jiabin3ff8d7d2022-12-13 06:27:44 +00002597 if (desc->mUsePreferredMixerAttributes && force) {
2598 // If the device is using preferred mixer attributes, the output need to
2599 // reopen with default configuration when the new selected devices are
2600 // different from current routing devices.
2601 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2602 continue;
2603 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302604 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002605
Eric Laurent57de36c2016-09-28 16:59:11 -07002606 // re-apply device specific volume if not done by setOutputDevice()
2607 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002608 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002609 }
Eric Laurente552edb2014-03-10 17:42:56 -07002610 }
2611 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002612 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002613 // update the outputs if stopping one with a stream that can affect notification routing
2614 handleNotificationRoutingForStream(stream);
2615 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002616
2617 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2618 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002619 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002620 }
2621
François Gaffiec005e562018-11-06 15:04:49 +01002622 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002623 selectOutputForMusicEffects();
2624 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002625
2626 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2627
Eric Laurente552edb2014-03-10 17:42:56 -07002628 return NO_ERROR;
2629 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002630 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002631 return INVALID_OPERATION;
2632 }
2633}
2634
jiabinbce0c1d2020-10-05 11:20:18 -07002635bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002636{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002637 ALOGV("%s portId %d", __FUNCTION__, portId);
2638
2639 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2640 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002641 // If an output descriptor is closed due to a device routing change,
2642 // then there are race conditions with releaseOutput from tracks
2643 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2644 // destroyed shortly thereafter.
2645 //
2646 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002647 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002648 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002649 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002650
2651 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002652
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302653 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2654 if (outputDesc->isClientActive(client)) {
2655 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2656 stopOutput(portId);
2657 }
2658
Eric Laurent8fc147b2018-07-22 19:13:55 -07002659 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2660 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002661 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002662 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002663 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002664 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002665 if (--outputDesc->mDirectOpenCount == 0) {
2666 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002667 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002668 }
2669 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302670
Andy Hung39efb7a2018-09-26 15:39:28 -07002671 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002672 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2673 // The output is pending reopened to query dynamic profiles and
2674 // there is no active clients
2675 closeOutput(outputDesc->mIoHandle);
2676 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2677 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2678 if (newOutputDesc == nullptr) {
2679 ALOGE("%s failed to open output", __func__);
2680 }
2681 return true;
2682 }
2683 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002684}
2685
Eric Laurentcaf7f482014-11-25 17:50:47 -08002686status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2687 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002688 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002689 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002690 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002691 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002692 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002693 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002694 input_type_t *inputType,
2695 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002696{
François Gaffiec005e562018-11-06 15:04:49 +01002697 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002698 "flags %#x attributes=%s requested device ID %d",
2699 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2700 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002701
Eric Laurentad2e7b92017-09-14 20:06:42 -07002702 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002703 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002704 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002705 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002706 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002707 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002708 sp<RecordClientDescriptor> clientDesc;
2709 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002710 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002711 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002712
2713 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2714 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2715 return INVALID_OPERATION;
2716 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002717
Francois Gaffie716e1432019-01-14 16:58:59 +01002718 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2719 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002720 }
2721
Paul McLean466dc8e2015-04-17 13:15:36 -06002722 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002723 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002724 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002725
Eric Laurentad2e7b92017-09-14 20:06:42 -07002726 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2727 // possible
2728 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2729 *input != AUDIO_IO_HANDLE_NONE) {
2730 ssize_t index = mInputs.indexOfKey(*input);
2731 if (index < 0) {
2732 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2733 status = BAD_VALUE;
2734 goto error;
2735 }
2736 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002737 RecordClientVector clients = inputDesc->getClientsForSession(session);
2738 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002739 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2740 status = BAD_VALUE;
2741 goto error;
2742 }
2743 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2744 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002745 // corresponds to a new client and is only permitted from the same UID.
2746 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002747 if (clients.size() > 1) {
2748 for (const auto& client : clients) {
2749 // The client map is ordered by key values (portId) and portIds are allocated
2750 // incrementaly. So the first client in this list is the one opened by audio flinger
2751 // when the mmap stream is created and should be ignored as it does not correspond
2752 // to an actual client
2753 if (client == *clients.cbegin()) {
2754 continue;
2755 }
2756 if (uid != client->uid() && !client->isSilenced()) {
2757 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2758 uid, client->portId(), client->uid());
2759 status = INVALID_OPERATION;
2760 goto error;
2761 }
Eric Laurent331679c2018-04-16 17:03:16 -07002762 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002763 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002764 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002765 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002766
Eric Laurentfecbceb2021-02-09 14:46:43 +01002767 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002768 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002769 }
2770
2771 *input = AUDIO_IO_HANDLE_NONE;
2772 *inputType = API_INPUT_INVALID;
2773
Francois Gaffie716e1432019-01-14 16:58:59 +01002774 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002775 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002776 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002777 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002778 ALOGW("%s could not find input mix for attr %s",
2779 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002780 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002781 }
jiabinc1de2df2019-05-07 14:26:40 -07002782 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2783 String8(attr->tags + strlen("addr=")),
2784 AUDIO_FORMAT_DEFAULT);
2785 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002786 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002787 __func__, attributes.source, attributes.tags);
2788 status = BAD_VALUE;
2789 goto error;
2790 }
2791
Kevin Rocard25f9b052019-02-27 15:08:54 -08002792 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2793 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2794 } else {
2795 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2796 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002797 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002798 if (explicitRoutingDevice != nullptr) {
2799 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002800 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002801 // Prevent from storing invalid requested device id in clients
2802 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002803 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002804 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2805 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002806 }
François Gaffie11d30102018-11-02 16:09:09 +01002807 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002808 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002809 status = BAD_VALUE;
2810 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002811 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002812 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2813 *inputType = API_INPUT_MIX_CAPTURE;
2814 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002815 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2816 // there is an external policy, but this input is attached to a mix of recorders,
2817 // meaning it receives audio injected into the framework, so the recorder doesn't
2818 // know about it and is therefore considered "legacy"
2819 *inputType = API_INPUT_LEGACY;
2820 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002821 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002822 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002823 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002824 } else {
2825 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002826 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002827
Eric Laurent599c7582015-12-07 18:05:55 -08002828 }
2829
François Gaffiec005e562018-11-06 15:04:49 +01002830 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002831 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002832 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002833 AudioProfileVector profiles;
2834 status_t ret = getProfilesForDevices(
2835 DeviceVector(device), profiles, flags, true /*isInput*/);
2836 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002837 const auto channels = profiles[0]->getChannels();
2838 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2839 config->channel_mask = *channels.begin();
2840 }
2841 const auto sampleRates = profiles[0]->getSampleRates();
2842 if (!sampleRates.empty() &&
2843 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2844 config->sample_rate = *sampleRates.begin();
2845 }
jiabinf1c73972022-04-14 16:28:52 -07002846 config->format = profiles[0]->getFormat();
2847 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002848 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002849 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002850
Eric Laurent8f42ea12018-08-08 09:08:25 -07002851exit:
2852
François Gaffiec005e562018-11-06 15:04:49 +01002853 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2854 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002855
Francois Gaffie716e1432019-01-14 16:58:59 +01002856 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002857 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002858 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002859
Mikhail Naganov2996f672019-04-18 12:29:59 -07002860 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002861 requestedDeviceId, attributes.source, flags,
2862 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002863 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002864 // Move (if found) effect for the client session to its input
2865 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002866 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002867
2868 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2869 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002870
Eric Laurent599c7582015-12-07 18:05:55 -08002871 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002872
2873error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002874 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002875}
2876
2877
François Gaffie11d30102018-11-02 16:09:09 +01002878audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002879 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002880 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002881 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002882 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002883 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002884{
2885 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002886 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002887 bool isSoundTrigger = false;
2888
François Gaffiec005e562018-11-06 15:04:49 +01002889 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002890 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2891 if (index >= 0) {
2892 input = mSoundTriggerSessions.valueFor(session);
2893 isSoundTrigger = true;
2894 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2895 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2896 } else {
2897 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002898 }
François Gaffiec005e562018-11-06 15:04:49 +01002899 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002900 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002901 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002902 }
2903
Carter Hsua3abb402021-10-26 11:11:20 +08002904 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2905 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2906 }
2907
Eric Laurentfe231122017-11-17 17:48:06 -08002908 // sampling rate and flags may be updated by getInputProfile
2909 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2910 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002911 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002912 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002913 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002914 // find a compatible input profile (not necessarily identical in parameters)
2915 sp<IOProfile> profile = getInputProfile(
2916 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2917 if (profile == nullptr) {
2918 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002919 }
jiabin2fd710d2022-05-02 23:20:22 +00002920
Glenn Kasten05ddca52016-02-11 08:17:12 -08002921 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002922 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002923 if (samplingRate == 0) {
2924 samplingRate = profileSamplingRate;
2925 }
Eric Laurente552edb2014-03-10 17:42:56 -07002926
Eric Laurent322b4d22015-04-03 15:57:54 -07002927 if (profile->getModuleHandle() == 0) {
2928 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002929 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002930 }
2931
Eric Laurentec376dc2021-04-08 20:41:22 +02002932 // Reuse an already opened input if a client with the same session ID already exists
2933 // on that input
2934 for (size_t i = 0; i < mInputs.size(); i++) {
2935 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2936 if (desc->mProfile != profile) {
2937 continue;
2938 }
2939 RecordClientVector clients = desc->clientsList();
2940 for (const auto &client : clients) {
2941 if (session == client->session()) {
2942 return desc->mIoHandle;
2943 }
2944 }
2945 }
2946
Eric Laurent3974e3b2017-12-07 17:58:43 -08002947 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002948 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002949 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002950 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002951 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002952 continue;
2953 }
2954 // if sound trigger, reuse input if used by other sound trigger on same session
2955 // else
2956 // reuse input if active client app is not in IDLE state
2957 //
2958 RecordClientVector clients = desc->clientsList();
2959 bool doClose = false;
2960 for (const auto& client : clients) {
2961 if (isSoundTrigger != client->isSoundTrigger()) {
2962 continue;
2963 }
2964 if (client->isSoundTrigger()) {
2965 if (session == client->session()) {
2966 return desc->mIoHandle;
2967 }
2968 continue;
2969 }
2970 if (client->active() && client->appState() != APP_STATE_IDLE) {
2971 return desc->mIoHandle;
2972 }
2973 doClose = true;
2974 }
2975 if (doClose) {
2976 closeInput(desc->mIoHandle);
2977 } else {
2978 i++;
2979 }
2980 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002981 }
2982
Eric Laurentfe231122017-11-17 17:48:06 -08002983 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002984
Eric Laurentfe231122017-11-17 17:48:06 -08002985 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2986 lConfig.sample_rate = profileSamplingRate;
2987 lConfig.channel_mask = profileChannelMask;
2988 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002989
François Gaffie11d30102018-11-02 16:09:09 +01002990 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002991
2992 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002993 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002994 (profileSamplingRate != lConfig.sample_rate) ||
2995 !audio_formats_match(profileFormat, lConfig.format) ||
2996 (profileChannelMask != lConfig.channel_mask)) {
2997 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002998 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002999 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08003000 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08003001 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07003002 }
Eric Laurent599c7582015-12-07 18:05:55 -08003003 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003004 }
3005
Eric Laurentc722f302014-12-10 11:21:49 -08003006 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003007
Eric Laurent599c7582015-12-07 18:05:55 -08003008 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003009 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003010
Eric Laurent599c7582015-12-07 18:05:55 -08003011 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003012}
3013
Eric Laurent4eb58f12018-12-07 16:41:02 -08003014status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003015{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003016 ALOGV("%s portId %d", __FUNCTION__, portId);
3017
3018 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3019 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003020 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003021 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003022 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003023 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003024 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003025 if (client->active()) {
3026 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3027 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003028 }
3029
Eric Laurent8f42ea12018-08-08 09:08:25 -07003030 audio_session_t session = client->session();
3031
Eric Laurent4eb58f12018-12-07 16:41:02 -08003032 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003033
Eric Laurent4eb58f12018-12-07 16:41:02 -08003034 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003035
Eric Laurent4eb58f12018-12-07 16:41:02 -08003036 status_t status = inputDesc->start();
3037 if (status != NO_ERROR) {
3038 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003039 }
Eric Laurente552edb2014-03-10 17:42:56 -07003040
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003041 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003042 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003043 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003044
Eric Laurent8f42ea12018-08-08 09:08:25 -07003045 // indicate active capture to sound trigger service if starting capture from a mic on
3046 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003047 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003048 if (device != nullptr) {
3049 status = setInputDevice(input, device, true /* force */);
3050 } else {
3051 ALOGW("%s no new input device can be found for descriptor %d",
3052 __FUNCTION__, inputDesc->getId());
3053 status = BAD_VALUE;
3054 }
Eric Laurente552edb2014-03-10 17:42:56 -07003055
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003056 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003057 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003058 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003059 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003060 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3061 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003062 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003063 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003064
François Gaffie11d30102018-11-02 16:09:09 +01003065 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3066 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003067 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003068 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003069 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003070
Eric Laurent8f42ea12018-08-08 09:08:25 -07003071 // automatically enable the remote submix output when input is started if not
3072 // used by a policy mix of type MIX_TYPE_RECORDERS
3073 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003074 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003075 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003076 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003077 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003078 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3079 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003080 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003081 if (address != "") {
3082 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3083 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003084 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003085 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003086 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003087 } else if (status != NO_ERROR) {
3088 // Restore client activity state.
3089 inputDesc->setClientActive(client, false);
3090 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003091 }
3092
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003093 ALOGV("%s input %d source = %d status = %d exit",
3094 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003095
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003096 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003097}
3098
Eric Laurent8fc147b2018-07-22 19:13:55 -07003099status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003100{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003101 ALOGV("%s portId %d", __FUNCTION__, portId);
3102
3103 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3104 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003105 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003106 return BAD_VALUE;
3107 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003108 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003109 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003110 if (!client->active()) {
3111 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003112 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003113 }
Carter Hsue6139d52021-07-08 10:30:20 +08003114 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003115 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003116
Eric Laurent8f42ea12018-08-08 09:08:25 -07003117 inputDesc->stop();
3118 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003119 auto current_source = inputDesc->source();
3120 setInputDevice(input, getNewInputDevice(inputDesc),
3121 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003122 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003123 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003124 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003125 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003126 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3127 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003128 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003129 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003130
3131 // automatically disable the remote submix output when input is stopped if not
3132 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003133 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003134 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003135 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003136 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003137 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3138 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003139 }
3140 if (address != "") {
3141 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3142 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003143 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003144 }
3145 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003146 resetInputDevice(input);
3147
3148 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3149 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003150 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3151 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003152 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003153 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003154 }
3155 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003156 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003157 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003158}
3159
Eric Laurent8fc147b2018-07-22 19:13:55 -07003160void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003161{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003162 ALOGV("%s portId %d", __FUNCTION__, portId);
3163
3164 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3165 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003166 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003167 return;
3168 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003169 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003170 audio_io_handle_t input = inputDesc->mIoHandle;
3171
Eric Laurent8f42ea12018-08-08 09:08:25 -07003172 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003173
Andy Hung39efb7a2018-09-26 15:39:28 -07003174 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003175 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003176 if (inputDesc->getClientCount() > 0) {
3177 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003178 return;
3179 }
3180
Eric Laurent05b90f82014-08-27 15:32:29 -07003181 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003182 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003183 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003184}
3185
Eric Laurent8f42ea12018-08-08 09:08:25 -07003186void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003187{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003188 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003189
3190 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003191 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003192 }
3193}
3194
Eric Laurent8f42ea12018-08-08 09:08:25 -07003195void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3196{
3197 stopInput(portId);
3198 releaseInput(portId);
3199}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003200
Eric Laurent0dd51852019-04-19 18:18:58 -07003201void AudioPolicyManager::checkCloseInputs() {
3202 // After connecting or disconnecting an input device, close input if:
3203 // - it has no client (was just opened to check profile) OR
3204 // - none of its supported devices are connected anymore OR
3205 // - one of its clients cannot be routed to one of its supported
3206 // devices anymore. Otherwise update device selection
3207 std::vector<audio_io_handle_t> inputsToClose;
3208 for (size_t i = 0; i < mInputs.size(); i++) {
3209 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3210 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003211 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003212 inputsToClose.push_back(mInputs.keyAt(i));
3213 } else {
3214 bool close = false;
3215 for (const auto& client : input->clientsList()) {
3216 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003217 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3218 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003219 if (!input->supportedDevices().contains(device)) {
3220 close = true;
3221 break;
3222 }
3223 }
3224 if (close) {
3225 inputsToClose.push_back(mInputs.keyAt(i));
3226 } else {
3227 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3228 }
3229 }
3230 }
3231
3232 for (const audio_io_handle_t handle : inputsToClose) {
3233 ALOGV("%s closing input %d", __func__, handle);
3234 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003235 }
Eric Laurentd4692962014-05-05 18:13:44 -07003236}
3237
François Gaffie251c7f02018-11-07 10:41:08 +01003238void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003239{
3240 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003241 if (indexMin < 0 || indexMax < 0) {
3242 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3243 return;
3244 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003245 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003246
3247 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003248 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3249 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003250 continue;
3251 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003252 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003253 }
Eric Laurente552edb2014-03-10 17:42:56 -07003254}
3255
Eric Laurente0720872014-03-11 09:30:41 -07003256status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003257 int index,
3258 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003259{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003260 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003261 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3262 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3263 return NO_ERROR;
3264 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003265 ALOGV("%s: stream %s attributes=%s", __func__,
3266 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003267 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003268}
3269
Eric Laurente0720872014-03-11 09:30:41 -07003270status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003271 int *index,
3272 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003273{
François Gaffiec005e562018-11-06 15:04:49 +01003274 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3275 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003276 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003277 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003278 deviceTypes = mEngine->getOutputDevicesForStream(
3279 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003280 }
jiabin9a3361e2019-10-01 09:38:30 -07003281 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003282}
3283
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003284status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003285 int index,
3286 audio_devices_t device)
3287{
3288 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003289 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3290 if (group == VOLUME_GROUP_NONE) {
3291 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003292 return BAD_VALUE;
3293 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003294 ALOGV("%s: group %d matching with %s index %d",
3295 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003296 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003297 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003298 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003299 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3300 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3301 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3302 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003303 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3304
3305 status = setVolumeCurveIndex(index, device, curves);
3306 if (status != NO_ERROR) {
3307 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3308 return status;
3309 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003310
jiabin9a3361e2019-10-01 09:38:30 -07003311 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003312 auto curCurvAttrs = curves.getAttributes();
3313 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3314 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003315 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003316 } else if (!curves.getStreamTypes().empty()) {
3317 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003318 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003319 } else {
3320 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3321 return BAD_VALUE;
3322 }
jiabin9a3361e2019-10-01 09:38:30 -07003323 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3324 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003325
François Gaffiecfe17322018-11-07 13:41:29 +01003326 // update volume on all outputs and streams matching the following:
3327 // - The requested stream (or a stream matching for volume control) is active on the output
3328 // - The device (or devices) selected by the engine for this stream includes
3329 // the requested device
3330 // - For non default requested device, currently selected device on the output is either the
3331 // requested device or one of the devices selected by the engine for this stream
3332 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3333 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003334 for (size_t i = 0; i < mOutputs.size(); i++) {
3335 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003336 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003337
jiabin9a3361e2019-10-01 09:38:30 -07003338 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3339 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003340 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003341
3342 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003343 continue;
3344 }
3345 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3346 curDevices.find(device) == curDevices.end()) {
3347 continue;
3348 }
3349 bool applyVolume = false;
3350 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3351 curSrcDevices.insert(device);
3352 applyVolume = (curSrcDevices.find(
3353 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3354 } else {
3355 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3356 }
3357 if (!applyVolume) {
3358 continue; // next output
3359 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003360 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3361 // If a higher priority strategy is active, and the output is routed to a device with a
3362 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003363 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003364 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003365 // If the volume source is active with higher priority source, ensure at least Sw Muted
3366 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003367 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3368 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3369 false /*preferredDevice*/);
3370 if (activeClients.empty()) {
3371 continue;
3372 }
3373 bool isPreempted = false;
3374 bool isHigherPriority = productStrategy < strategy;
3375 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003376 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003377 ALOGV("%s: Strategy=%d (\nrequester:\n"
3378 " group %d, volumeGroup=%d attributes=%s)\n"
3379 " higher priority source active:\n"
3380 " volumeGroup=%d attributes=%s) \n"
3381 " on output %zu, bailing out", __func__, productStrategy,
3382 group, group, toString(attributes).c_str(),
3383 client->volumeSource(), toString(client->attributes()).c_str(), i);
3384 applyVolume = false;
3385 isPreempted = true;
3386 break;
3387 }
3388 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003389 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003390 applyVolume = true;
3391 }
3392 }
3393 if (isPreempted || applyVolume) {
3394 break;
3395 }
3396 }
3397 if (!applyVolume) {
3398 continue; // next output
3399 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003400 }
François Gaffieed91f582020-01-31 10:35:37 +01003401 //FIXME: workaround for truncated touch sounds
3402 // delayed volume change for system stream to be removed when the problem is
3403 // handled by system UI
3404 status_t volStatus = checkAndSetVolume(
3405 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003406 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003407 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3408 if (volStatus != NO_ERROR) {
3409 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003410 }
3411 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003412
3413 // update voice volume if the an active call route exists
3414 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3415 && (curSrcDevices.find(
3416 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3417 != curSrcDevices.end())) {
3418 bool isVoiceVolSrc;
3419 bool isBtScoVolSrc;
3420 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3421 isVoiceVolSrc, isBtScoVolSrc, __func__)
3422 && (isVoiceVolSrc || isBtScoVolSrc)) {
3423 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3424 }
3425 }
3426
François Gaffiecfe17322018-11-07 13:41:29 +01003427 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3428 return status;
3429}
3430
François Gaffieaaac0fd2018-11-22 17:56:39 +01003431status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003432 audio_devices_t device,
3433 IVolumeCurves &volumeCurves)
3434{
3435 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3436 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003437 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3438 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003439 (index > volumeCurves.getVolumeIndexMax())) {
3440 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3441 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3442 return BAD_VALUE;
3443 }
3444 if (!audio_is_output_device(device)) {
3445 return BAD_VALUE;
3446 }
3447
3448 // Force max volume if stream cannot be muted
3449 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3450
François Gaffieaaac0fd2018-11-22 17:56:39 +01003451 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003452 volumeCurves.addCurrentVolumeIndex(device, index);
3453 return NO_ERROR;
3454}
3455
3456status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3457 int &index,
3458 audio_devices_t device)
3459{
3460 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3461 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003462 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003463 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003464 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003465 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003466 }
jiabin9a3361e2019-10-01 09:38:30 -07003467 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003468}
3469
3470status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3471 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003472 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003473{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003474 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003475 return BAD_VALUE;
3476 }
jiabin9a3361e2019-10-01 09:38:30 -07003477 index = curves.getVolumeIndex(deviceTypes);
3478 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003479 return NO_ERROR;
3480}
3481
3482status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3483 int &index)
3484{
3485 index = getVolumeCurves(attr).getVolumeIndexMin();
3486 return NO_ERROR;
3487}
3488
3489status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3490 int &index)
3491{
3492 index = getVolumeCurves(attr).getVolumeIndexMax();
3493 return NO_ERROR;
3494}
3495
Eric Laurent36829f92017-04-07 19:04:42 -07003496audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003497{
3498 // select one output among several suitable for global effects.
3499 // The priority is as follows:
3500 // 1: An offloaded output. If the effect ends up not being offloadable,
3501 // AudioFlinger will invalidate the track and the offloaded output
3502 // will be closed causing the effect to be moved to a PCM output.
3503 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003504 // 3: The primary output
3505 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003506
François Gaffiec005e562018-11-06 15:04:49 +01003507 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3508 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003509 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003510
Eric Laurent36829f92017-04-07 19:04:42 -07003511 if (outputs.size() == 0) {
3512 return AUDIO_IO_HANDLE_NONE;
3513 }
Eric Laurente552edb2014-03-10 17:42:56 -07003514
Eric Laurent36829f92017-04-07 19:04:42 -07003515 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3516 bool activeOnly = true;
3517
3518 while (output == AUDIO_IO_HANDLE_NONE) {
3519 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3520 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3521 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3522
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003523 for (audio_io_handle_t output : outputs) {
3524 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003525 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003526 continue;
3527 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003528 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3529 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003530 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003531 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003532 }
3533 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003534 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003535 }
3536 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003537 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003538 }
3539 }
3540 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3541 output = outputOffloaded;
3542 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3543 output = outputDeepBuffer;
3544 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3545 output = outputPrimary;
3546 } else {
3547 output = outputs[0];
3548 }
3549 activeOnly = false;
3550 }
3551
3552 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003553 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3554 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003555 mMusicEffectOutput = output;
3556 }
3557
3558 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003559 return output;
3560}
3561
Eric Laurent36829f92017-04-07 19:04:42 -07003562audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3563{
3564 return selectOutputForMusicEffects();
3565}
3566
Eric Laurente0720872014-03-11 09:30:41 -07003567status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003568 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003569 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003570 int session,
3571 int id)
3572{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003573 if (session != AUDIO_SESSION_DEVICE) {
3574 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003575 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003576 index = mInputs.indexOfKey(io);
3577 if (index < 0) {
3578 ALOGW("registerEffect() unknown io %d", io);
3579 return INVALID_OPERATION;
3580 }
Eric Laurente552edb2014-03-10 17:42:56 -07003581 }
3582 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003583 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3584 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3585 || strategy == PRODUCT_STRATEGY_NONE));
3586 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003587}
3588
Eric Laurentc241b0d2018-11-28 09:08:49 -08003589status_t AudioPolicyManager::unregisterEffect(int id)
3590{
3591 if (mEffects.getEffect(id) == nullptr) {
3592 return INVALID_OPERATION;
3593 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003594 if (mEffects.isEffectEnabled(id)) {
3595 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3596 setEffectEnabled(id, false);
3597 }
3598 return mEffects.unregisterEffect(id);
3599}
3600
3601status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3602{
3603 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3604 if (effect == nullptr) {
3605 return INVALID_OPERATION;
3606 }
3607
3608 status_t status = mEffects.setEffectEnabled(id, enabled);
3609 if (status == NO_ERROR) {
3610 mInputs.trackEffectEnabled(effect, enabled);
3611 }
3612 return status;
3613}
3614
Eric Laurent6c796322019-04-09 14:13:17 -07003615
3616status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3617{
3618 mEffects.moveEffects(ids, io);
3619 return NO_ERROR;
3620}
3621
Eric Laurentc75307b2015-03-17 15:29:32 -07003622bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3623{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003624 auto vs = toVolumeSource(stream, false);
3625 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003626}
3627
3628bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3629{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003630 auto vs = toVolumeSource(stream, false);
3631 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003632}
3633
Eric Laurente0720872014-03-11 09:30:41 -07003634bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003635{
3636 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003637 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003638 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003639 return true;
3640 }
3641 }
3642 return false;
3643}
3644
Eric Laurent275e8e92014-11-30 15:14:47 -08003645// Register a list of custom mixes with their attributes and format.
3646// When a mix is registered, corresponding input and output profiles are
3647// added to the remote submix hw module. The profile contains only the
3648// parameters (sampling rate, format...) specified by the mix.
3649// The corresponding input remote submix device is also connected.
3650//
3651// When a remote submix device is connected, the address is checked to select the
3652// appropriate profile and the corresponding input or output stream is opened.
3653//
3654// When capture starts, getInputForAttr() will:
3655// - 1 look for a mix matching the address passed in attribtutes tags if any
3656// - 2 if none found, getDeviceForInputSource() will:
3657// - 2.1 look for a mix matching the attributes source
3658// - 2.2 if none found, default to device selection by policy rules
3659// At this time, the corresponding output remote submix device is also connected
3660// and active playback use cases can be transferred to this mix if needed when reconnecting
3661// after AudioTracks are invalidated
3662//
3663// When playback starts, getOutputForAttr() will:
3664// - 1 look for a mix matching the address passed in attribtutes tags if any
3665// - 2 if none found, look for a mix matching the attributes usage
3666// - 3 if none found, default to device and output selection by policy rules.
3667
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003668status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003669{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003670 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3671 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003672 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003673 sp<HwModule> rSubmixModule;
3674 // examine each mix's route type
3675 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003676 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003677 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3678 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3679 ALOGE("Unsupported Policy Mix %zu of %zu: "
3680 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3681 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003682 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003683 break;
3684 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003685 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3686 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003687 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003688 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3689 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003690 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003691 rSubmixModule = mHwModules.getModuleFromName(
3692 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3693 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003694 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003695 i);
3696 res = INVALID_OPERATION;
3697 break;
3698 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003699 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003700
Eric Laurent97ac8712018-07-27 18:59:02 -07003701 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003702 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003703 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003704 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003705 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3706 } else {
3707 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3708 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003709 }
François Gaffie036e1e92015-03-19 10:16:24 +01003710
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003711 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003712 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003713 res = INVALID_OPERATION;
3714 break;
3715 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003716 audio_config_t outputConfig = mix.mFormat;
3717 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003718 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3719 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003720 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3721 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003722 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003723 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3724 audio_is_linear_pcm(outputConfig.format)
3725 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003726 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003727 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3728 audio_is_linear_pcm(inputConfig.format)
3729 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003730
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003731 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003732 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003733 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003734 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003735 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003736 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003737 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003738 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3739 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003740 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003741 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003742 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003743
3744 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3745 mix.mDeviceType, mix.mDeviceAddress,
3746 String8(), AUDIO_FORMAT_DEFAULT);
3747 if (device == nullptr) {
3748 res = INVALID_OPERATION;
3749 break;
3750 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003751
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003752 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003753 // First try to find an already opened output supporting the device
3754 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003755 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003756
Eric Laurentc529cf62020-04-17 18:19:10 -07003757 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003758 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003759 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003760 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003761 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003762 } else {
3763 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003764 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003765 }
3766 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003767 // If no output found, try to find a direct output profile supporting the device
3768 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3769 sp<HwModule> module = mHwModules[i];
3770 for (size_t j = 0;
3771 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3772 j++) {
3773 sp<IOProfile> profile = module->getOutputProfiles()[j];
3774 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3775 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3776 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003777 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003778 res = INVALID_OPERATION;
3779 } else {
3780 foundOutput = true;
3781 }
3782 }
3783 }
3784 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003785 if (res != NO_ERROR) {
3786 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003787 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003788 res = INVALID_OPERATION;
3789 break;
3790 } else if (!foundOutput) {
3791 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003792 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003793 res = INVALID_OPERATION;
3794 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003795 } else {
3796 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003797 }
Eric Laurentc722f302014-12-10 11:21:49 -08003798 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003799 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003800 if (res != NO_ERROR) {
3801 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003802 } else if (checkOutputs) {
3803 checkForDeviceAndOutputChanges();
3804 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003805 }
3806 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003807}
3808
3809status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3810{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003811 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003812 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003813 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003814 sp<HwModule> rSubmixModule;
3815 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003816 for (const auto& mix : mixes) {
3817 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003818
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003819 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003820 rSubmixModule = mHwModules.getModuleFromName(
3821 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3822 if (rSubmixModule == 0) {
3823 res = INVALID_OPERATION;
3824 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003825 }
3826 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003827
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003828 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003829
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003830 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003831 res = INVALID_OPERATION;
3832 continue;
3833 }
3834
Kevin Rocard04ed0462019-05-02 17:53:24 -07003835 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003836 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003837 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3838 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003839 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003840 AUDIO_FORMAT_DEFAULT);
3841 if (res != OK) {
3842 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003843 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003844 }
3845 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003846 }
jiabin5740f082019-08-19 15:08:30 -07003847 rSubmixModule->removeOutputProfile(address.c_str());
3848 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003849
Kevin Rocard153f92d2018-12-18 18:33:28 -08003850 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003851 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003852 res = INVALID_OPERATION;
3853 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003854 } else {
3855 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003856 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003857 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003858 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003859 if (res == NO_ERROR && checkOutputs) {
3860 checkForDeviceAndOutputChanges();
3861 updateCallAndOutputRouting();
3862 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003863 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003864}
3865
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003866status_t AudioPolicyManager::updatePolicyMix(
3867 const AudioMix& mix,
3868 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3869 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3870 if (res == NO_ERROR) {
3871 checkForDeviceAndOutputChanges();
3872 updateCallAndOutputRouting();
3873 }
3874 return res;
3875}
3876
Mikhail Naganov100f0122018-11-29 11:22:16 -08003877void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3878{
3879 size_t i = 0;
3880 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3881 for (const auto& fmt : mManualSurroundFormats) {
3882 if (i++ != 0) dst->append(", ");
3883 std::string sfmt;
3884 FormatConverter::toString(fmt, sfmt);
3885 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3886 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3887 }
3888}
3889
Eric Laurentc529cf62020-04-17 18:19:10 -07003890// Returns true if all devices types match the predicate and are supported by one HW module
3891bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003892 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003893 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003894 const char *context,
3895 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003896 for (size_t i = 0; i < devices.size(); i++) {
3897 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003898 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003899 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003900 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003901 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003902 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003903 return false;
3904 }
3905 }
3906 return true;
3907}
3908
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003909void AudioPolicyManager::changeOutputDevicesMuteState(
3910 const AudioDeviceTypeAddrVector& devices) {
3911 ALOGVV("%s() num devices %zu", __func__, devices.size());
3912
3913 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3914 getSoftwareOutputsForDevices(devices);
3915
3916 for (size_t i = 0; i < outputs.size(); i++) {
3917 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3918 DeviceVector prevDevices = outputDesc->devices();
3919 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3920 }
3921}
3922
3923std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3924 const AudioDeviceTypeAddrVector& devices) const
3925{
3926 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3927 DeviceVector deviceDescriptors;
3928 for (size_t j = 0; j < devices.size(); j++) {
3929 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3930 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3931 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3932 ALOGE("%s: device type %#x address %s not supported or not an output device",
3933 __func__, devices[j].mType, devices[j].getAddress());
3934 continue;
3935 }
3936 deviceDescriptors.add(desc);
3937 }
3938 for (size_t i = 0; i < mOutputs.size(); i++) {
3939 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3940 continue;
3941 }
3942 outputs.push_back(mOutputs.valueAt(i));
3943 }
3944 return outputs;
3945}
3946
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003947status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003948 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003949 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003950 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3951 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003952 }
3953 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003954 if (res != NO_ERROR) {
3955 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3956 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003957 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003958
3959 checkForDeviceAndOutputChanges();
3960 updateCallAndOutputRouting();
3961
3962 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003963}
3964
3965status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3966 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003967 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3968 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003969 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003970 __FUNCTION__, uid);
3971 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003972 }
3973
Eric Laurentc529cf62020-04-17 18:19:10 -07003974 checkForDeviceAndOutputChanges();
3975 updateCallAndOutputRouting();
3976
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003977 return res;
3978}
3979
Eric Laurent2517af32020-11-25 15:31:27 +01003980
jiabin0a488932020-08-07 17:32:40 -07003981status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3982 device_role_t role,
3983 const AudioDeviceTypeAddrVector &devices) {
3984 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3985 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003986
Eric Laurentc529cf62020-04-17 18:19:10 -07003987 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003988 return BAD_VALUE;
3989 }
jiabin0a488932020-08-07 17:32:40 -07003990 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003991 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003992 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3993 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003994 return status;
3995 }
3996
3997 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003998
3999 bool forceVolumeReeval = false;
4000 // FIXME: workaround for truncated touch sounds
4001 // to be removed when the problem is handled by system UI
4002 uint32_t delayMs = 0;
4003 if (strategy == mCommunnicationStrategy) {
4004 forceVolumeReeval = true;
4005 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4006 updateInputRouting();
4007 }
4008 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004009
4010 return NO_ERROR;
4011}
4012
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004013void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4014 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004015{
4016 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004017 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004018 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004019 // Only apply special touch sound delay once
4020 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004021 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004022 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004023 for (size_t i = 0; i < mOutputs.size(); i++) {
4024 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4025 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004026 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4027 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004028 // As done in setDeviceConnectionState, we could also fix default device issue by
4029 // preventing the force re-routing in case of default dev that distinguishes on address.
4030 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004031 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004032 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4033 // If the device is using preferred mixer attributes, the output need to reopen
4034 // with default configuration when the new selected devices are different from
4035 // current routing devices.
4036 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4037 continue;
4038 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304039
4040 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4041 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004042 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004043 // Only apply special touch sound delay once
4044 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004045 }
4046 if (forceVolumeReeval && !newDevices.isEmpty()) {
4047 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4048 }
4049 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004050 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004051 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004052}
4053
Eric Laurent2517af32020-11-25 15:31:27 +01004054void AudioPolicyManager::updateInputRouting() {
4055 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304056 // Skip for hotword recording as the input device switch
4057 // is handled within sound trigger HAL
4058 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4059 continue;
4060 }
Eric Laurent2517af32020-11-25 15:31:27 +01004061 auto newDevice = getNewInputDevice(activeDesc);
4062 // Force new input selection if the new device can not be reached via current input
4063 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4064 setInputDevice(activeDesc->mIoHandle, newDevice);
4065 } else {
4066 closeInput(activeDesc->mIoHandle);
4067 }
4068 }
4069}
4070
Paul Wang5d7cdb52022-11-22 09:45:06 +00004071status_t
4072AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4073 device_role_t role,
4074 const AudioDeviceTypeAddrVector &devices) {
4075 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4076 dumpAudioDeviceTypeAddrVector(devices).c_str());
4077
Eric Laurent78fedbf2023-03-09 14:40:44 +01004078 if (!areAllDevicesSupported(
4079 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004080 return BAD_VALUE;
4081 }
4082 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4083 if (status != NO_ERROR) {
4084 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4085 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4086 return status;
4087 }
4088
4089 checkForDeviceAndOutputChanges();
4090
4091 bool forceVolumeReeval = false;
4092 // TODO(b/263479999): workaround for truncated touch sounds
4093 // to be removed when the problem is handled by system UI
4094 uint32_t delayMs = 0;
4095 if (strategy == mCommunnicationStrategy) {
4096 forceVolumeReeval = true;
4097 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4098 updateInputRouting();
4099 }
4100 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4101
4102 return NO_ERROR;
4103}
4104
4105status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4106 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004107{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004108 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004109
Paul Wang5d7cdb52022-11-22 09:45:06 +00004110 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004111 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004112 ALOGW_IF(status != NAME_NOT_FOUND,
4113 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004114 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004115 return status;
4116 }
4117
4118 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004119
4120 bool forceVolumeReeval = false;
4121 // FIXME: workaround for truncated touch sounds
4122 // to be removed when the problem is handled by system UI
4123 uint32_t delayMs = 0;
4124 if (strategy == mCommunnicationStrategy) {
4125 forceVolumeReeval = true;
4126 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4127 updateInputRouting();
4128 }
4129 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004130
4131 return NO_ERROR;
4132}
4133
jiabin0a488932020-08-07 17:32:40 -07004134status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4135 device_role_t role,
4136 AudioDeviceTypeAddrVector &devices) {
4137 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004138}
4139
Jiabin Huang3b98d322020-09-03 17:54:16 +00004140status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4141 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4142 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4143 dumpAudioDeviceTypeAddrVector(devices).c_str());
4144
Mikhail Naganov55773032020-10-01 15:08:13 -07004145 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004146 return BAD_VALUE;
4147 }
4148 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4149 ALOGW_IF(status != NO_ERROR,
4150 "Engine could not set preferred devices %s for audio source %d role %d",
4151 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4152
4153 return status;
4154}
4155
4156status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4157 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4158 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4159 dumpAudioDeviceTypeAddrVector(devices).c_str());
4160
Mikhail Naganov55773032020-10-01 15:08:13 -07004161 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004162 return BAD_VALUE;
4163 }
4164 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4165 ALOGW_IF(status != NO_ERROR,
4166 "Engine could not add preferred devices %s for audio source %d role %d",
4167 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4168
Eric Laurent2517af32020-11-25 15:31:27 +01004169 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004170 return status;
4171}
4172
4173status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4174 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4175{
4176 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4177 dumpAudioDeviceTypeAddrVector(devices).c_str());
4178
Eric Laurent78fedbf2023-03-09 14:40:44 +01004179 if (!areAllDevicesSupported(
4180 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004181 return BAD_VALUE;
4182 }
4183
4184 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4185 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004186 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004187 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004188 if (status == NO_ERROR) {
4189 updateInputRouting();
4190 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004191 return status;
4192}
4193
4194status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4195 device_role_t role) {
4196 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4197
4198 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004199 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004200 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004201 if (status == NO_ERROR) {
4202 updateInputRouting();
4203 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004204 return status;
4205}
4206
4207status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4208 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4209 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4210}
4211
Oscar Azucena90e77632019-11-27 17:12:28 -08004212status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004213 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004214 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004215 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4216 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004217 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004218 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4219 if (status != NO_ERROR) {
4220 ALOGE("%s() could not set device affinity for userId %d",
4221 __FUNCTION__, userId);
4222 return status;
4223 }
4224
4225 // reevaluate outputs for all devices
4226 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004227 changeOutputDevicesMuteState(devices);
4228 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4229 true /* skipDelays */);
4230 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004231
4232 return NO_ERROR;
4233}
4234
4235status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004236 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004237 AudioDeviceTypeAddrVector devices;
4238 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004239 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4240 if (status != NO_ERROR) {
4241 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4242 __FUNCTION__, userId);
4243 return status;
4244 }
4245
4246 // reevaluate outputs for all devices
4247 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004248 changeOutputDevicesMuteState(devices);
4249 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4250 true /* skipDelays */);
4251 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004252
4253 return NO_ERROR;
4254}
4255
Andy Hungc29d82b2018-10-05 12:23:17 -07004256void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004257{
Andy Hungc29d82b2018-10-05 12:23:17 -07004258 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004259 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004260 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004261 std::string stateLiteral;
4262 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004263 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004264 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4265 "communications", "media", "record", "dock", "system",
4266 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4267 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4268 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004269 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4270 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4271 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4272 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4273 dst->append(" (MANUAL: ");
4274 dumpManualSurroundFormats(dst);
4275 dst->append(")");
4276 }
4277 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004278 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004279 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4280 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004281 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004282 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004283
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004284 dst->append("\n");
4285 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4286 dst->append("\n");
4287 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004288 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004289 mOutputs.dump(dst);
4290 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004291 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004292 mAudioPatches.dump(dst);
4293 mPolicyMixes.dump(dst);
4294 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004295
Kevin Rocardb99cc752019-03-21 20:52:24 -07004296 dst->appendFormat(" AllowedCapturePolicies:\n");
4297 for (auto& policy : mAllowedCapturePolicies) {
4298 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4299 }
4300
jiabina84c3d32022-12-02 18:59:55 +00004301 dst->appendFormat(" Preferred mixer audio configuration:\n");
4302 for (const auto it : mPreferredMixerAttrInfos) {
4303 dst->appendFormat(" - device port id: %d\n", it.first);
4304 for (const auto preferredMixerInfoIt : it.second) {
4305 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4306 preferredMixerInfoIt.second->dump(dst);
4307 }
4308 }
4309
François Gaffiec005e562018-11-06 15:04:49 +01004310 dst->appendFormat("\nPolicy Engine dump:\n");
4311 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004312}
4313
4314status_t AudioPolicyManager::dump(int fd)
4315{
4316 String8 result;
4317 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004318 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004319 return NO_ERROR;
4320}
4321
Kevin Rocardb99cc752019-03-21 20:52:24 -07004322status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4323{
4324 mAllowedCapturePolicies[uid] = capturePolicy;
4325 return NO_ERROR;
4326}
4327
Eric Laurente552edb2014-03-10 17:42:56 -07004328// This function checks for the parameters which can be offloaded.
4329// This can be enhanced depending on the capability of the DSP and policy
4330// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004331audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004332{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004333 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004334 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004335 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004336 offloadInfo.format,
4337 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4338 offloadInfo.has_video);
4339
jiabin2b9d5a12021-12-10 01:06:29 +00004340 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004341 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004342 }
4343
4344 // See if there is a profile to support this.
4345 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004346 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004347 offloadInfo.sample_rate,
4348 offloadInfo.format,
4349 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004350 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4351 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004352 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4353 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4354 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004355 if (profile == nullptr) {
4356 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4357 }
4358 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4359 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4360 }
4361 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004362}
4363
Michael Chana94fbb22018-04-24 14:31:19 +10004364bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4365 const audio_attributes_t& attributes) {
4366 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004367 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004368 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4369 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004370 config.sample_rate,
4371 config.format,
4372 config.channel_mask,
4373 output_flags,
4374 true /* directOnly */);
4375 ALOGV("%s() profile %sfound with name: %s, "
4376 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4377 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004378 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004379 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004380
4381 // also try the MSD module if compatible profile not found
4382 if (profile == nullptr) {
4383 profile = getMsdProfileForOutput(outputDevices,
4384 config.sample_rate,
4385 config.format,
4386 config.channel_mask,
4387 output_flags,
4388 true /* directOnly */);
4389 ALOGV("%s() MSD profile %sfound with name: %s, "
4390 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4391 __FUNCTION__, profile != 0 ? "" : "NOT ",
4392 (profile != 0 ? profile->getTagName().c_str() : "null"),
4393 config.sample_rate, config.format, config.channel_mask, output_flags);
4394 }
4395 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004396}
4397
jiabin2b9d5a12021-12-10 01:06:29 +00004398bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4399 bool durationIgnored) {
4400 if (mMasterMono) {
4401 return false; // no offloading if mono is set.
4402 }
4403
4404 // Check if offload has been disabled
4405 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4406 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4407 return false;
4408 }
4409
4410 // Check if stream type is music, then only allow offload as of now.
4411 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4412 {
4413 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4414 return false;
4415 }
4416
4417 //TODO: enable audio offloading with video when ready
4418 const bool allowOffloadWithVideo =
4419 property_get_bool("audio.offload.video", false /* default_value */);
4420 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4421 ALOGV("%s: has_video == true, returning false", __func__);
4422 return false;
4423 }
4424
4425 //If duration is less than minimum value defined in property, return false
4426 const int min_duration_secs = property_get_int32(
4427 "audio.offload.min.duration.secs", -1 /* default_value */);
4428 if (!durationIgnored) {
4429 if (min_duration_secs >= 0) {
4430 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4431 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4432 __func__, min_duration_secs);
4433 return false;
4434 }
4435 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4436 ALOGV("%s: Offload denied by duration < default min(=%u)",
4437 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4438 return false;
4439 }
4440 }
4441
4442 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4443 // creating an offloaded track and tearing it down immediately after start when audioflinger
4444 // detects there is an active non offloadable effect.
4445 // FIXME: We should check the audio session here but we do not have it in this context.
4446 // This may prevent offloading in rare situations where effects are left active by apps
4447 // in the background.
4448 if (mEffects.isNonOffloadableEffectEnabled()) {
4449 return false;
4450 }
4451
4452 return true;
4453}
4454
4455audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4456 const audio_config_t *config) {
4457 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4458 offloadInfo.format = config->format;
4459 offloadInfo.sample_rate = config->sample_rate;
4460 offloadInfo.channel_mask = config->channel_mask;
4461 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4462 offloadInfo.has_video = false;
4463 offloadInfo.is_streaming = false;
4464 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4465
4466 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4467 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4468 audio_flags_to_audio_output_flags(attr->flags, &flags);
4469 // only retain flags that will drive compressed offload or passthrough
4470 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4471 if (offloadPossible) {
4472 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4473 }
4474 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4475
Dorin Drimusfae3c642022-03-17 18:36:30 +01004476 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004477 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004478 DeviceVector outputDevices = engineOutputDevices;
4479 // the MSD module checks for different conditions and output devices
4480 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4481 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4482 continue;
4483 }
4484 outputDevices = getMsdAudioOutDevices();
4485 }
jiabin2b9d5a12021-12-10 01:06:29 +00004486 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004487 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004488 config->sample_rate, nullptr /*updatedSamplingRate*/,
4489 config->format, nullptr /*updatedFormat*/,
4490 config->channel_mask, nullptr /*updatedChannelMask*/,
4491 flags)) {
4492 continue;
4493 }
4494 // reject profiles not corresponding to a device currently available
4495 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4496 continue;
4497 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004498 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4499 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004500 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004501 != AUDIO_DIRECT_NOT_SUPPORTED) {
4502 // Already reports offload gapless supported. No need to report offload support.
4503 continue;
4504 }
4505 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4506 != AUDIO_OUTPUT_FLAG_NONE) {
4507 // If offload gapless is reported, no need to report offload support.
4508 directMode = (audio_direct_mode_t) ((directMode &
4509 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4510 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4511 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004512 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004513 }
4514 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004515 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004516 }
4517 }
4518 }
4519 return directMode;
4520}
4521
Dorin Drimusf2196d82022-01-03 12:11:18 +01004522status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4523 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004524 if (mEffects.isNonOffloadableEffectEnabled()) {
4525 return OK;
4526 }
jiabinf1c73972022-04-14 16:28:52 -07004527 DeviceVector devices;
4528 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004529 if (status != OK) {
4530 return status;
4531 }
4532 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4533 if (devices.empty()) {
4534 return OK; // no output devices for the attributes
4535 }
jiabinf1c73972022-04-14 16:28:52 -07004536 return getProfilesForDevices(devices, audioProfilesVector,
4537 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004538}
4539
jiabina84c3d32022-12-02 18:59:55 +00004540status_t AudioPolicyManager::getSupportedMixerAttributes(
4541 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4542 ALOGV("%s, portId=%d", __func__, portId);
4543 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4544 if (deviceDescriptor == nullptr) {
4545 ALOGE("%s the requested device is currently unavailable", __func__);
4546 return BAD_VALUE;
4547 }
jiabin96daffc2023-05-11 17:51:55 +00004548 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4549 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4550 deviceDescriptor->type());
4551 return BAD_VALUE;
4552 }
jiabina84c3d32022-12-02 18:59:55 +00004553 for (const auto& hwModule : mHwModules) {
4554 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4555 if (curProfile->supportsDevice(deviceDescriptor)) {
4556 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4557 }
4558 }
4559 }
4560 return NO_ERROR;
4561}
4562
4563status_t AudioPolicyManager::setPreferredMixerAttributes(
4564 const audio_attributes_t *attr,
4565 audio_port_handle_t portId,
4566 uid_t uid,
4567 const audio_mixer_attributes_t *mixerAttributes) {
4568 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4569 "mixerBehavior=%d}, uid=%d, portId=%u",
4570 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4571 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4572 mixerAttributes->mixer_behavior, uid, portId);
4573 if (attr->usage != AUDIO_USAGE_MEDIA) {
4574 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4575 return BAD_VALUE;
4576 }
4577 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4578 if (deviceDescriptor == nullptr) {
4579 ALOGE("%s the requested device is currently unavailable", __func__);
4580 return BAD_VALUE;
4581 }
4582 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4583 ALOGE("%s(%d), type=%d, is not a usb output device",
4584 __func__, portId, deviceDescriptor->type());
4585 return BAD_VALUE;
4586 }
4587
4588 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4589 audio_flags_to_audio_output_flags(attr->flags, &flags);
4590 flags = (audio_output_flags_t) (flags |
4591 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4592 sp<IOProfile> profile = nullptr;
4593 DeviceVector devices(deviceDescriptor);
4594 for (const auto& hwModule : mHwModules) {
4595 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4596 if (curProfile->hasDynamicAudioProfile()
4597 && curProfile->isCompatibleProfile(devices,
4598 mixerAttributes->config.sample_rate,
4599 nullptr /*updatedSamplingRate*/,
4600 mixerAttributes->config.format,
4601 nullptr /*updatedFormat*/,
4602 mixerAttributes->config.channel_mask,
4603 nullptr /*updatedChannelMask*/,
4604 flags,
4605 false /*exactMatchRequiredForInputFlags*/)) {
4606 profile = curProfile;
4607 break;
4608 }
4609 }
4610 }
4611 if (profile == nullptr) {
4612 ALOGE("%s, there is no compatible profile found", __func__);
4613 return BAD_VALUE;
4614 }
4615
4616 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4617 sp<PreferredMixerAttributesInfo>::make(
4618 uid, portId, profile, flags, *mixerAttributes);
4619 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4620 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4621
4622 // If 1) there is any client from the preferred mixer configuration owner that is currently
4623 // active and matches the strategy and 2) current output is on the preferred device and the
4624 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4625 // configuration.
4626 std::vector<audio_io_handle_t> outputsToReopen;
4627 for (size_t i = 0; i < mOutputs.size(); i++) {
4628 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004629 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4630 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4631 output->mUsePreferredMixerAttributes = true;
4632 } else {
4633 for (const auto &client: output->getActiveClients()) {
4634 if (client->uid() == uid && client->strategy() == strategy) {
4635 client->setIsInvalid();
4636 outputsToReopen.push_back(output->mIoHandle);
4637 }
jiabina84c3d32022-12-02 18:59:55 +00004638 }
4639 }
4640 }
4641 }
4642 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4643 config.sample_rate = mixerAttributes->config.sample_rate;
4644 config.channel_mask = mixerAttributes->config.channel_mask;
4645 config.format = mixerAttributes->config.format;
4646 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004647 sp<SwAudioOutputDescriptor> desc =
4648 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4649 if (desc == nullptr) {
4650 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4651 continue;
4652 }
4653 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004654 }
4655
4656 return NO_ERROR;
4657}
4658
4659sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004660 audio_port_handle_t devicePortId,
4661 product_strategy_t strategy,
4662 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004663 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4664 if (it == mPreferredMixerAttrInfos.end()) {
4665 return nullptr;
4666 }
jiabind9a58d32023-06-01 17:57:30 +00004667 if (activeBitPerfectPreferred) {
4668 for (auto [strategy, info] : it->second) {
4669 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4670 && info->getActiveClientCount() != 0) {
4671 return info;
4672 }
4673 }
jiabina84c3d32022-12-02 18:59:55 +00004674 }
jiabind9a58d32023-06-01 17:57:30 +00004675 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4676 return strategyMatchedMixerAttrInfoIt == it->second.end()
4677 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004678}
4679
4680status_t AudioPolicyManager::getPreferredMixerAttributes(
4681 const audio_attributes_t *attr,
4682 audio_port_handle_t portId,
4683 audio_mixer_attributes_t* mixerAttributes) {
4684 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4685 portId, mEngine->getProductStrategyForAttributes(*attr));
4686 if (info == nullptr) {
4687 return NAME_NOT_FOUND;
4688 }
4689 *mixerAttributes = info->getMixerAttributes();
4690 return NO_ERROR;
4691}
4692
4693status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4694 audio_port_handle_t portId,
4695 uid_t uid) {
4696 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4697 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4698 if (preferredMixerAttrInfo == nullptr) {
4699 return NAME_NOT_FOUND;
4700 }
4701 if (preferredMixerAttrInfo->getUid() != uid) {
4702 ALOGE("%s, requested uid=%d, owned uid=%d",
4703 __func__, uid, preferredMixerAttrInfo->getUid());
4704 return PERMISSION_DENIED;
4705 }
4706 mPreferredMixerAttrInfos[portId].erase(strategy);
4707 if (mPreferredMixerAttrInfos[portId].empty()) {
4708 mPreferredMixerAttrInfos.erase(portId);
4709 }
4710
4711 // Reconfig existing output
4712 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4713 for (size_t i = 0; i < mOutputs.size(); i++) {
4714 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4715 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4716 }
4717 }
4718 for (const auto output : potentialOutputsToReopen) {
4719 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4720 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4721 preferredMixerAttrInfo->getFlags())) {
4722 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4723 }
4724 }
4725 return NO_ERROR;
4726}
4727
Eric Laurent6a94d692014-05-20 11:18:06 -07004728status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4729 audio_port_type_t type,
4730 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004731 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004732 unsigned int *generation)
4733{
jiabin19cdba52020-11-24 11:28:58 -08004734 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4735 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004736 return BAD_VALUE;
4737 }
4738 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004739 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004740 *num_ports = 0;
4741 }
4742
4743 size_t portsWritten = 0;
4744 size_t portsMax = *num_ports;
4745 *num_ports = 0;
4746 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004747 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4748 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004749 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004750 for (const auto& dev : mAvailableOutputDevices) {
4751 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004752 continue;
4753 }
4754 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004755 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004756 }
4757 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004758 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004759 }
4760 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004761 for (const auto& dev : mAvailableInputDevices) {
4762 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004763 continue;
4764 }
4765 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004766 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004767 }
4768 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004769 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004770 }
4771 }
4772 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4773 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4774 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4775 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4776 }
4777 *num_ports += mInputs.size();
4778 }
4779 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004780 size_t numOutputs = 0;
4781 for (size_t i = 0; i < mOutputs.size(); i++) {
4782 if (!mOutputs[i]->isDuplicated()) {
4783 numOutputs++;
4784 if (portsWritten < portsMax) {
4785 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4786 }
4787 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004788 }
Eric Laurent84c70242014-06-23 08:46:27 -07004789 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004790 }
4791 }
jiabina84c3d32022-12-02 18:59:55 +00004792
Eric Laurent6a94d692014-05-20 11:18:06 -07004793 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004794 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004795 return NO_ERROR;
4796}
4797
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004798status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4799 std::vector<media::AudioPortFw>* _aidl_return) {
4800 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4801 audio_port_v7 port;
4802 dev->toAudioPort(&port);
4803 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4804 _aidl_return->push_back(std::move(aidlPort));
4805 return OK;
4806 };
4807
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004808 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004809 for (const auto& dev : module->getDeclaredDevices()) {
4810 if (role == media::AudioPortRole::NONE ||
4811 ((role == media::AudioPortRole::SOURCE)
4812 == audio_is_input_device(dev->type()))) {
4813 RETURN_STATUS_IF_ERROR(pushPort(dev));
4814 }
4815 }
4816 }
4817 return OK;
4818}
4819
jiabin19cdba52020-11-24 11:28:58 -08004820status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004821{
Eric Laurent99fcae42018-05-17 16:59:18 -07004822 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4823 return BAD_VALUE;
4824 }
4825 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4826 if (dev != 0) {
4827 dev->toAudioPort(port);
4828 return NO_ERROR;
4829 }
4830 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4831 if (dev != 0) {
4832 dev->toAudioPort(port);
4833 return NO_ERROR;
4834 }
4835 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4836 if (out != 0) {
4837 out->toAudioPort(port);
4838 return NO_ERROR;
4839 }
4840 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4841 if (in != 0) {
4842 in->toAudioPort(port);
4843 return NO_ERROR;
4844 }
4845 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004846}
4847
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004848status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4849 audio_patch_handle_t *handle,
4850 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004851{
François Gaffieafd4cea2019-11-18 15:50:22 +01004852 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004853 if (handle == NULL || patch == NULL) {
4854 return BAD_VALUE;
4855 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004856 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004857 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004858 return BAD_VALUE;
4859 }
4860 // only one source per audio patch supported for now
4861 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004862 return INVALID_OPERATION;
4863 }
Eric Laurent874c42872014-08-08 15:13:39 -07004864 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004865 return INVALID_OPERATION;
4866 }
Eric Laurent874c42872014-08-08 15:13:39 -07004867 for (size_t i = 0; i < patch->num_sinks; i++) {
4868 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4869 return INVALID_OPERATION;
4870 }
4871 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004872
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004873 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4874 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4875 if (srcDevice == nullptr || sinkDevice == nullptr) {
4876 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4877 return BAD_VALUE;
4878 }
4879 ALOGV("%s between source %s and sink %s", __func__,
4880 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4881 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4882 // Default attributes, default volume priority, not to infer with non raw audio patches.
4883 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4884 const struct audio_port_config *source = &patch->sources[0];
4885 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004886 new SourceClientDescriptor(
4887 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4888 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4889 true);
4890 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004891
4892 status_t status =
4893 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4894
4895 if (status != NO_ERROR) {
4896 return INVALID_OPERATION;
4897 }
4898 mAudioSources.add(portId, sourceDesc);
4899 return NO_ERROR;
4900}
4901
4902status_t AudioPolicyManager::connectAudioSourceToSink(
4903 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4904 const struct audio_patch *patch,
4905 audio_patch_handle_t &handle,
4906 uid_t uid, uint32_t delayMs)
4907{
4908 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4909 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4910 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4911 return INVALID_OPERATION;
4912 }
4913 sourceDesc->connect(handle, sinkDevice);
4914 if (isMsdPatch(handle)) {
4915 return NO_ERROR;
4916 }
4917 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4918 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4919 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4920 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4921 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4922 goto FailurePatchAdded;
4923 }
4924 status = swOutput->start();
4925 if (status != NO_ERROR) {
4926 goto FailureSourceAdded;
4927 }
4928 swOutput->addClient(sourceDesc);
4929 status = startSource(swOutput, sourceDesc, &delayMs);
4930 if (status != NO_ERROR) {
4931 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4932 goto FailureSourceActive;
4933 }
4934 if (delayMs != 0) {
4935 usleep(delayMs * 1000);
4936 }
4937 return NO_ERROR;
4938
4939FailureSourceActive:
4940 swOutput->stop();
4941 releaseOutput(sourceDesc->portId());
4942FailureSourceAdded:
4943 sourceDesc->setSwOutput(nullptr);
4944FailurePatchAdded:
4945 releaseAudioPatchInternal(handle);
4946 return INVALID_OPERATION;
4947}
4948
4949status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4950 audio_patch_handle_t *handle,
4951 uid_t uid, uint32_t delayMs,
4952 const sp<SourceClientDescriptor>& sourceDesc)
4953{
4954 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004955 sp<AudioPatch> patchDesc;
4956 ssize_t index = mAudioPatches.indexOfKey(*handle);
4957
François Gaffieafd4cea2019-11-18 15:50:22 +01004958 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4959 patch->sources[0].role,
4960 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004961#if LOG_NDEBUG == 0
4962 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004963 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4964 patch->sinks[i].role,
4965 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004966 }
4967#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004968
4969 if (index >= 0) {
4970 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004971 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4972 __func__, mUidCached, patchDesc->getUid(), uid);
4973 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004974 return INVALID_OPERATION;
4975 }
4976 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004977 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004978 }
4979
4980 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004981 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004982 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004983 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004984 return BAD_VALUE;
4985 }
Eric Laurent84c70242014-06-23 08:46:27 -07004986 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4987 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004988 if (patchDesc != 0) {
4989 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004990 ALOGV("%s source id differs for patch current id %d new id %d",
4991 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004992 return BAD_VALUE;
4993 }
4994 }
Eric Laurent874c42872014-08-08 15:13:39 -07004995 DeviceVector devices;
4996 for (size_t i = 0; i < patch->num_sinks; i++) {
4997 // Only support mix to devices connection
4998 // TODO add support for mix to mix connection
4999 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005000 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005001 return INVALID_OPERATION;
5002 }
5003 sp<DeviceDescriptor> devDesc =
5004 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5005 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005006 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005007 return BAD_VALUE;
5008 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005009
François Gaffie11d30102018-11-02 16:09:09 +01005010 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07005011 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01005012 NULL, // updatedSamplingRate
5013 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005014 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01005015 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005016 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01005017 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005018 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005019 return INVALID_OPERATION;
5020 }
5021 devices.add(devDesc);
5022 }
5023 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 return INVALID_OPERATION;
5025 }
Eric Laurent874c42872014-08-08 15:13:39 -07005026
Eric Laurent6a94d692014-05-20 11:18:06 -07005027 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005028 ALOGV("%s setting device %s on output %d",
5029 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305030 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005031 index = mAudioPatches.indexOfKey(*handle);
5032 if (index >= 0) {
5033 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005034 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005035 }
5036 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005037 patchDesc->setUid(uid);
5038 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005039 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005040 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005041 return INVALID_OPERATION;
5042 }
5043 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5044 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5045 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005046 // only one sink supported when connecting an input device to a mix
5047 if (patch->num_sinks > 1) {
5048 return INVALID_OPERATION;
5049 }
François Gaffie53615e22015-03-19 09:24:12 +01005050 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005051 if (inputDesc == NULL) {
5052 return BAD_VALUE;
5053 }
5054 if (patchDesc != 0) {
5055 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5056 return BAD_VALUE;
5057 }
5058 }
François Gaffie11d30102018-11-02 16:09:09 +01005059 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005060 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005061 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005062 return BAD_VALUE;
5063 }
5064
François Gaffie11d30102018-11-02 16:09:09 +01005065 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005066 patch->sinks[0].sample_rate,
5067 NULL, /*updatedSampleRate*/
5068 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005069 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005070 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005071 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005072 // FIXME for the parameter type,
5073 // and the NONE
5074 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005075 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005076 return INVALID_OPERATION;
5077 }
5078 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005079 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005080 device->toString().c_str(), inputDesc->mIoHandle);
5081 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005082 index = mAudioPatches.indexOfKey(*handle);
5083 if (index >= 0) {
5084 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005085 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005086 }
5087 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005088 patchDesc->setUid(uid);
5089 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005090 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005091 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005092 return INVALID_OPERATION;
5093 }
5094 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5095 // device to device connection
5096 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005097 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005098 return BAD_VALUE;
5099 }
5100 }
François Gaffie11d30102018-11-02 16:09:09 +01005101 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005102 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005103 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005104 return BAD_VALUE;
5105 }
Eric Laurent874c42872014-08-08 15:13:39 -07005106
Eric Laurent6a94d692014-05-20 11:18:06 -07005107 //update source and sink with our own data as the data passed in the patch may
5108 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005109 PatchBuilder patchBuilder;
5110 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005111
5112 // if first sink is to MSD, establish single MSD patch
5113 if (getMsdAudioOutDevices().contains(
5114 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5115 ALOGV("%s patching to MSD", __FUNCTION__);
5116 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5117 goto installPatch;
5118 }
5119
François Gaffieafd4cea2019-11-18 15:50:22 +01005120 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5121 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005122
Eric Laurent874c42872014-08-08 15:13:39 -07005123 for (size_t i = 0; i < patch->num_sinks; i++) {
5124 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005125 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005126 return INVALID_OPERATION;
5127 }
François Gaffie11d30102018-11-02 16:09:09 +01005128 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005129 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005130 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005131 return BAD_VALUE;
5132 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005133 audio_port_config sinkPortConfig = {};
5134 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5135 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005136
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005137 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5138 // volume management purpose (tracking activity)
5139 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5140 // in config XML to reach the sink so that is can be declared as available.
5141 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005142 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005143 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005144 // take care of dynamic routing for SwOutput selection,
5145 audio_attributes_t attributes = sourceDesc->attributes();
5146 audio_stream_type_t stream = sourceDesc->stream();
5147 audio_attributes_t resultAttr;
5148 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5149 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005150 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5151 config.channel_mask =
5152 (audio_channel_mask_get_representation(sourceMask)
5153 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5154 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005155 config.format = sourceDesc->config().format;
5156 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5157 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5158 bool isRequestedDeviceForExclusiveUse = false;
5159 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005160 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005161 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005162 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5163 &stream, sourceDesc->uid(), &config, &flags,
5164 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005165 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005166 if (output == AUDIO_IO_HANDLE_NONE) {
5167 ALOGV("%s no output for device %s",
5168 __FUNCTION__, sinkDevice->toString().c_str());
5169 return INVALID_OPERATION;
5170 }
5171 outputDesc = mOutputs.valueFor(output);
5172 if (outputDesc->isDuplicated()) {
5173 ALOGE("%s output is duplicated", __func__);
5174 return INVALID_OPERATION;
5175 }
François Gaffie7e39df22022-04-26 12:48:49 +02005176 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5177 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005178 } else {
5179 // Same for "raw patches" aka created from createAudioPatch API
5180 SortedVector<audio_io_handle_t> outputs =
5181 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5182 // if the sink device is reachable via an opened output stream, request to
5183 // go via this output stream by adding a second source to the patch
5184 // description
5185 output = selectOutput(outputs);
5186 if (output == AUDIO_IO_HANDLE_NONE) {
5187 ALOGE("%s no output available for internal patch sink", __func__);
5188 return INVALID_OPERATION;
5189 }
5190 outputDesc = mOutputs.valueFor(output);
5191 if (outputDesc->isDuplicated()) {
5192 ALOGV("%s output for device %s is duplicated",
5193 __func__, sinkDevice->toString().c_str());
5194 return INVALID_OPERATION;
5195 }
François Gaffie7e39df22022-04-26 12:48:49 +02005196 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005197 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005198 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005199 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005200 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005201 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005202 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5203 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005204 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5205 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005206 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005207 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005208 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005209 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005210 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005211 return INVALID_OPERATION;
5212 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005213 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005214 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005215 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005216 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005217 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005218 srcMixPortConfig.ext.mix.usecase.stream =
5219 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005220 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5221 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005222 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005223 }
Eric Laurent83b88082014-06-20 18:31:16 -07005224 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005225 }
5226 // TODO: check from routing capabilities in config file and other conflicting patches
5227
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005228installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005229 status_t status = installPatch(
5230 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005231 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005232 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005233 return INVALID_OPERATION;
5234 }
5235 } else {
5236 return BAD_VALUE;
5237 }
5238 } else {
5239 return BAD_VALUE;
5240 }
5241 return NO_ERROR;
5242}
5243
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005244status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005245{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005246 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005247 ssize_t index = mAudioPatches.indexOfKey(handle);
5248
5249 if (index < 0) {
5250 return BAD_VALUE;
5251 }
5252 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005253 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5254 __func__, mUidCached, patchDesc->getUid(), uid);
5255 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005256 return INVALID_OPERATION;
5257 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005258 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5259 for (size_t i = 0; i < mAudioSources.size(); i++) {
5260 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5261 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5262 portId = sourceDesc->portId();
5263 break;
5264 }
5265 }
5266 return portId != AUDIO_PORT_HANDLE_NONE ?
5267 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005268}
Eric Laurent6a94d692014-05-20 11:18:06 -07005269
François Gaffieafd4cea2019-11-18 15:50:22 +01005270status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005271 uint32_t delayMs,
5272 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005273{
5274 ALOGV("%s patch %d", __func__, handle);
5275 if (mAudioPatches.indexOfKey(handle) < 0) {
5276 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5277 return BAD_VALUE;
5278 }
5279 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005280 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005281 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005282 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005283 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005284 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005285 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005286 return BAD_VALUE;
5287 }
5288
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305289 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005290 getNewOutputDevices(outputDesc, true /*fromCache*/),
5291 true,
5292 0,
5293 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005294 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5295 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005296 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005297 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005298 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005299 return BAD_VALUE;
5300 }
5301 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005302 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005303 true,
5304 NULL);
5305 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005306 status_t status =
5307 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5308 ALOGV("%s patch panel returned %d patchHandle %d",
5309 __func__, status, patchDesc->getAfHandle());
5310 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005311 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005312 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005313 // SW or HW Bridge
5314 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5315 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005316 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005317 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5318 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5319 outputDesc = sourceDesc->swOutput().promote();
5320 }
5321 if (outputDesc == nullptr) {
5322 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5323 // releaseOutput has already called closeOutput in case of direct output
5324 return NO_ERROR;
5325 }
François Gaffie7e39df22022-04-26 12:48:49 +02005326 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005327 // While using a HwBridge, force reconsidering device only if not reusing an existing
5328 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005329 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005330 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5331 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5332 // Reconsider device only for cases:
5333 // 1 / Active Output
5334 // 2 / Inactive Output previously hosting HwBridge
5335 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5336 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5337 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305338 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005339 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5340 outputDesc->devices(),
5341 force,
5342 0,
5343 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005344 } else {
5345 return BAD_VALUE;
5346 }
5347 } else {
5348 return BAD_VALUE;
5349 }
5350 return NO_ERROR;
5351}
5352
5353status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5354 struct audio_patch *patches,
5355 unsigned int *generation)
5356{
François Gaffie53615e22015-03-19 09:24:12 +01005357 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005358 return BAD_VALUE;
5359 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005360 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005361 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005362}
5363
Eric Laurente1715a42014-05-20 11:30:42 -07005364status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005365{
Eric Laurente1715a42014-05-20 11:30:42 -07005366 ALOGV("setAudioPortConfig()");
5367
5368 if (config == NULL) {
5369 return BAD_VALUE;
5370 }
5371 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5372 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005373 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5374 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005375 }
5376
Eric Laurenta121f902014-06-03 13:32:54 -07005377 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005378 if (config->type == AUDIO_PORT_TYPE_MIX) {
5379 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005380 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005381 if (outputDesc == NULL) {
5382 return BAD_VALUE;
5383 }
Eric Laurent84c70242014-06-23 08:46:27 -07005384 ALOG_ASSERT(!outputDesc->isDuplicated(),
5385 "setAudioPortConfig() called on duplicated output %d",
5386 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005387 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005388 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005389 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005390 if (inputDesc == NULL) {
5391 return BAD_VALUE;
5392 }
Eric Laurenta121f902014-06-03 13:32:54 -07005393 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005394 } else {
5395 return BAD_VALUE;
5396 }
5397 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5398 sp<DeviceDescriptor> deviceDesc;
5399 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5400 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5401 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5402 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5403 } else {
5404 return BAD_VALUE;
5405 }
5406 if (deviceDesc == NULL) {
5407 return BAD_VALUE;
5408 }
Eric Laurenta121f902014-06-03 13:32:54 -07005409 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005410 } else {
5411 return BAD_VALUE;
5412 }
5413
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005414 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005415 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5416 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005417 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005418 audioPortConfig->toAudioPortConfig(&newConfig, config);
5419 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005420 }
Eric Laurenta121f902014-06-03 13:32:54 -07005421 if (status != NO_ERROR) {
5422 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005423 }
Eric Laurente1715a42014-05-20 11:30:42 -07005424
5425 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005426}
5427
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005428void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5429{
Eric Laurentd60560a2015-04-10 11:31:20 -07005430 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005431 clearAudioPatches(uid);
5432 clearSessionRoutes(uid);
5433}
5434
Eric Laurent6a94d692014-05-20 11:18:06 -07005435void AudioPolicyManager::clearAudioPatches(uid_t uid)
5436{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005437 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005438 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005439 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005440 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005441 }
5442 }
5443}
5444
François Gaffiec005e562018-11-06 15:04:49 +01005445void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005446{
François Gaffiec005e562018-11-06 15:04:49 +01005447 // Take the first attributes following the product strategy as it is used to retrieve the routed
5448 // device. All attributes wihin a strategy follows the same "routing strategy"
5449 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5450 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005451 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005452 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005453 for (size_t j = 0; j < mOutputs.size(); j++) {
5454 if (mOutputs.keyAt(j) == ouptutToSkip) {
5455 continue;
5456 }
5457 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005458 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005459 continue;
5460 }
5461 // If the default device for this strategy is on another output mix,
5462 // invalidate all tracks in this strategy to force re connection.
5463 // Otherwise select new device on the output mix.
5464 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005465 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005466 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005467 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5468 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5469 // If the device is using preferred mixer attributes, the output need to reopen
5470 // with default configuration when the new selected devices are different from
5471 // current routing devices.
5472 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5473 continue;
5474 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305475 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005476 }
5477 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005478 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005479}
5480
5481void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5482{
5483 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005484 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005485 for (size_t i = 0; i < mOutputs.size(); i++) {
5486 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005487 for (const auto& client : outputDesc->getClientIterable()) {
5488 if (client->hasPreferredDevice() && client->uid() == uid) {
5489 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005490 auto clientStrategy = client->strategy();
5491 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5492 end(affectedStrategies)) {
5493 continue;
5494 }
5495 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005496 }
5497 }
5498 }
5499 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005500 for (const auto& strategy : affectedStrategies) {
5501 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005502 }
5503
5504 // remove input routes associated with this uid
5505 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005506 for (size_t i = 0; i < mInputs.size(); i++) {
5507 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005508 for (const auto& client : inputDesc->getClientIterable()) {
5509 if (client->hasPreferredDevice() && client->uid() == uid) {
5510 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5511 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005512 }
5513 }
5514 }
5515 // reroute inputs if necessary
5516 SortedVector<audio_io_handle_t> inputsToClose;
5517 for (size_t i = 0; i < mInputs.size(); i++) {
5518 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005519 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005520 inputsToClose.add(inputDesc->mIoHandle);
5521 }
5522 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005523 for (const auto& input : inputsToClose) {
5524 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005525 }
5526}
5527
Eric Laurentd60560a2015-04-10 11:31:20 -07005528void AudioPolicyManager::clearAudioSources(uid_t uid)
5529{
5530 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005531 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5532 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005533 stopAudioSource(mAudioSources.keyAt(i));
5534 }
5535 }
5536}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005537
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005538status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5539 audio_io_handle_t *ioHandle,
5540 audio_devices_t *device)
5541{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005542 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5543 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005544 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005545 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5546 if (deviceDesc == nullptr) {
5547 return INVALID_OPERATION;
5548 }
5549 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005550
François Gaffiedf372692015-03-19 10:43:27 +01005551 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005552}
5553
Eric Laurentd60560a2015-04-10 11:31:20 -07005554status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005555 const audio_attributes_t *attributes,
5556 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005557 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005558{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005559 ALOGV("%s", __FUNCTION__);
5560 *portId = AUDIO_PORT_HANDLE_NONE;
5561
5562 if (source == NULL || attributes == NULL || portId == NULL) {
5563 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5564 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005565 return BAD_VALUE;
5566 }
5567
Eric Laurentd60560a2015-04-10 11:31:20 -07005568 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5569 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005570 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5571 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005572 return INVALID_OPERATION;
5573 }
5574
François Gaffie11d30102018-11-02 16:09:09 +01005575 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005576 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005577 String8(source->ext.device.address),
5578 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005579 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005580 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005581 return BAD_VALUE;
5582 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005583
jiabin4ef93452019-09-10 14:29:54 -07005584 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005585
François Gaffieaaac0fd2018-11-22 17:56:39 +01005586 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005587 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005588 mEngine->getStreamTypeForAttributes(*attributes),
5589 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005590 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005591
5592 status_t status = connectAudioSource(sourceDesc);
5593 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005594 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005595 }
5596 return status;
5597}
5598
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005599status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005600{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005601 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005602
5603 // make sure we only have one patch per source.
5604 disconnectAudioSource(sourceDesc);
5605
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005606 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005607 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5608 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5609 sourceDesc->srcDevice()->type(),
5610 String8(sourceDesc->srcDevice()->address().c_str()),
5611 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005612 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005613 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005614 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005615 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005616 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5617 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5618 return INVALID_OPERATION;
5619 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005620 PatchBuilder patchBuilder;
5621 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5622 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005623
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005624 return connectAudioSourceToSink(
5625 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005626}
5627
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005628status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005629{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005630 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5631 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005632 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005633 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005634 return BAD_VALUE;
5635 }
5636 status_t status = disconnectAudioSource(sourceDesc);
5637
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005638 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005639 return status;
5640}
5641
Andy Hung2ddee192015-12-18 17:34:44 -08005642status_t AudioPolicyManager::setMasterMono(bool mono)
5643{
5644 if (mMasterMono == mono) {
5645 return NO_ERROR;
5646 }
5647 mMasterMono = mono;
5648 // if enabling mono we close all offloaded devices, which will invalidate the
5649 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5650 // for recreating the new AudioTrack as non-offloaded PCM.
5651 //
5652 // If disabling mono, we leave all tracks as is: we don't know which clients
5653 // and tracks are able to be recreated as offloaded. The next "song" should
5654 // play back offloaded.
5655 if (mMasterMono) {
5656 Vector<audio_io_handle_t> offloaded;
5657 for (size_t i = 0; i < mOutputs.size(); ++i) {
5658 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5659 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5660 offloaded.push(desc->mIoHandle);
5661 }
5662 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005663 for (const auto& handle : offloaded) {
5664 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005665 }
5666 }
5667 // update master mono for all remaining outputs
5668 for (size_t i = 0; i < mOutputs.size(); ++i) {
5669 updateMono(mOutputs.keyAt(i));
5670 }
5671 return NO_ERROR;
5672}
5673
5674status_t AudioPolicyManager::getMasterMono(bool *mono)
5675{
5676 *mono = mMasterMono;
5677 return NO_ERROR;
5678}
5679
Eric Laurentac9cef52017-06-09 15:46:26 -07005680float AudioPolicyManager::getStreamVolumeDB(
5681 audio_stream_type_t stream, int index, audio_devices_t device)
5682{
jiabin9a3361e2019-10-01 09:38:30 -07005683 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005684}
5685
jiabin81772902018-04-02 17:52:27 -07005686status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5687 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005688 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005689{
Kriti Dang6537def2021-03-02 13:46:59 +01005690 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5691 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005692 return BAD_VALUE;
5693 }
Kriti Dang6537def2021-03-02 13:46:59 +01005694 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5695 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005696
5697 size_t formatsWritten = 0;
5698 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005699
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005700 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005701 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5702 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005703 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005704 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005705 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005706 bool formatEnabled = true;
5707 switch (forceUse) {
5708 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005709 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005710 break;
5711 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5712 formatEnabled = false;
5713 break;
5714 default: // AUTO or ALWAYS => true
5715 break;
jiabin81772902018-04-02 17:52:27 -07005716 }
5717 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5718 }
jiabin81772902018-04-02 17:52:27 -07005719 }
5720 return NO_ERROR;
5721}
5722
Kriti Dang6537def2021-03-02 13:46:59 +01005723status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5724 audio_format_t *surroundFormats) {
5725 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5726 return BAD_VALUE;
5727 }
5728 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5729 __func__, *numSurroundFormats, surroundFormats);
5730
5731 size_t formatsWritten = 0;
5732 size_t formatsMax = *numSurroundFormats;
5733 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5734
5735 // Return formats from all device profiles that have already been resolved by
5736 // checkOutputsForDevice().
5737 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5738 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5739 audio_devices_t deviceType = device->type();
5740 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5741 // returns formats reported by HDMI devices.
5742 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5743 continue;
5744 }
5745 // Formats reported by sink devices
5746 std::unordered_set<audio_format_t> formatset;
5747 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5748 formatset.insert(it->second.begin(), it->second.end());
5749 }
5750
5751 // Formats hard-coded in the in policy configuration file (if any).
5752 FormatVector encodedFormats = device->encodedFormats();
5753 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5754 // Filter the formats which are supported by the vendor hardware.
5755 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005756 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005757 formats.insert(*it);
5758 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005759 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005760 if (pair.second.count(*it) != 0) {
5761 formats.insert(pair.first);
5762 break;
5763 }
5764 }
5765 }
5766 }
5767 }
5768 *numSurroundFormats = formats.size();
5769 for (const auto& format: formats) {
5770 if (formatsWritten < formatsMax) {
5771 surroundFormats[formatsWritten++] = format;
5772 }
5773 }
5774 return NO_ERROR;
5775}
5776
jiabin81772902018-04-02 17:52:27 -07005777status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5778{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005779 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005780 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5781 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005782 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005783 return BAD_VALUE;
5784 }
5785
Mikhail Naganov100f0122018-11-29 11:22:16 -08005786 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5787 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005788 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005789 return INVALID_OPERATION;
5790 }
5791
Mikhail Naganov100f0122018-11-29 11:22:16 -08005792 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005793 return NO_ERROR;
5794 }
5795
Mikhail Naganov100f0122018-11-29 11:22:16 -08005796 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005797 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005798 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005799 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005800 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005801 }
5802 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005803 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005804 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005805 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005806 }
5807 }
5808
5809 sp<SwAudioOutputDescriptor> outputDesc;
5810 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005811 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5812 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005813 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5814 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005815 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005816 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005817 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5818 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5819 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005820 name.c_str(),
5821 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005822 if (status != NO_ERROR) {
5823 continue;
5824 }
5825 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5826 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5827 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005828 name.c_str(),
5829 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005830 profileUpdated |= (status == NO_ERROR);
5831 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005832 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005833 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005834 AUDIO_DEVICE_IN_HDMI);
5835 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5836 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005837 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005838 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005839 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5840 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5841 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005842 name.c_str(),
5843 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005844 if (status != NO_ERROR) {
5845 continue;
5846 }
5847 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5848 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5849 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005850 name.c_str(),
5851 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005852 profileUpdated |= (status == NO_ERROR);
5853 }
5854
jiabin81772902018-04-02 17:52:27 -07005855 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005856 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005857 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005858 }
5859
5860 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5861}
5862
Eric Laurent5ada82e2019-08-29 17:53:54 -07005863void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005864{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005865 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005866 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005867 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005868 }
5869}
5870
jiabin6012f912018-11-02 17:06:30 -07005871bool AudioPolicyManager::isHapticPlaybackSupported()
5872{
5873 for (const auto& hwModule : mHwModules) {
5874 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5875 for (const auto &outProfile : outputProfiles) {
5876 struct audio_port audioPort;
5877 outProfile->toAudioPort(&audioPort);
5878 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5879 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5880 return true;
5881 }
5882 }
5883 }
5884 }
5885 return false;
5886}
5887
Carter Hsu325a8eb2022-01-19 19:56:51 +08005888bool AudioPolicyManager::isUltrasoundSupported()
5889{
5890 bool hasUltrasoundOutput = false;
5891 bool hasUltrasoundInput = false;
5892 for (const auto& hwModule : mHwModules) {
5893 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5894 if (!hasUltrasoundOutput) {
5895 for (const auto &outProfile : outputProfiles) {
5896 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5897 hasUltrasoundOutput = true;
5898 break;
5899 }
5900 }
5901 }
5902
5903 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5904 if (!hasUltrasoundInput) {
5905 for (const auto &inputProfile : inputProfiles) {
5906 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5907 hasUltrasoundInput = true;
5908 break;
5909 }
5910 }
5911 }
5912
5913 if (hasUltrasoundOutput && hasUltrasoundInput)
5914 return true;
5915 }
5916 return false;
5917}
5918
Atneya Nair698f5ef2022-12-15 16:15:09 -08005919bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5920{
5921 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5922 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5923 for (const auto& hwModule : mHwModules) {
5924 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5925 for (const auto &inputProfile : inputProfiles) {
5926 if ((inputProfile->getFlags() & mask) == mask) {
5927 return true;
5928 }
5929 }
5930 }
5931 return false;
5932}
5933
Eric Laurent8340e672019-11-06 11:01:08 -08005934bool AudioPolicyManager::isCallScreenModeSupported()
5935{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005936 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005937}
5938
5939
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005940status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005941{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005942 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005943 if (!sourceDesc->isConnected()) {
5944 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5945 return NO_ERROR;
5946 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005947 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5948 if (swOutput != 0) {
5949 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005950 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005951 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005952 }
jiabinbce0c1d2020-10-05 11:20:18 -07005953 if (releaseOutput(sourceDesc->portId())) {
5954 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5955 // no need to release audio patch here but just return NO_ERROR.
5956 return NO_ERROR;
5957 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005958 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005959 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005960 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005961 // close Hwoutput and remove from mHwOutputs
5962 } else {
5963 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5964 }
5965 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005966 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005967 sourceDesc->disconnect();
5968 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005969}
5970
François Gaffiec005e562018-11-06 15:04:49 +01005971sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5972 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005973{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005974 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005975 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005976 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005977 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005978 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5979 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005980 source = sourceDesc;
5981 break;
5982 }
5983 }
5984 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005985}
5986
Eric Laurentb4f42a92022-01-17 17:37:31 +01005987bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005988 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005989 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005990{
5991 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5992 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005993 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005994 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005995 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5996 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5997 return false;
5998 }
5999 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6000 return false;
6001 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006002 }
6003
Eric Laurentd332bc82023-08-04 11:45:23 +02006004 // The caller can have the audio config criteria ignored by either passing a null ptr or
6005 // the AUDIO_CONFIG_INITIALIZER value.
6006 // If an audio config is specified, current policy is to only allow spatialization for
Eric Laurentf9230d52024-01-26 18:49:09 +01006007 // some positional channel masks and PCM format and for stereo if low latency performance
6008 // mode is not requested.
Eric Laurentd332bc82023-08-04 11:45:23 +02006009
6010 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006011 const bool channel_mask_spatialized =
6012 com_android_media_audio_stereo_spatialization()
6013 ? audio_channel_mask_contains_stereo(config->channel_mask)
6014 : audio_is_channel_mask_spatialized(config->channel_mask);
6015 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006016 return false;
6017 }
6018 if (!audio_is_linear_pcm(config->format)) {
6019 return false;
6020 }
Eric Laurentf9230d52024-01-26 18:49:09 +01006021 if (config->channel_mask == AUDIO_CHANNEL_OUT_STEREO
6022 && ((attr->flags & AUDIO_FLAG_LOW_LATENCY) != 0)) {
6023 return false;
6024 }
Eric Laurentd332bc82023-08-04 11:45:23 +02006025 }
6026
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006027 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006028 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006029 if (profile == nullptr) {
6030 return false;
6031 }
6032
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006033 return true;
6034}
6035
6036void AudioPolicyManager::checkVirtualizerClientRoutes() {
6037 std::set<audio_stream_type_t> streamsToInvalidate;
6038 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006039 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6040 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006041 audio_attributes_t attr = client->attributes();
6042 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6043 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6044 audio_config_base_t clientConfig = client->config();
6045 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006046 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006047 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006048 streamsToInvalidate.insert(client->stream());
6049 }
6050 }
6051 }
6052
jiabinc44b3462022-12-08 12:52:31 -08006053 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006054}
6055
Eric Laurente191d1b2022-04-15 11:59:25 +02006056
6057bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6058 const sp<SwAudioOutputDescriptor>& outputDesc) {
6059 if (outputDesc->isDuplicated()) {
6060 return false;
6061 }
6062 DeviceVector devices = outputDesc->supportedDevices();
6063 for (size_t i = 0; i < mOutputs.size(); i++) {
6064 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6065 if (desc == outputDesc || desc->isDuplicated()) {
6066 continue;
6067 }
6068 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6069 if (!sharedDevices.isEmpty()
6070 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6071 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6072 return false;
6073 }
6074 }
6075 return true;
6076}
6077
6078
Eric Laurentfa0f6742021-08-17 18:39:44 +02006079status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006080 const audio_attributes_t *attr,
6081 audio_io_handle_t *output) {
6082 *output = AUDIO_IO_HANDLE_NONE;
6083
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006084 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6085 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6086 audio_config_t *configPtr = nullptr;
6087 audio_config_t config;
6088 if (mixerConfig != nullptr) {
6089 config = audio_config_initializer(mixerConfig);
6090 configPtr = &config;
6091 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006092 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006093 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006094 return BAD_VALUE;
6095 }
6096
6097 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006098 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006099 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006100 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006101 return BAD_VALUE;
6102 }
6103
Eric Laurente191d1b2022-04-15 11:59:25 +02006104 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006105 for (size_t i = 0; i < mOutputs.size(); i++) {
6106 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006107 if (!desc->isDuplicated()
6108 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6109 spatializerOutputs.push_back(desc);
6110 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006111 }
6112 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006113 mSpatializerOutput.clear();
6114 bool outputsChanged = false;
6115 for (const auto& desc : spatializerOutputs) {
6116 if (desc->mProfile == profile
6117 && (configPtr == nullptr
6118 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6119 mSpatializerOutput = desc;
6120 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6121 } else {
6122 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6123 " and devices %s", __func__, desc->mIoHandle,
6124 configPtr != nullptr ? configPtr->channel_mask : 0,
6125 devices.toString().c_str());
6126 closeOutput(desc->mIoHandle);
6127 outputsChanged = true;
6128 }
Eric Laurent39095982021-08-24 18:29:27 +02006129 }
6130
Eric Laurente191d1b2022-04-15 11:59:25 +02006131 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006132 sp<SwAudioOutputDescriptor> desc =
6133 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006134 if (desc != nullptr) {
6135 mSpatializerOutput = desc;
6136 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006137 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006138 }
6139
6140 checkVirtualizerClientRoutes();
6141
Eric Laurente191d1b2022-04-15 11:59:25 +02006142 if (outputsChanged) {
6143 mPreviousOutputs = mOutputs;
6144 mpClientInterface->onAudioPortListUpdate();
6145 }
6146
6147 if (mSpatializerOutput == nullptr) {
6148 ALOGV("%s could not open spatializer output with requested config", __func__);
6149 return BAD_VALUE;
6150 }
Eric Laurent39095982021-08-24 18:29:27 +02006151 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006152 ALOGV("%s returning new spatializer output %d", __func__, *output);
6153 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006154}
6155
Eric Laurentfa0f6742021-08-17 18:39:44 +02006156status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6157 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006158 return INVALID_OPERATION;
6159 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006160 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006161 return BAD_VALUE;
6162 }
Eric Laurent39095982021-08-24 18:29:27 +02006163
Eric Laurente191d1b2022-04-15 11:59:25 +02006164 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6165 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6166 closeOutput(mSpatializerOutput->mIoHandle);
6167 //from now on mSpatializerOutput is null
6168 checkVirtualizerClientRoutes();
6169 }
Eric Laurent39095982021-08-24 18:29:27 +02006170
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006171 return NO_ERROR;
6172}
6173
Eric Laurente552edb2014-03-10 17:42:56 -07006174// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006175// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006176// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006177uint32_t AudioPolicyManager::nextAudioPortGeneration()
6178{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006179 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006180}
6181
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006182AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006183 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006184 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006185 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006186 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006187 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006188 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006189 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006190 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006191 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006192 mAudioPortGeneration(1),
6193 mBeaconMuteRefCount(0),
6194 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006195 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006196 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006197 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006198 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006199{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006200}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006201
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006202status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006203 if (mEngine == nullptr) {
6204 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006205 }
6206 mEngine->setObserver(this);
6207 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006208 if (status != NO_ERROR) {
6209 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6210 return status;
6211 }
François Gaffie2110e042015-03-24 08:41:51 +01006212
jiabin29230182023-04-04 21:02:36 +00006213 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6214 // at the end of this function.
6215 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006216 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6217 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6218
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006219 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006220 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006221 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006222
Eric Laurent3a4311c2014-03-17 12:00:47 -07006223 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006224 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6225 defaultOutputDevice == nullptr ||
6226 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6227 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6228 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006229 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006230 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006231 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006232
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006233 // Silence ALOGV statements
6234 property_set("log.tag." LOG_TAG, "D");
6235
Eric Laurente552edb2014-03-10 17:42:56 -07006236 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006237 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006238}
6239
Eric Laurente0720872014-03-11 09:30:41 -07006240AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006241{
Eric Laurente552edb2014-03-10 17:42:56 -07006242 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006243 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006244 }
6245 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006246 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006247 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006248 mAvailableOutputDevices.clear();
6249 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006250 mOutputs.clear();
6251 mInputs.clear();
6252 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006253 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006254 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006255}
6256
Eric Laurente0720872014-03-11 09:30:41 -07006257status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006258{
Eric Laurent87ffa392015-05-22 10:32:38 -07006259 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006260}
6261
Eric Laurente552edb2014-03-10 17:42:56 -07006262// ---
6263
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006264void AudioPolicyManager::onNewAudioModulesAvailable()
6265{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006266 DeviceVector newDevices;
6267 onNewAudioModulesAvailableInt(&newDevices);
6268 if (!newDevices.empty()) {
6269 nextAudioPortGeneration();
6270 mpClientInterface->onAudioPortListUpdate();
6271 }
6272}
6273
6274void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6275{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006276 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006277 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6278 continue;
6279 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006280 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006281 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6282 handle != AUDIO_MODULE_HANDLE_NONE) {
6283 hwModule->setHandle(handle);
6284 } else {
6285 ALOGW("could not load HW module %s", hwModule->getName());
6286 continue;
6287 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006288 }
6289 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006290 // open all output streams needed to access attached devices.
6291 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006292 // This also validates mAvailableOutputDevices list
6293 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6294 if (!outProfile->canOpenNewIo()) {
6295 ALOGE("Invalid Output profile max open count %u for profile %s",
6296 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6297 continue;
6298 }
6299 if (!outProfile->hasSupportedDevices()) {
6300 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6301 continue;
6302 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006303 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6304 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006305 mTtsOutputAvailable = true;
6306 }
6307
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006308 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006309 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006310 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006311 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6312 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006313 } else {
6314 // choose first device present in profile's SupportedDevices also part of
6315 // mAvailableOutputDevices.
6316 if (availProfileDevices.isEmpty()) {
6317 continue;
6318 }
6319 supportedDevice = availProfileDevices.itemAt(0);
6320 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006321 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006322 continue;
6323 }
6324 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6325 mpClientInterface);
6326 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006327 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6328 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006329 AUDIO_STREAM_DEFAULT,
6330 AUDIO_OUTPUT_FLAG_NONE, &output);
6331 if (status != NO_ERROR) {
6332 ALOGW("Cannot open output stream for devices %s on hw module %s",
6333 supportedDevice->toString().c_str(), hwModule->getName());
6334 continue;
6335 }
6336 for (const auto &device : availProfileDevices) {
6337 // give a valid ID to an attached device once confirmed it is reachable
6338 if (!device->isAttached()) {
6339 device->attach(hwModule);
6340 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006341 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006342 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006343 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6344 }
6345 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006346 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006347 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6348 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006349 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006350 }
Eric Laurent39095982021-08-24 18:29:27 +02006351 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006352 outputDesc->close();
6353 } else {
6354 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306355 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006356 DeviceVector(supportedDevice),
6357 true,
6358 0,
6359 NULL);
6360 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006361 }
6362 // open input streams needed to access attached devices to validate
6363 // mAvailableInputDevices list
6364 for (const auto& inProfile : hwModule->getInputProfiles()) {
6365 if (!inProfile->canOpenNewIo()) {
6366 ALOGE("Invalid Input profile max open count %u for profile %s",
6367 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6368 continue;
6369 }
6370 if (!inProfile->hasSupportedDevices()) {
6371 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6372 continue;
6373 }
6374 // chose first device present in profile's SupportedDevices also part of
6375 // available input devices
6376 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006377 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006378 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006379 ALOGV("%s: Input device list is empty! for profile %s",
6380 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006381 continue;
6382 }
6383 sp<AudioInputDescriptor> inputDesc =
6384 new AudioInputDescriptor(inProfile, mpClientInterface);
6385
6386 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6387 status_t status = inputDesc->open(nullptr,
6388 availProfileDevices.itemAt(0),
6389 AUDIO_SOURCE_MIC,
6390 AUDIO_INPUT_FLAG_NONE,
6391 &input);
6392 if (status != NO_ERROR) {
6393 ALOGW("Cannot open input stream for device %s on hw module %s",
6394 availProfileDevices.toString().c_str(),
6395 hwModule->getName());
6396 continue;
6397 }
6398 for (const auto &device : availProfileDevices) {
6399 // give a valid ID to an attached device once confirmed it is reachable
6400 if (!device->isAttached()) {
6401 device->attach(hwModule);
6402 device->importAudioPortAndPickAudioProfile(inProfile, true);
6403 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006404 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006405 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6406 }
6407 }
6408 inputDesc->close();
6409 }
6410 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006411
6412 // Check if spatializer outputs can be closed until used.
6413 // mOutputs vector never contains duplicated outputs at this point.
6414 std::vector<audio_io_handle_t> outputsClosed;
6415 for (size_t i = 0; i < mOutputs.size(); i++) {
6416 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6417 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6418 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6419 outputsClosed.push_back(desc->mIoHandle);
6420 desc->close();
6421 }
6422 }
6423 for (auto output : outputsClosed) {
6424 removeOutput(output);
6425 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006426}
6427
Eric Laurent98e38192018-02-15 18:31:53 -08006428void AudioPolicyManager::addOutput(audio_io_handle_t output,
6429 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006430{
Eric Laurent1c333e22014-05-20 10:48:17 -07006431 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006432 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006433 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006434 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006435 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006436}
6437
François Gaffie53615e22015-03-19 09:24:12 +01006438void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6439{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006440 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6441 ALOGV("%s: removing primary output", __func__);
6442 mPrimaryOutput = nullptr;
6443 }
François Gaffie53615e22015-03-19 09:24:12 +01006444 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006445 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006446}
6447
Eric Laurent98e38192018-02-15 18:31:53 -08006448void AudioPolicyManager::addInput(audio_io_handle_t input,
6449 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006450{
Eric Laurent1c333e22014-05-20 10:48:17 -07006451 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006452 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006453}
Eric Laurente552edb2014-03-10 17:42:56 -07006454
François Gaffie11d30102018-11-02 16:09:09 +01006455status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006456 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006457 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006458{
François Gaffie11d30102018-11-02 16:09:09 +01006459 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006460 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006461 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006462
François Gaffie11d30102018-11-02 16:09:09 +01006463 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006464 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006465 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006466 }
Eric Laurente552edb2014-03-10 17:42:56 -07006467
Eric Laurent3b73df72014-03-11 09:06:29 -07006468 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006469 // first call getAudioPort to get the supported attributes from the HAL
6470 struct audio_port_v7 port = {};
6471 device->toAudioPort(&port);
6472 status_t status = mpClientInterface->getAudioPort(&port);
6473 if (status == NO_ERROR) {
6474 device->importAudioPort(port);
6475 }
6476
6477 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006478 for (size_t i = 0; i < mOutputs.size(); i++) {
6479 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006480 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006481 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006482 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6483 mOutputs.keyAt(i), device->toString().c_str());
6484 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006485 }
6486 }
6487 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006488 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006489 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006490 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6491 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006492 if (profile->supportsDevice(device)) {
6493 profiles.add(profile);
6494 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6495 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006496 }
6497 }
6498 }
6499
Eric Laurent7b279bb2015-12-14 10:18:23 -08006500 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006501
Eric Laurente552edb2014-03-10 17:42:56 -07006502 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006503 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006504 return BAD_VALUE;
6505 }
6506
6507 // open outputs for matching profiles if needed. Direct outputs are also opened to
6508 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6509 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006510 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006511
6512 // nothing to do if one output is already opened for this profile
6513 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006514 for (j = 0; j < outputs.size(); j++) {
6515 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006516 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006517 // matching profile: save the sample rates, format and channel masks supported
6518 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006519 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006520 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006521 }
Eric Laurente552edb2014-03-10 17:42:56 -07006522 break;
6523 }
6524 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006525 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006526 continue;
6527 }
6528
Eric Laurent3974e3b2017-12-07 17:58:43 -08006529 if (!profile->canOpenNewIo()) {
6530 ALOGW("Max Output number %u already opened for this profile %s",
6531 profile->maxOpenCount, profile->getTagName().c_str());
6532 continue;
6533 }
6534
Eric Laurent83efe1c2017-07-09 16:51:08 -07006535 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006536 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006537 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6538 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006539 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006540 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006541 profiles.removeAt(profile_index);
6542 profile_index--;
6543 } else {
6544 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006545 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006546 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006547 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6548 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006549 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006550 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006551
François Gaffie11d30102018-11-02 16:09:09 +01006552 if (device_distinguishes_on_address(deviceType)) {
6553 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6554 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306555 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6556 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006557 }
Eric Laurente552edb2014-03-10 17:42:56 -07006558 ALOGV("checkOutputsForDevice(): adding output %d", output);
6559 }
6560 }
6561
6562 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006563 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006564 return BAD_VALUE;
6565 }
Eric Laurentd4692962014-05-05 18:13:44 -07006566 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006567 // check if one opened output is not needed any more after disconnecting one device
6568 for (size_t i = 0; i < mOutputs.size(); i++) {
6569 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006570 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006571 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006572 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006573 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006574 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006575 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006576 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6577 mOutputs.keyAt(i));
6578 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006579 }
Eric Laurente552edb2014-03-10 17:42:56 -07006580 }
6581 }
Eric Laurentd4692962014-05-05 18:13:44 -07006582 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006583 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006584 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6585 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006586 if (!profile->supportsDevice(device)) {
6587 continue;
6588 }
6589 ALOGV("checkOutputsForDevice(): "
6590 "clearing direct output profile %zu on module %s",
6591 j, hwModule->getName());
6592 profile->clearAudioProfiles();
6593 if (!profile->hasDynamicAudioProfile()) {
6594 continue;
6595 }
6596 // When a device is disconnected, if there is an IOProfile that contains dynamic
6597 // profiles and supports the disconnected device, call getAudioPort to repopulate
6598 // the capabilities of the devices that is supported by the IOProfile.
6599 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6600 if (supportedDevice == device ||
6601 !mAvailableOutputDevices.contains(supportedDevice)) {
6602 continue;
6603 }
6604 struct audio_port_v7 port;
6605 supportedDevice->toAudioPort(&port);
6606 status_t status = mpClientInterface->getAudioPort(&port);
6607 if (status == NO_ERROR) {
6608 supportedDevice->importAudioPort(port);
6609 }
Eric Laurente552edb2014-03-10 17:42:56 -07006610 }
6611 }
6612 }
6613 }
6614 return NO_ERROR;
6615}
6616
François Gaffie11d30102018-11-02 16:09:09 +01006617status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006618 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006619{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006620 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006621
François Gaffie11d30102018-11-02 16:09:09 +01006622 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006623 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006624 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006625 }
6626
Eric Laurentd4692962014-05-05 18:13:44 -07006627 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006628 // first call getAudioPort to get the supported attributes from the HAL
6629 struct audio_port_v7 port = {};
6630 device->toAudioPort(&port);
6631 status_t status = mpClientInterface->getAudioPort(&port);
6632 if (status == NO_ERROR) {
6633 device->importAudioPort(port);
6634 }
6635
Eric Laurent0dd51852019-04-19 18:18:58 -07006636 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006637 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006638 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006639 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006640 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006641 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006642 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006643
François Gaffie11d30102018-11-02 16:09:09 +01006644 if (profile->supportsDevice(device)) {
6645 profiles.add(profile);
6646 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6647 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006648 }
6649 }
6650 }
6651
Eric Laurent0dd51852019-04-19 18:18:58 -07006652 if (profiles.isEmpty()) {
6653 ALOGW("%s: No input profile available for device %s",
6654 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006655 return BAD_VALUE;
6656 }
6657
6658 // open inputs for matching profiles if needed. Direct inputs are also opened to
6659 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6660 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6661
Eric Laurent1c333e22014-05-20 10:48:17 -07006662 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006663
Eric Laurentd4692962014-05-05 18:13:44 -07006664 // nothing to do if one input is already opened for this profile
6665 size_t input_index;
6666 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6667 desc = mInputs.valueAt(input_index);
6668 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006669 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006670 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006671 }
Eric Laurentd4692962014-05-05 18:13:44 -07006672 break;
6673 }
6674 }
6675 if (input_index != mInputs.size()) {
6676 continue;
6677 }
6678
Eric Laurent3974e3b2017-12-07 17:58:43 -08006679 if (!profile->canOpenNewIo()) {
6680 ALOGW("Max Input number %u already opened for this profile %s",
6681 profile->maxOpenCount, profile->getTagName().c_str());
6682 continue;
6683 }
6684
Eric Laurentfe231122017-11-17 17:48:06 -08006685 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006686 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006687 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006688
Eric Laurentcf2c0212014-07-25 16:20:43 -07006689 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006690 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006691 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006692 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006693 mpClientInterface->setParameters(input, String8(param));
6694 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006695 }
jiabin12537fc2023-10-12 17:56:08 +00006696 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006697 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006698 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006699 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006700 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006701 }
6702
Eric Laurent0dd51852019-04-19 18:18:58 -07006703 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006704 addInput(input, desc);
6705 }
6706 } // endif input != 0
6707
Eric Laurentcf2c0212014-07-25 16:20:43 -07006708 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006709 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006710 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006711 profiles.removeAt(profile_index);
6712 profile_index--;
6713 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006714 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006715 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006716 }
Eric Laurentd4692962014-05-05 18:13:44 -07006717 ALOGV("checkInputsForDevice(): adding input %d", input);
6718 }
6719 } // end scan profiles
6720
6721 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006722 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006723 return BAD_VALUE;
6724 }
6725 } else {
6726 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006727 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006728 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006729 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006730 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006731 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006732 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006733 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006734 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6735 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006736 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006737 }
6738 }
6739 }
6740 } // end disconnect
6741
6742 return NO_ERROR;
6743}
6744
6745
Eric Laurente0720872014-03-11 09:30:41 -07006746void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006747{
6748 ALOGV("closeOutput(%d)", output);
6749
François Gaffie1c878552018-11-22 16:53:21 +01006750 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6751 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006752 ALOGW("closeOutput() unknown output %d", output);
6753 return;
6754 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006755 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006756 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006757
Eric Laurente552edb2014-03-10 17:42:56 -07006758 // look for duplicated outputs connected to the output being removed.
6759 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006760 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6761 if (dupOutput->isDuplicated() &&
6762 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6763 sp<SwAudioOutputDescriptor> remainingOutput =
6764 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006765 // As all active tracks on duplicated output will be deleted,
6766 // and as they were also referenced on the other output, the reference
6767 // count for their stream type must be adjusted accordingly on
6768 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006769 const bool wasActive = remainingOutput->isActive();
6770 // Note: no-op on the closing output where all clients has already been set inactive
6771 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006772 // stop() will be a no op if the output is still active but is needed in case all
6773 // active streams refcounts where cleared above
6774 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006775 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006776 }
Eric Laurente552edb2014-03-10 17:42:56 -07006777 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6778 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6779
6780 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006781 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006782 }
6783 }
6784
Eric Laurent05b90f82014-08-27 15:32:29 -07006785 nextAudioPortGeneration();
6786
François Gaffie1c878552018-11-22 16:53:21 +01006787 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006788 if (index >= 0) {
6789 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006790 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6791 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006792 mAudioPatches.removeItemsAt(index);
6793 mpClientInterface->onAudioPatchListUpdate();
6794 }
6795
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006796 if (closingOutputWasActive) {
6797 closingOutput->stop();
6798 }
François Gaffie1c878552018-11-22 16:53:21 +01006799 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006800 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6801 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6802 for (const auto device : closingOutput->devices()) {
6803 device->setPreferredConfig(nullptr);
6804 }
6805 }
Eric Laurente552edb2014-03-10 17:42:56 -07006806
François Gaffie53615e22015-03-19 09:24:12 +01006807 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006808 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006809 if (closingOutput == mSpatializerOutput) {
6810 mSpatializerOutput.clear();
6811 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006812
6813 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6814 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006815 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006816 bool directOutputOpen = false;
6817 for (size_t i = 0; i < mOutputs.size(); i++) {
6818 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6819 directOutputOpen = true;
6820 break;
6821 }
6822 }
6823 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006824 ALOGV("no direct outputs open, reset MSD patches");
6825 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6826 // how output devices for patching are resolved. Avoid by caching and reusing the
6827 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6828 // devices to patch to. This may be complicated by the fact that devices may become
6829 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006830 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006831 }
6832 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006833}
6834
6835void AudioPolicyManager::closeInput(audio_io_handle_t input)
6836{
6837 ALOGV("closeInput(%d)", input);
6838
6839 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6840 if (inputDesc == NULL) {
6841 ALOGW("closeInput() unknown input %d", input);
6842 return;
6843 }
6844
Eric Laurent6a94d692014-05-20 11:18:06 -07006845 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006846
François Gaffie11d30102018-11-02 16:09:09 +01006847 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006848 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006849 if (index >= 0) {
6850 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006851 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6852 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006853 mAudioPatches.removeItemsAt(index);
6854 mpClientInterface->onAudioPatchListUpdate();
6855 }
6856
François Gaffie6ebbce02023-07-19 13:27:53 +02006857 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006858 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006859 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006860
François Gaffie11d30102018-11-02 16:09:09 +01006861 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6862 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006863 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006864 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006865 }
Eric Laurente552edb2014-03-10 17:42:56 -07006866}
6867
François Gaffie11d30102018-11-02 16:09:09 +01006868SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6869 const DeviceVector &devices,
6870 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006871{
6872 SortedVector<audio_io_handle_t> outputs;
6873
François Gaffie11d30102018-11-02 16:09:09 +01006874 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006875 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006876 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006877 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006878 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006879 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006880 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006881 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006882 outputs.add(openOutputs.keyAt(i));
6883 }
6884 }
6885 return outputs;
6886}
6887
Mikhail Naganov37977152018-07-11 15:54:44 -07006888void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6889{
6890 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6891 // output is suspended before any tracks are moved to it
6892 checkA2dpSuspend();
6893 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006894 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006895 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006896 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006897 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006898 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6899 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6900 // configuration changes will ultimately be rerouted correctly. We can still avoid
6901 // unnecessary rerouting by caching and reusing the arguments to
6902 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6903 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006904 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006905 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006906 // an event that changed routing likely occurred, inform upper layers
6907 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006908}
6909
François Gaffiec005e562018-11-06 15:04:49 +01006910bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6911 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006912{
François Gaffiec005e562018-11-06 15:04:49 +01006913 return mEngine->getProductStrategyForAttributes(lAttr) ==
6914 mEngine->getProductStrategyForAttributes(rAttr);
6915}
6916
Francois Gaffieff1eb522020-05-06 18:37:04 +02006917void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6918{
6919 for (size_t i = 0; i < mAudioSources.size(); i++) {
6920 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6921 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006922 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006923 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006924 connectAudioSource(sourceDesc);
6925 }
6926 }
6927}
6928
6929void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6930{
6931 for (size_t i = 0; i < mAudioSources.size(); i++) {
6932 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6933 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6934 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6935 disconnectAudioSource(sourceDesc);
6936 }
6937 }
6938}
6939
François Gaffiec005e562018-11-06 15:04:49 +01006940void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6941{
6942 auto psId = mEngine->getProductStrategyForAttributes(attr);
6943
6944 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6945 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006946
François Gaffie11d30102018-11-02 16:09:09 +01006947 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6948 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006949
Eric Laurentc209fe42020-06-05 18:11:23 -07006950 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006951 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006952 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006953 // take into account dynamic audio policies related changes: if a client is now associated
6954 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006955 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006956 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6957 if (desc->isDuplicated()) {
6958 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006959 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006960 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6961 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6962 continue;
6963 }
6964 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006965 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006966 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6967 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6968 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006969 if (status != OK) {
6970 continue;
6971 }
yucliuf4de36d2020-09-14 14:57:56 -07006972 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006973 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006974 maxLatency = desc->latency();
6975 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006976 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006977 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006978 }
6979 }
6980
Eric Laurent56ed8842022-11-15 16:04:41 +01006981 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006982 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6983 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006984 for (audio_io_handle_t srcOut : srcOutputs) {
6985 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006986 if (desc == nullptr) continue;
6987
6988 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006989 maxLatency = desc->latency();
6990 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006991
Eric Laurent56ed8842022-11-15 16:04:41 +01006992 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006993 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006994 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006995 // a client on a non direct outputs has necessarily a linear PCM format
6996 // so we can call selectOutput() safely
6997 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6998 client->flags(),
6999 client->config().format,
7000 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07007001 client->config().sample_rate,
7002 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07007003 if (newOutput != srcOut) {
7004 invalidate = true;
7005 break;
7006 }
7007 } else {
7008 sp<IOProfile> profile = getProfileForOutput(newDevices,
7009 client->config().sample_rate,
7010 client->config().format,
7011 client->config().channel_mask,
7012 client->flags(),
7013 true /* directOnly */);
7014 if (profile != desc->mProfile) {
7015 invalidate = true;
7016 break;
7017 }
7018 }
7019 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007020 // mute strategy while moving tracks from one output to another
7021 if (invalidate) {
7022 invalidatedOutputs.push_back(desc);
7023 if (desc->isStrategyActive(psId)) {
7024 setStrategyMute(psId, true, desc);
7025 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7026 newDevices.types());
7027 }
Eric Laurente552edb2014-03-10 17:42:56 -07007028 }
François Gaffiec005e562018-11-06 15:04:49 +01007029 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007030 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007031 connectAudioSource(source);
7032 }
Eric Laurente552edb2014-03-10 17:42:56 -07007033 }
7034
Eric Laurent56ed8842022-11-15 16:04:41 +01007035 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7036 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7037 std::to_string(srcOutputs[0]).c_str(),
7038 std::to_string(dstOutputs[0]).c_str());
7039
François Gaffiec005e562018-11-06 15:04:49 +01007040 // Move effects associated to this stream from previous output to new output
7041 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007042 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007043 }
François Gaffiec005e562018-11-06 15:04:49 +01007044 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007045 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007046 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007047 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007048 desc->setTracksInvalidatedStatusByStrategy(psId);
7049 }
Eric Laurente552edb2014-03-10 17:42:56 -07007050 }
7051 }
7052}
7053
Eric Laurente0720872014-03-11 09:30:41 -07007054void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007055{
François Gaffiec005e562018-11-06 15:04:49 +01007056 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7057 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7058 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007059 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007060 }
Eric Laurente552edb2014-03-10 17:42:56 -07007061}
7062
Kevin Rocard153f92d2018-12-18 18:33:28 -08007063void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007064 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007065 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007066 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007067 for (size_t i = 0; i < mOutputs.size(); i++) {
7068 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7069 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007070 sp<AudioPolicyMix> primaryMix;
7071 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007072 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007073 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7074 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7075 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007076 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7077 for (auto &secondaryMix : secondaryMixes) {
7078 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7079 if (outputDesc != nullptr &&
7080 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7081 secondaryDescs.push_back(outputDesc);
7082 }
7083 }
7084
jiabinc44b3462022-12-08 12:52:31 -08007085 if (status != OK &&
7086 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7087 // When it failed to query secondary output, only invalidate the client that is not
7088 // MMAP. The reason is that MMAP stream will not support secondary output.
7089 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007090 } else if (!std::equal(
7091 client->getSecondaryOutputs().begin(),
7092 client->getSecondaryOutputs().end(),
7093 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007094 if (!audio_is_linear_pcm(client->config().format)) {
7095 // If the format is not PCM, the tracks should be invalidated to get correct
7096 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007097 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007098 } else {
7099 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7100 std::vector<audio_io_handle_t> secondaryOutputIds;
7101 for (const auto &secondaryDesc: secondaryDescs) {
7102 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7103 weakSecondaryDescs.push_back(secondaryDesc);
7104 }
7105 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7106 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007107 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007108 }
7109 }
7110 }
jiabin10a03f12021-05-07 23:46:28 +00007111 if (!trackSecondaryOutputs.empty()) {
7112 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7113 }
jiabinc44b3462022-12-08 12:52:31 -08007114 if (!clientsToInvalidate.empty()) {
7115 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7116 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007117 }
7118}
7119
Eric Laurent2517af32020-11-25 15:31:27 +01007120bool AudioPolicyManager::isScoRequestedForComm() const {
7121 AudioDeviceTypeAddrVector devices;
7122 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7123 for (const auto &device : devices) {
7124 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7125 return true;
7126 }
7127 }
7128 return false;
7129}
7130
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007131bool AudioPolicyManager::isHearingAidUsedForComm() const {
7132 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7133 true /*fromCache*/);
7134 for (const auto &device : devices) {
7135 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7136 return true;
7137 }
7138 }
7139 return false;
7140}
7141
7142
Eric Laurente0720872014-03-11 09:30:41 -07007143void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007144{
François Gaffie53615e22015-03-19 09:24:12 +01007145 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007146 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007147 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007148 return;
7149 }
7150
Eric Laurent3a4311c2014-03-17 12:00:47 -07007151 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007152 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7153 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007154 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007155
7156 // if suspended, restore A2DP output if:
7157 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007158 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007159 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007160 //
Eric Laurentf732e072016-08-03 19:30:28 -07007161 // if not suspended, suspend A2DP output if:
7162 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007163 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007164 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007165 //
7166 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007167 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007168 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007169 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007170 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007171
7172 mpClientInterface->restoreOutput(a2dpOutput);
7173 mA2dpSuspended = false;
7174 }
7175 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007176 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007177 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007178 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007179 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007180
7181 mpClientInterface->suspendOutput(a2dpOutput);
7182 mA2dpSuspended = true;
7183 }
7184 }
7185}
7186
François Gaffie11d30102018-11-02 16:09:09 +01007187DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7188 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007189{
François Gaffiedb1755b2023-09-01 11:50:35 +02007190 if (outputDesc == nullptr) {
7191 return DeviceVector{};
7192 }
François Gaffie11d30102018-11-02 16:09:09 +01007193
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007194 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007195 if (index >= 0) {
7196 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007197 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007198 ALOGV("%s device %s forced by patch %d", __func__,
7199 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7200 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007201 }
7202 }
7203
Dean Wheatley514b4312020-06-17 21:45:00 +10007204 // Do not retrieve engine device for outputs through MSD
7205 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7206 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7207 return outputDesc->devices();
7208 }
7209
Eric Laurent97ac8712018-07-27 18:59:02 -07007210 // Honor explicit routing requests only if no client using default routing is active on this
7211 // input: a specific app can not force routing for other apps by setting a preferred device.
7212 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007213 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007214 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007215 if (device != nullptr) {
7216 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007217 }
7218
François Gaffiea807ef92018-11-05 10:44:33 +01007219 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7220 // of setForceUse / Default Bus device here
7221 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7222 if (device != nullptr) {
7223 return DeviceVector(device);
7224 }
7225
François Gaffiedb1755b2023-09-01 11:50:35 +02007226 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007227 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7228 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7229 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307230 auto hasStreamActive = [&](auto stream) {
7231 return hasStream(streams, stream) && isStreamActive(stream, 0);
7232 };
Eric Laurent484e9272018-06-07 17:29:23 -07007233
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307234 auto doGetOutputDevicesForVoice = [&]() {
7235 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007236 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307237 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007238 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7239 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307240 };
7241
7242 // With low-latency playing on speaker, music on WFD, when the first low-latency
7243 // output is stopped, getNewOutputDevices checks for a product strategy
7244 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007245 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307246 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7247 // stream is associated to the output descriptor.
7248 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7249 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7250 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7251 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007252 // Retrieval of devices for voice DL is done on primary output profile, cannot
7253 // check the route (would force modifying configuration file for this profile)
7254 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7255 break;
7256 }
Eric Laurente552edb2014-03-10 17:42:56 -07007257 }
François Gaffiec005e562018-11-06 15:04:49 +01007258 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007259 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007260}
7261
François Gaffie11d30102018-11-02 16:09:09 +01007262sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7263 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007264{
François Gaffie11d30102018-11-02 16:09:09 +01007265 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007266
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007267 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007268 if (index >= 0) {
7269 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007270 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007271 ALOGV("getNewInputDevice() device %s forced by patch %d",
7272 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7273 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007274 }
7275 }
7276
Eric Laurent97ac8712018-07-27 18:59:02 -07007277 // Honor explicit routing requests only if no client using default routing is active on this
7278 // input: a specific app can not force routing for other apps by setting a preferred device.
7279 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007280 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7281 if (device != nullptr) {
7282 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007283 }
7284
Eric Laurentdc95a252018-04-12 12:46:56 -07007285 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007286 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007287 audio_attributes_t attributes;
7288 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007289 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007290 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7291 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007292 attributes = topClient->attributes();
7293 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007294 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007295 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007296 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7297 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007298 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007299 }
7300
Francois Gaffie716e1432019-01-14 16:58:59 +01007301 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7302 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007303 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007304 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007305 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007306 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007307
Eric Laurente552edb2014-03-10 17:42:56 -07007308 return device;
7309}
7310
Eric Laurent794fde22016-03-11 09:50:45 -08007311bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7312 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007313 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007314}
7315
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007316status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007317 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007318 if (devices == nullptr) {
7319 return BAD_VALUE;
7320 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007321
Andy Hung6d23c0f2022-02-16 09:37:15 -08007322 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007323 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7324 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007325 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007326 for (const auto& device : curDevices) {
7327 devices->push_back(device->getDeviceTypeAddr());
7328 }
7329 return NO_ERROR;
7330}
7331
Eric Laurente0720872014-03-11 09:30:41 -07007332void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007333 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007334 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007335 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007336 updateDevicesAndOutputs();
7337 break;
7338 default:
7339 break;
7340 }
7341}
7342
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007343uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007344
7345 // skip beacon mute management if a dedicated TTS output is available
7346 if (mTtsOutputAvailable) {
7347 return 0;
7348 }
7349
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007350 switch(event) {
7351 case STARTING_OUTPUT:
7352 mBeaconMuteRefCount++;
7353 break;
7354 case STOPPING_OUTPUT:
7355 if (mBeaconMuteRefCount > 0) {
7356 mBeaconMuteRefCount--;
7357 }
7358 break;
7359 case STARTING_BEACON:
7360 mBeaconPlayingRefCount++;
7361 break;
7362 case STOPPING_BEACON:
7363 if (mBeaconPlayingRefCount > 0) {
7364 mBeaconPlayingRefCount--;
7365 }
7366 break;
7367 }
7368
7369 if (mBeaconMuteRefCount > 0) {
7370 // any playback causes beacon to be muted
7371 return setBeaconMute(true);
7372 } else {
7373 // no other playback: unmute when beacon starts playing, mute when it stops
7374 return setBeaconMute(mBeaconPlayingRefCount == 0);
7375 }
7376}
7377
7378uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7379 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7380 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7381 // keep track of muted state to avoid repeating mute/unmute operations
7382 if (mBeaconMuted != mute) {
7383 // mute/unmute AUDIO_STREAM_TTS on all outputs
7384 ALOGV("\t muting %d", mute);
7385 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007386 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7387 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7388 ALOGV("\t no tts volume source available");
7389 return 0;
7390 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007391 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007392 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007393 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007394 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007395 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007396 maxLatency = latency;
7397 }
7398 }
7399 mBeaconMuted = mute;
7400 return maxLatency;
7401 }
7402 return 0;
7403}
7404
Eric Laurente0720872014-03-11 09:30:41 -07007405void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007406{
François Gaffiec005e562018-11-06 15:04:49 +01007407 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007408 mPreviousOutputs = mOutputs;
7409}
7410
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007411uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007412 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007413 uint32_t delayMs)
7414{
7415 // mute/unmute strategies using an incompatible device combination
7416 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7417 // if unmuting, unmute only after the specified delay
7418 if (outputDesc->isDuplicated()) {
7419 return 0;
7420 }
7421
7422 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007423 DeviceVector devices = outputDesc->devices();
7424 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007425
François Gaffiec005e562018-11-06 15:04:49 +01007426 auto productStrategies = mEngine->getOrderedProductStrategies();
7427 for (const auto &productStrategy : productStrategies) {
7428 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7429 DeviceVector curDevices =
7430 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7431 curDevices = curDevices.filter(outputDesc->supportedDevices());
7432 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007433 bool doMute = false;
7434
François Gaffiec005e562018-11-06 15:04:49 +01007435 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007436 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007437 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7438 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007439 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007440 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007441 }
Eric Laurent99401132014-05-07 19:48:15 -07007442 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007443 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007444 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007445 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007446 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007447 continue;
7448 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307449 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007450 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7451 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7452 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007453 if (mute) {
7454 // FIXME: should not need to double latency if volume could be applied
7455 // immediately by the audioflinger mixer. We must account for the delay
7456 // between now and the next time the audioflinger thread for this output
7457 // will process a buffer (which corresponds to one buffer size,
7458 // usually 1/2 or 1/4 of the latency).
7459 if (muteWaitMs < desc->latency() * 2) {
7460 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007461 }
7462 }
7463 }
7464 }
7465 }
7466 }
7467
Eric Laurent99401132014-05-07 19:48:15 -07007468 // temporary mute output if device selection changes to avoid volume bursts due to
7469 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007470 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007471 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007472
Eric Laurentdc462862016-07-19 12:29:53 -07007473 if (muteWaitMs < tempMuteWaitMs) {
7474 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007475 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007476
7477 // If recommended duration is defined, replace temporary mute duration to avoid
7478 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7479 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7480 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7481 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7482 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7483
François Gaffieaaac0fd2018-11-22 17:56:39 +01007484 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7485 // make sure that we do not start the temporary mute period too early in case of
7486 // delayed device change
7487 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7488 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007489 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007490 }
7491 }
7492
Eric Laurente552edb2014-03-10 17:42:56 -07007493 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7494 if (muteWaitMs > delayMs) {
7495 muteWaitMs -= delayMs;
7496 usleep(muteWaitMs * 1000);
7497 return muteWaitMs;
7498 }
7499 return 0;
7500}
7501
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307502uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7503 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007504 const DeviceVector &devices,
7505 bool force,
7506 int delayMs,
7507 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007508 bool requiresMuteCheck, bool requiresVolumeCheck,
7509 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007510{
jiabin3ff8d7d2022-12-13 06:27:44 +00007511 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307512 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7513 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7514 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007515 uint32_t muteWaitMs;
7516
7517 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307518 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007519 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307520 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007521 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007522 return muteWaitMs;
7523 }
Eric Laurente552edb2014-03-10 17:42:56 -07007524
7525 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007526 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007527 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007528 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007529
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307530 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7531 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007532
7533 if (!filteredDevices.isEmpty()) {
7534 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007535 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007536
7537 // if the outputs are not materially active, there is no need to mute.
7538 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007539 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007540 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307541 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7542 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007543 muteWaitMs = 0;
7544 }
Eric Laurente552edb2014-03-10 17:42:56 -07007545
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007546 bool outputRouted = outputDesc->isRouted();
7547
Eric Laurent79ea9582020-06-11 18:49:24 -07007548 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7549 // output profile or if new device is not supported AND previous device(s) is(are) still
7550 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007551 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307552 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7553 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007554 // restore previous device after evaluating strategy mute state
7555 outputDesc->setDevices(prevDevices);
7556 return muteWaitMs;
7557 }
7558
Eric Laurente552edb2014-03-10 17:42:56 -07007559 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007560 // the requested device is AUDIO_DEVICE_NONE
7561 // OR the requested device is the same as current device
7562 // AND force is not specified
7563 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007564 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007565 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307566 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7567 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7568 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007569 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307570 ALOGV("%s %s setting same device on routed output, force apply volumes",
7571 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007572 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7573 }
Eric Laurente552edb2014-03-10 17:42:56 -07007574 return muteWaitMs;
7575 }
7576
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307577 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7578 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007579
Eric Laurente552edb2014-03-10 17:42:56 -07007580 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007581 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007582 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007583 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007584 PatchBuilder patchBuilder;
7585 patchBuilder.addSource(outputDesc);
7586 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7587 for (const auto &filteredDevice : filteredDevices) {
7588 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007589 }
7590
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007591 // Add half reported latency to delayMs when muteWaitMs is null in order
7592 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007593 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7594 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7595 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007596 }
Eric Laurente552edb2014-03-10 17:42:56 -07007597
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007598 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7599 if (!skipMuteDelay) {
7600 // update stream volumes according to new device
7601 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7602 }
Eric Laurente552edb2014-03-10 17:42:56 -07007603
7604 return muteWaitMs;
7605}
7606
Eric Laurentc75307b2015-03-17 15:29:32 -07007607status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007608 int delayMs,
7609 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007610{
Eric Laurent6a94d692014-05-20 11:18:06 -07007611 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007612 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7613 return INVALID_OPERATION;
7614 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007615 if (patchHandle) {
7616 index = mAudioPatches.indexOfKey(*patchHandle);
7617 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007618 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007619 }
7620 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007621 return INVALID_OPERATION;
7622 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007623 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007624 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007625 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007626 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007627 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007628 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007629 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007630 return status;
7631}
7632
7633status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007634 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007635 bool force,
7636 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007637{
7638 status_t status = NO_ERROR;
7639
Eric Laurent1f2f2232014-06-02 12:01:23 -07007640 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007641 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7642 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007643
François Gaffie11d30102018-11-02 16:09:09 +01007644 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007645 PatchBuilder patchBuilder;
7646 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007647 // AUDIO_SOURCE_HOTWORD is for internal use only:
7648 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007649 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7650 auto result = usecase;
7651 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7652 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7653 }
7654 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007655 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007656 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007657 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007658 }
7659 }
7660 return status;
7661}
7662
Eric Laurent6a94d692014-05-20 11:18:06 -07007663status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7664 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007665{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007666 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007667 ssize_t index;
7668 if (patchHandle) {
7669 index = mAudioPatches.indexOfKey(*patchHandle);
7670 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007671 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007672 }
7673 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007674 return INVALID_OPERATION;
7675 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007676 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007677 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007678 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007679 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007680 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007681 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007682 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007683 return status;
7684}
7685
François Gaffie11d30102018-11-02 16:09:09 +01007686sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007687 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007688 audio_format_t& format,
7689 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007690 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007691{
7692 // Choose an input profile based on the requested capture parameters: select the first available
7693 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007694 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007695 //
7696 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7697 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007698
Atneya Nair0f0a8032022-12-12 16:20:12 -08007699 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7700 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7701 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7702
7703 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007704
jiabin2fd710d2022-05-02 23:20:22 +00007705 for (;;) {
7706 sp<IOProfile> firstInexact = nullptr;
7707 uint32_t updatedSamplingRate = 0;
7708 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7709 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7710 for (const auto& hwModule : mHwModules) {
7711 for (const auto& profile : hwModule->getInputProfiles()) {
7712 // profile->log();
7713 //updatedFormat = format;
7714 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7715 &samplingRate /*updatedSamplingRate*/,
7716 format,
7717 &format, /*updatedFormat*/
7718 channelMask,
7719 &channelMask /*updatedChannelMask*/,
7720 // FIXME ugly cast
7721 (audio_output_flags_t) flags,
7722 true /*exactMatchRequiredForInputFlags*/)) {
7723 return profile;
7724 }
7725 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7726 samplingRate,
7727 &updatedSamplingRate,
7728 format,
7729 &updatedFormat,
7730 channelMask,
7731 &updatedChannelMask,
7732 // FIXME ugly cast
7733 (audio_output_flags_t) flags,
7734 false /*exactMatchRequiredForInputFlags*/)) {
7735 firstInexact = profile;
7736 }
7737 }
7738 }
7739
7740 if (firstInexact != nullptr) {
7741 samplingRate = updatedSamplingRate;
7742 format = updatedFormat;
7743 channelMask = updatedChannelMask;
7744 return firstInexact;
7745 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7746 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7747 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7748 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7749 flags = AUDIO_INPUT_FLAG_NONE;
7750 } else { // fail
7751 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7752 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7753 samplingRate, format, channelMask, oriFlags);
7754 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007755 }
7756 }
jiabin2fd710d2022-05-02 23:20:22 +00007757
7758 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007759}
7760
François Gaffieaaac0fd2018-11-22 17:56:39 +01007761float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7762 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007763 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007764 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007765{
jiabin9a3361e2019-10-01 09:38:30 -07007766 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007767
7768 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7769 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7770 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7771 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007772 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7773 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7774 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7775 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7776 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007777 // Verify that the current volume source is not the ringer volume to prevent recursively
7778 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7779 // to the same volume group.
7780 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007781 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7782 mOutputs.isActive(ringVolumeSrc, 0)) {
7783 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007784 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007785 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007786 }
7787
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007788 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007789 if ((volumeSource != callVolumeSrc && (isInCall() ||
7790 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007791 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007792 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7793 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007794 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7795 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7796 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007797 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007798 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007799 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007800 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007801 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007802 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007803 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7804 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7805 // programmatically muted.
7806 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7807 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7808 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007809 bool exemptFromCapping =
7810 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7811 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007812 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7813 volumeSource, volumeDb);
7814 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007815 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7816 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7817 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007818 }
7819 }
Eric Laurente552edb2014-03-10 17:42:56 -07007820 // if a headset is connected, apply the following rules to ring tones and notifications
7821 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007822 // - always attenuate notifications volume by 6dB
7823 // - attenuate ring tones volume by 6dB unless music is not playing and
7824 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007825 // - if music is playing, always limit the volume to current music volume,
7826 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007827 if (!Intersection(deviceTypes,
7828 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7829 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007830 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7831 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007832 ((volumeSource == alarmVolumeSrc ||
7833 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007834 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7835 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7836 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007837 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7838 curves.canBeMuted()) {
7839
Eric Laurente552edb2014-03-10 17:42:56 -07007840 // when the phone is ringing we must consider that music could have been paused just before
7841 // by the music application and behave as if music was active if the last music track was
7842 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007843 // Verify that the current volume source is not the music volume to prevent recursively
7844 // calling to compute volume. This could happen in cases where music and
7845 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7846 if (volumeSource != musicVolumeSrc &&
7847 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7848 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007849 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007850 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007851 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7852 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007853 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007854 float musicVolDb = computeVolume(musicCurves,
7855 musicVolumeSrc,
7856 musicCurves.getVolumeIndex(musicDevice),
7857 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007858 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7859 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7860 if (volumeDb > minVolDb) {
7861 volumeDb = minVolDb;
7862 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007863 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007864 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7865 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7866 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007867 // on A2DP, also ensure notification volume is not too low compared to media when
7868 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007869 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007870 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007871 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7872 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007873 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7874 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007875 }
7876 }
jiabin9a3361e2019-10-01 09:38:30 -07007877 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007878 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007879 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007880 }
7881 }
7882
François Gaffie43c73442018-11-08 08:21:55 +01007883 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007884}
7885
Eric Laurent3839bc02018-07-10 18:33:34 -07007886int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007887 VolumeSource fromVolumeSource,
7888 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007889{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007890 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007891 return srcIndex;
7892 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007893 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7894 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007895 float minSrc = (float)srcCurves.getVolumeIndexMin();
7896 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7897 float minDst = (float)dstCurves.getVolumeIndexMin();
7898 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007899
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007900 // preserve mute request or correct range
7901 if (srcIndex < minSrc) {
7902 if (srcIndex == 0) {
7903 return 0;
7904 }
7905 srcIndex = minSrc;
7906 } else if (srcIndex > maxSrc) {
7907 srcIndex = maxSrc;
7908 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007909 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7910}
7911
François Gaffieaaac0fd2018-11-22 17:56:39 +01007912status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7913 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007914 int index,
7915 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007916 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007917 int delayMs,
7918 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007919{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007920 // do not change actual attributes volume if the attributes is muted
7921 if (outputDesc->isMuted(volumeSource)) {
7922 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7923 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007924 return NO_ERROR;
7925 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007926
Eric Laurentae6e88c2024-01-10 14:42:57 +01007927 bool isVoiceVolSrc;
7928 bool isBtScoVolSrc;
7929 if (!isVolumeConsistentForCalls(
7930 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07007931 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01007932 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07007933 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007934 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01007935
jiabin9a3361e2019-10-01 09:38:30 -07007936 if (deviceTypes.empty()) {
7937 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007938 index = curves.getVolumeIndex(deviceTypes);
7939 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7940 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007941 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007942
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007943 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7944 ALOGE("invalid volume index range");
7945 return BAD_VALUE;
7946 }
7947
jiabin9a3361e2019-10-01 09:38:30 -07007948 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7949 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007950 // Force VoIP volume to max for bluetooth SCO device except if muted
7951 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007952 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007953 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007954 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007955 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007956 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7957 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007958
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007959 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01007960 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007961 }
Eric Laurente552edb2014-03-10 17:42:56 -07007962 return NO_ERROR;
7963}
7964
Eric Laurentae6e88c2024-01-10 14:42:57 +01007965void AudioPolicyManager::setVoiceVolume(
7966 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
7967 float voiceVolume;
7968 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
7969 // by the headset
7970 if (isVoiceVolSrc) {
7971 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
7972 } else {
7973 voiceVolume = index == 0 ? 0.0 : 1.0;
7974 }
7975 if (voiceVolume != mLastVoiceVolume) {
7976 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7977 mLastVoiceVolume = voiceVolume;
7978 }
7979}
7980
7981bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
7982 const DeviceTypeSet& deviceTypes,
7983 bool& isVoiceVolSrc,
7984 bool& isBtScoVolSrc,
7985 const char* caller) {
7986 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7987 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7988 const bool isScoRequested = isScoRequestedForComm();
7989 const bool isHAUsed = isHearingAidUsedForComm();
7990
7991 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7992 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
7993
7994 if ((callVolSrc != btScoVolSrc) &&
7995 ((isVoiceVolSrc && isScoRequested) ||
7996 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7997 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
7998 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
7999 volumeSource, isScoRequested ? " " : " not ");
8000 return false;
8001 }
8002 return true;
8003}
8004
Eric Laurentc75307b2015-03-17 15:29:32 -07008005void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008006 const DeviceTypeSet& deviceTypes,
8007 int delayMs,
8008 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008009{
jiabincd510522020-01-22 09:40:55 -08008010 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008011 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8012 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8013 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008014 curves.getVolumeIndex(deviceTypes),
8015 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008016 }
8017}
8018
François Gaffiec005e562018-11-06 15:04:49 +01008019void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8020 bool on,
8021 const sp<AudioOutputDescriptor>& outputDesc,
8022 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008023 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008024{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008025 std::vector<VolumeSource> sourcesToMute;
8026 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8027 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8028 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008029 VolumeSource source = toVolumeSource(attributes, false);
8030 if ((source != VOLUME_SOURCE_NONE) &&
8031 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8032 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008033 sourcesToMute.push_back(source);
8034 }
Eric Laurente552edb2014-03-10 17:42:56 -07008035 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008036 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008037 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008038 }
8039
Eric Laurente552edb2014-03-10 17:42:56 -07008040}
8041
François Gaffieaaac0fd2018-11-22 17:56:39 +01008042void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8043 bool on,
8044 const sp<AudioOutputDescriptor>& outputDesc,
8045 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008046 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008047{
jiabin9a3361e2019-10-01 09:38:30 -07008048 if (deviceTypes.empty()) {
8049 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008050 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008051 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008052 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008053 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008054 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008055 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008056 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8057 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008058 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008059 }
8060 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008061 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8062 // ignored
8063 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008064 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008065 if (!outputDesc->isMuted(volumeSource)) {
8066 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008067 return;
8068 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008069 if (outputDesc->decMuteCount(volumeSource) == 0) {
8070 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008071 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008072 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008073 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008074 delayMs);
8075 }
8076 }
8077}
8078
François Gaffie53615e22015-03-19 09:24:12 +01008079bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8080{
François Gaffiec005e562018-11-06 15:04:49 +01008081 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008082 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8083 return true;
8084 }
8085
8086 // has known usage?
8087 switch (paa->usage) {
8088 case AUDIO_USAGE_UNKNOWN:
8089 case AUDIO_USAGE_MEDIA:
8090 case AUDIO_USAGE_VOICE_COMMUNICATION:
8091 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8092 case AUDIO_USAGE_ALARM:
8093 case AUDIO_USAGE_NOTIFICATION:
8094 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8095 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8096 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8097 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8098 case AUDIO_USAGE_NOTIFICATION_EVENT:
8099 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8100 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8101 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8102 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008103 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008104 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008105 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008106 case AUDIO_USAGE_EMERGENCY:
8107 case AUDIO_USAGE_SAFETY:
8108 case AUDIO_USAGE_VEHICLE_STATUS:
8109 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008110 break;
8111 default:
8112 return false;
8113 }
8114 return true;
8115}
8116
François Gaffie2110e042015-03-24 08:41:51 +01008117audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8118{
8119 return mEngine->getForceUse(usage);
8120}
8121
Eric Laurent96d1dda2022-03-14 17:14:19 +01008122bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008123 return isStateInCall(mEngine->getPhoneState());
8124}
8125
Eric Laurent96d1dda2022-03-14 17:14:19 +01008126bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008127 return is_state_in_call(state);
8128}
8129
Eric Laurentf9cccec2022-11-16 19:12:00 +01008130bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008131 audio_mode_t mode = mEngine->getPhoneState();
8132 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008133 || (mode == AUDIO_MODE_CALL_SCREEN)
8134 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008135}
8136
Eric Laurentf9cccec2022-11-16 19:12:00 +01008137bool AudioPolicyManager::isInCallOrScreening() const {
8138 audio_mode_t mode = mEngine->getPhoneState();
8139 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8140}
8141
Eric Laurentd60560a2015-04-10 11:31:20 -07008142void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8143{
8144 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008145 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008146 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008147 sourceDesc->sinkDevice()->equals(deviceDesc))
8148 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008149 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008150 }
8151 }
8152
8153 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8154 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8155 bool release = false;
8156 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8157 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8158 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8159 source->ext.device.type == deviceDesc->type()) {
8160 release = true;
8161 }
8162 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008163 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008164 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8165 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8166 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008167 sink->ext.device.type == deviceDesc->type() &&
8168 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8169 || strncmp(sink->ext.device.address, address,
8170 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008171 release = true;
8172 }
8173 }
8174 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008175 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8176 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008177 }
8178 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008179
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008180 mInputs.clearSessionRoutesForDevice(deviceDesc);
8181
Francois Gaffie716e1432019-01-14 16:58:59 +01008182 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008183}
8184
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008185void AudioPolicyManager::modifySurroundFormats(
8186 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008187 std::unordered_set<audio_format_t> enforcedSurround(
8188 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008189 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008190 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008191 allSurround.insert(pair.first);
8192 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8193 }
Phil Burk09bc4612016-02-24 15:58:15 -08008194
8195 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8196 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008197 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008198 // This is the resulting set of formats depending on the surround mode:
8199 // 'all surround' = allSurround
8200 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8201 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8202 // 'manual surround' = mManualSurroundFormats
8203 // AUTO: formats v 'enforced surround'
8204 // ALWAYS: formats v 'all surround' v 'enforced surround'
8205 // NEVER: formats ^ 'non-surround'
8206 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008207
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008208 std::unordered_set<audio_format_t> formatSet;
8209 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8210 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008211 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008212 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008213 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008214 formatSet.insert(*formatIter);
8215 }
8216 }
8217 } else {
8218 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8219 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008220 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008221
jiabin81772902018-04-02 17:52:27 -07008222 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008223 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008224 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8225 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8226 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008227 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008228 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8229 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8230 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008231 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008232 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008233 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008234 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008235 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008236 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008237}
8238
jiabin06e4bab2019-07-29 10:13:34 -07008239void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8240 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008241 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8242 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8243
8244 // If NEVER, then remove support for channelMasks > stereo.
8245 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008246 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8247 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008248 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008249 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008250 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008251 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008252 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008253 }
8254 }
jiabin81772902018-04-02 17:52:27 -07008255 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8256 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8257 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008258 bool supports5dot1 = false;
8259 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008260 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008261 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8262 supports5dot1 = true;
8263 break;
8264 }
8265 }
8266 // If not then add 5.1 support.
8267 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008268 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008269 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008270 }
Phil Burk09bc4612016-02-24 15:58:15 -08008271 }
8272}
8273
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008274void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008275 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008276 const sp<IOProfile>& profile) {
8277 if (!profile->hasDynamicAudioProfile()) {
8278 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008279 }
François Gaffie112b0af2015-11-19 16:13:25 +01008280
jiabin12537fc2023-10-12 17:56:08 +00008281 audio_port_v7 devicePort;
8282 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008283
jiabin12537fc2023-10-12 17:56:08 +00008284 audio_port_v7 mixPort;
8285 profile->toAudioPort(&mixPort);
8286 mixPort.ext.mix.handle = ioHandle;
8287
8288 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8289 if (status != NO_ERROR) {
8290 ALOGE("%s failed to query the attributes of the mix port", __func__);
8291 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008292 }
jiabin12537fc2023-10-12 17:56:08 +00008293
8294 std::set<audio_format_t> supportedFormats;
8295 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8296 supportedFormats.insert(mixPort.audio_profiles[i].format);
8297 }
8298 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8299 mReportedFormatsMap[devDesc] = formats;
8300
8301 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8302 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8303 modifySurroundFormats(devDesc, &formats);
8304 size_t modifiedNumProfiles = 0;
8305 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8306 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8307 formats.end()) {
8308 // Skip the format that is not present after modifying surround formats.
8309 continue;
8310 }
8311 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8312 sizeof(struct audio_profile));
8313 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8314 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8315 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8316 modifySurroundChannelMasks(&channels);
8317 std::copy(channels.begin(), channels.end(),
8318 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8319 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8320 }
8321 mixPort.num_audio_profiles = modifiedNumProfiles;
8322 }
8323 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008324}
Eric Laurentd60560a2015-04-10 11:31:20 -07008325
Mikhail Naganovdc769682018-05-04 15:34:08 -07008326status_t AudioPolicyManager::installPatch(const char *caller,
8327 audio_patch_handle_t *patchHandle,
8328 AudioIODescriptorInterface *ioDescriptor,
8329 const struct audio_patch *patch,
8330 int delayMs)
8331{
8332 ssize_t index = mAudioPatches.indexOfKey(
8333 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8334 *patchHandle : ioDescriptor->getPatchHandle());
8335 sp<AudioPatch> patchDesc;
8336 status_t status = installPatch(
8337 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8338 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008339 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008340 }
8341 return status;
8342}
8343
8344status_t AudioPolicyManager::installPatch(const char *caller,
8345 ssize_t index,
8346 audio_patch_handle_t *patchHandle,
8347 const struct audio_patch *patch,
8348 int delayMs,
8349 uid_t uid,
8350 sp<AudioPatch> *patchDescPtr)
8351{
8352 sp<AudioPatch> patchDesc;
8353 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8354 if (index >= 0) {
8355 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008356 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008357 }
8358
8359 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8360 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8361 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8362 if (status == NO_ERROR) {
8363 if (index < 0) {
8364 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008365 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008366 } else {
8367 patchDesc->mPatch = *patch;
8368 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008369 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008370 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008371 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008372 }
8373 nextAudioPortGeneration();
8374 mpClientInterface->onAudioPatchListUpdate();
8375 }
8376 if (patchDescPtr) *patchDescPtr = patchDesc;
8377 return status;
8378}
8379
jiabinbce0c1d2020-10-05 11:20:18 -07008380bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8381{
8382 const TrackClientVector activeClients = output->getActiveClients();
8383 if (activeClients.empty()) {
8384 return true;
8385 }
8386 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8387 if (index < 0) {
8388 ALOGE("%s, no audio patch found while there are active clients on output %d",
8389 __func__, output->getId());
8390 return false;
8391 }
8392 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8393 DeviceVector routedDevices;
8394 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8395 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8396 patchDesc->mPatch.sinks[i].id);
8397 if (device == nullptr) {
8398 ALOGE("%s, no audio device found with id(%d)",
8399 __func__, patchDesc->mPatch.sinks[i].id);
8400 return false;
8401 }
8402 routedDevices.add(device);
8403 }
8404 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008405 if (client->isInvalid()) {
8406 // No need to take care about invalidated clients.
8407 continue;
8408 }
jiabinbce0c1d2020-10-05 11:20:18 -07008409 sp<DeviceDescriptor> preferredDevice =
8410 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8411 if (mEngine->getOutputDevicesForAttributes(
8412 client->attributes(), preferredDevice, false) == routedDevices) {
8413 return false;
8414 }
8415 }
8416 return true;
8417}
8418
8419sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008420 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008421 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8422 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008423{
8424 for (const auto& device : devices) {
8425 // TODO: This should be checking if the profile supports the device combo.
8426 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008427 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8428 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008429 return nullptr;
8430 }
8431 }
8432 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8433 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008434 status_t status = desc->open(halConfig, mixerConfig, devices,
8435 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008436 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008437 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008438 return nullptr;
8439 }
jiabin14b50cc2023-12-13 19:01:52 +00008440 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8441 auto portConfig = desc->getConfig();
8442 for (const auto& device : devices) {
8443 device->setPreferredConfig(&portConfig);
8444 }
8445 }
jiabinbce0c1d2020-10-05 11:20:18 -07008446
8447 // Here is where the out_set_parameters() for card & device gets called
8448 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8449 const audio_devices_t deviceType = device->type();
8450 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008451 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008452 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8453 mpClientInterface->setParameters(output, String8(param));
8454 free(param);
8455 }
jiabin12537fc2023-10-12 17:56:08 +00008456 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008457 if (!profile->hasValidAudioProfile()) {
8458 ALOGW("%s() missing param", __func__);
8459 desc->close();
8460 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008461 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8462 // Reopen the output with the best audio profile picked by APM when the profile supports
8463 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008464 desc->close();
8465 output = AUDIO_IO_HANDLE_NONE;
8466 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8467 profile->pickAudioProfile(
8468 config.sample_rate, config.channel_mask, config.format);
8469 config.offload_info.sample_rate = config.sample_rate;
8470 config.offload_info.channel_mask = config.channel_mask;
8471 config.offload_info.format = config.format;
8472
jiabina84c3d32022-12-02 18:59:55 +00008473 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008474 if (status != NO_ERROR) {
8475 return nullptr;
8476 }
8477 }
8478
8479 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008480
baek.kim -61c20122022-07-27 10:05:32 +00008481 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8482 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8483
jiabinbce0c1d2020-10-05 11:20:18 -07008484 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8485 sp<AudioPolicyMix> policyMix;
8486 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8487 policyMix->setOutput(desc);
8488 desc->mPolicyMix = policyMix;
8489 } else {
8490 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008491 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008492 }
8493
baek.kim -61c20122022-07-27 10:05:32 +00008494 } else if (hasPrimaryOutput() && speaker != nullptr
8495 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008496 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8497 // no duplicated output for:
8498 // - direct outputs
8499 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008500 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008501 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8502
8503 //TODO: configure audio effect output stage here
8504
8505 // open a duplicating output thread for the new output and the primary output
8506 sp<SwAudioOutputDescriptor> dupOutputDesc =
8507 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8508 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8509 if (status == NO_ERROR) {
8510 // add duplicated output descriptor
8511 addOutput(duplicatedOutput, dupOutputDesc);
8512 } else {
8513 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8514 mPrimaryOutput->mIoHandle, output);
8515 desc->close();
8516 removeOutput(output);
8517 nextAudioPortGeneration();
8518 return nullptr;
8519 }
8520 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008521 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8522 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8523 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008524 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008525 }
jiabinbce0c1d2020-10-05 11:20:18 -07008526 return desc;
8527}
8528
jiabinf1c73972022-04-14 16:28:52 -07008529status_t AudioPolicyManager::getDevicesForAttributes(
8530 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8531 // Devices are determined in the following precedence:
8532 //
8533 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8534 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8535 //
8536 // If no such dynamic policy then
8537 // 2) Devices containing an active client using setPreferredDevice
8538 // with same strategy as the attributes.
8539 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8540 //
8541 // If no corresponding active client with setPreferredDevice then
8542 // 3) Devices associated with the strategy determined by the attributes
8543 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8544 //
8545 // See related getOutputForAttrInt().
8546
8547 // check dynamic policies but only for primary descriptors (secondary not used for audible
8548 // audio routing, only used for duplication for playback capture)
8549 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008550 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008551 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008552 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8553 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8554 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008555 if (status != OK) {
8556 return status;
8557 }
8558
8559 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8560 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8561 // as they are unaffected by device/stream volume
8562 // (per SwAudioOutputDescriptor::isFixedVolume()).
8563 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8564 ) {
8565 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8566 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8567 devices.add(deviceDesc);
8568 } else {
8569 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8570 // which selects setPreferredDevice if active. This means forVolume call
8571 // will take an active setPreferredDevice, if such exists.
8572
8573 devices = mEngine->getOutputDevicesForAttributes(
8574 attr, nullptr /* preferredDevice */, false /* fromCache */);
8575 }
8576
8577 if (forVolume) {
8578 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8579 // for single volume control in AudioService (such relationship should exist if
8580 // SPEAKER_SAFE is present).
8581 //
8582 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8583 DeviceVector speakerSafeDevices =
8584 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8585 if (!speakerSafeDevices.isEmpty()) {
8586 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8587 devices.remove(speakerSafeDevices);
8588 }
8589 }
8590
8591 return NO_ERROR;
8592}
8593
8594status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8595 AudioProfileVector& audioProfiles,
8596 uint32_t flags,
8597 bool isInput) {
8598 for (const auto& hwModule : mHwModules) {
8599 // the MSD module checks for different conditions
8600 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8601 continue;
8602 }
8603 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8604 : hwModule->getOutputProfiles();
8605 for (const auto& profile : ioProfiles) {
8606 if (!profile->areAllDevicesSupported(devices) ||
8607 !profile->isCompatibleProfileForFlags(
8608 flags, false /*exactMatchRequiredForInputFlags*/)) {
8609 continue;
8610 }
8611 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8612 }
8613 }
8614
8615 if (!isInput) {
8616 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8617 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8618 if (msdModule != nullptr) {
8619 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8620 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8621 for (const auto &profile: msdModule->getOutputProfiles()) {
8622 if (!profile->asAudioPort()->isDirectOutput()) {
8623 continue;
8624 }
8625 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8626 }
8627 } else {
8628 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8629 }
8630 }
8631 }
8632
8633 return NO_ERROR;
8634}
8635
jiabin3ff8d7d2022-12-13 06:27:44 +00008636sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8637 const audio_config_t *config,
8638 audio_output_flags_t flags,
8639 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008640 closeOutput(outputDesc->mIoHandle);
8641 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8642 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8643 if (preferredOutput == nullptr) {
8644 ALOGE("%s failed to reopen output device=%d, caller=%s",
8645 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008646 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008647 return preferredOutput;
8648}
8649
8650void AudioPolicyManager::reopenOutputsWithDevices(
8651 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8652 for (const auto& [output, devices] : outputsToReopen) {
8653 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8654 closeOutput(output);
8655 openOutputWithProfileAndDevice(desc->mProfile, devices);
8656 }
jiabina84c3d32022-12-02 18:59:55 +00008657}
8658
jiabinc44b3462022-12-08 12:52:31 -08008659PortHandleVector AudioPolicyManager::getClientsForStream(
8660 audio_stream_type_t streamType) const {
8661 PortHandleVector clients;
8662 for (size_t i = 0; i < mOutputs.size(); ++i) {
8663 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8664 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8665 }
8666 return clients;
8667}
8668
8669void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8670 PortHandleVector clients;
8671 for (auto stream : streams) {
8672 PortHandleVector clientsForStream = getClientsForStream(stream);
8673 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8674 }
8675 mpClientInterface->invalidateTracks(clients);
8676}
8677
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008678} // namespace android