blob: 6160f774fd1cb5f7941d8cfd0c2a543a8637020a [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 Laurent541a2002024-01-15 18:11:42 +010021// to enable VERBOSE logging dynamicstartAudioSourceally.
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 Laurentb0a7bc92022-04-05 15:06:08 +02001635 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001636 if (mSpatializerOutput != nullptr
jiabin2462ce82024-01-12 20:37:59 +00001637 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())
1638 && prefMixerConfigInfo == nullptr) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001639 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001640 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001641 }
1642
Eric Laurentc529cf62020-04-17 18:19:10 -07001643 audio_config_t directConfig = *config;
1644 directConfig.channel_mask = channelMask;
1645 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1646 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001647 return output;
1648 }
1649
Eric Laurent14cbfca2016-03-17 09:42:16 -07001650 // A request for HW A/V sync cannot fallback to a mixed output because time
1651 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001652 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001653 return AUDIO_IO_HANDLE_NONE;
1654 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001655 // A request for Tuner cannot fallback to a mixed output
1656 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1657 return AUDIO_IO_HANDLE_NONE;
1658 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001659
Eric Laurente552edb2014-03-10 17:42:56 -07001660 // ignoring channel mask due to downmix capability in mixer
1661
1662 // open a non direct output
1663
1664 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001665 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001666 // get which output is suitable for the specified stream. The actual
1667 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001668 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001669 if (prefMixerConfigInfo != nullptr) {
1670 for (audio_io_handle_t outputHandle : outputs) {
1671 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1672 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1673 output = outputHandle;
1674 break;
1675 }
1676 }
1677 if (output == AUDIO_IO_HANDLE_NONE) {
1678 // No output open with the preferred profile. Open a new one.
1679 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1680 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1681 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1682 config.format = prefMixerConfigInfo->getConfigBase().format;
1683 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1684 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1685 &config, prefMixerConfigInfo->getFlags());
1686 if (preferredOutput == nullptr) {
1687 ALOGE("%s failed to open output with preferred mixer config", __func__);
1688 } else {
1689 output = preferredOutput->mIoHandle;
1690 }
1691 }
1692 } else {
1693 // at this stage we should ignore the DIRECT flag as no direct output could be
1694 // found earlier
1695 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1696 output = selectOutput(
1697 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1698 }
Eric Laurente552edb2014-03-10 17:42:56 -07001699 }
François Gaffie11d30102018-11-02 16:09:09 +01001700 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001701 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001702 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001703
Eric Laurente552edb2014-03-10 17:42:56 -07001704 return output;
1705}
1706
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001707sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001708 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1709 mAvailableInputDevices);
1710 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1711}
1712
1713DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1714 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1715 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001716}
1717
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001718const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001719 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001720 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1721 if (msdModule != 0) {
1722 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1723 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1724 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1725 const struct audio_port_config *source = &patch->mPatch.sources[j];
1726 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1727 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001728 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001729 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001730 }
1731 }
1732 }
1733 return msdPatches;
1734}
1735
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001736bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1737 ssize_t index = mAudioPatches.indexOfKey(handle);
1738 if (index < 0) {
1739 return false;
1740 }
1741 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1742 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1743 if (msdModule == nullptr) {
1744 return false;
1745 }
1746 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1747 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1748 return true;
1749 }
1750 index = getMsdOutputPatches().indexOfKey(handle);
1751 if (index < 0) {
1752 return false;
1753 }
1754 return true;
1755}
1756
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001757status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1758 const InputProfileCollection &inputProfiles,
1759 const OutputProfileCollection &outputProfiles,
1760 const sp<DeviceDescriptor> &sourceDevice,
1761 const sp<DeviceDescriptor> &sinkDevice,
1762 AudioProfileVector& sourceProfiles,
1763 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001764 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001765 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001766 return NO_INIT;
1767 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001768 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001769 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001770 return NO_INIT;
1771 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001772 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001773 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1774 inProfile->supportsDevice(sourceDevice)) {
1775 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001776 }
1777 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001778 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001779 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001780 outProfile->supportsDevice(sinkDevice)) {
1781 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001782 }
1783 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001784 return NO_ERROR;
1785}
1786
1787status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1788 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1789 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1790{
Dean Wheatley16809da2022-12-09 14:55:46 +11001791 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1792 static const std::vector<audio_format_t> formatsOrder = {{
1793 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001794 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1795 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001796 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1797 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1798 // preferred).
1799 std::vector<audio_channel_mask_t> masks = {{
1800 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1801 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1802 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1803 // insert index masks (higher counts most preferred) as preferred over position masks
1804 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1805 masks.insert(
1806 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1807 }
1808 return masks;
1809 }();
1810
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001811 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001812 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1813 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001814 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001815 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1816 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001817 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001818 }
1819 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1820 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1821 sinkConfig->format = bestSinkConfig.format;
1822 // For encoded streams force direct flag to prevent downstream mixing.
1823 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1824 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001825 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1826 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001827 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001828 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1829 // raw and IEC61937 framed streams.
1830 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1831 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1832 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001833 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1834 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001835 sourceConfig->channel_mask =
1836 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1837 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1838 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001839 sourceConfig->format = bestSinkConfig.format;
1840 // Copy input stream directly without any processing (e.g. resampling).
1841 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1842 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1843 if (hwAvSync) {
1844 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1845 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1846 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1847 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1848 }
1849 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1850 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1851 sinkConfig->config_mask |= config_mask;
1852 sourceConfig->config_mask |= config_mask;
1853 return NO_ERROR;
1854}
1855
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001856PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1857 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001858{
1859 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001860 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1861 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1862 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1863 if (deviceModule == nullptr) {
1864 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1865 return patchBuilder;
1866 }
1867 const InputProfileCollection inputProfiles = msdIsSource ?
1868 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1869 const OutputProfileCollection outputProfiles = msdIsSource ?
1870 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1871
1872 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1873 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1874 device : getMsdAudioOutDevices().itemAt(0);
1875 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1876
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001877 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1878 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001879 AudioProfileVector sourceProfiles;
1880 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001881 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1882 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001883 for (auto hwAvSync : { true, false }) {
1884 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1885 sourceProfiles, sinkProfiles) != NO_ERROR) {
1886 continue;
1887 }
1888 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1889 &sinkConfig) == NO_ERROR) {
1890 // Found a matching config. Re-create PatchBuilder with this config.
1891 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1892 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001893 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001894 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001895 " supporting PCM format conversion.", __func__);
1896 return patchBuilder;
1897}
1898
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001899status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001900 DeviceVector devices;
1901 if (outputDevices != nullptr && outputDevices->size() > 0) {
1902 devices.add(*outputDevices);
1903 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001904 // Use media strategy for unspecified output device. This should only
1905 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1906 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001907 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001908 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001909 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001910 }
Michael Chan6fb34492020-12-08 15:44:49 +11001911 std::vector<PatchBuilder> patchesToCreate;
1912 for (auto i = 0u; i < devices.size(); ++i) {
1913 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001914 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001915 }
1916 // Retain only the MSD patches associated with outputDevices request.
1917 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001918 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001919 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1920 auto retainedPatch = false;
1921 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1922 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1923 patchesToRemove.removeItemsAt(i);
1924 retainedPatch = true;
1925 break;
1926 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001927 }
Michael Chan6fb34492020-12-08 15:44:49 +11001928 if (retainedPatch) {
1929 it = patchesToCreate.erase(it);
1930 continue;
1931 }
1932 ++it;
1933 }
1934 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1935 return NO_ERROR;
1936 }
1937 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1938 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001939 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001940 }
Michael Chan6fb34492020-12-08 15:44:49 +11001941 status_t status = NO_ERROR;
1942 for (const auto &p : patchesToCreate) {
1943 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1944 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1945 char message[256];
1946 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1947 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1948 currStatus == NO_ERROR ? "Success" : "Error",
1949 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1950 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1951 if (currStatus == NO_ERROR) {
1952 ALOGD("%s", message);
1953 } else {
1954 ALOGE("%s", message);
1955 if (status == NO_ERROR) {
1956 status = currStatus;
1957 }
1958 }
1959 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001960 return status;
1961}
1962
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001963void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1964 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001965 for (size_t i = 0; i < msdPatches.size(); i++) {
1966 const auto& patch = msdPatches[i];
1967 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1968 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1969 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1970 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1971 releaseAudioPatch(patch->getHandle(), mUidCached);
1972 break;
1973 }
1974 }
1975 }
1976}
1977
Dorin Drimus94d94412022-02-02 09:05:02 +01001978bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001979 DeviceVector devicesToCheck =
1980 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001981 AudioPatchCollection msdPatches = getMsdOutputPatches();
1982 for (size_t i = 0; i < msdPatches.size(); i++) {
1983 const auto& patch = msdPatches[i];
1984 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1985 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1986 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1987 const auto& foundDevice = devicesToCheck.getDevice(
1988 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1989 if (foundDevice != nullptr) {
1990 devicesToCheck.remove(foundDevice);
1991 if (devicesToCheck.isEmpty()) {
1992 return true;
1993 }
1994 }
1995 }
1996 }
1997 }
1998 return false;
1999}
2000
Eric Laurente0720872014-03-11 09:30:41 -07002001audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07002002 audio_output_flags_t flags,
2003 audio_format_t format,
2004 audio_channel_mask_t channelMask,
2005 uint32_t samplingRate,
2006 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002007{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002008 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2009 "%s called with format %#x", __func__, format);
2010
jiabinebb6af42020-06-09 17:31:17 -07002011 // Return the output that haptic-generating attached to when 1) session id is specified,
2012 // 2) haptic-generating effect exists for given session id and 3) the output that
2013 // haptic-generating effect attached to is in given outputs.
2014 if (sessionId != AUDIO_SESSION_NONE) {
2015 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2016 sessionId, FX_IID_HAPTICGENERATOR);
2017 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2018 return hapticGeneratingOutput;
2019 }
2020 }
2021
Eric Laurent16c66dd2019-05-01 17:54:10 -07002022 // Flags disqualifying an output: the match must happen before calling selectOutput()
2023 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2024 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2025
2026 // Flags expressing a functional request: must be honored in priority over
2027 // other criteria
2028 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2029 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002030 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2031 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002032 // Flags expressing a performance request: have lower priority than serving
2033 // requested sampling rate or channel mask
2034 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2035 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2036 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2037
2038 const audio_output_flags_t functionalFlags =
2039 (audio_output_flags_t)(flags & kFunctionalFlags);
2040 const audio_output_flags_t performanceFlags =
2041 (audio_output_flags_t)(flags & kPerformanceFlags);
2042
2043 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2044
Eric Laurente552edb2014-03-10 17:42:56 -07002045 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002046 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002047 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002048 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002049 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002050 // with tiebreak preferring the minimum number of extra functional flags
2051 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002052 // 3: the output supporting the exact channel mask
2053 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002054 // 5: the output with the highest sampling rate if the requested sample rate is
2055 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002056 // 6: the output with the highest number of requested performance flags
2057 // 7: the output with the bit depth the closest to the requested one
2058 // 8: the primary output
2059 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002060
Eric Laurent16c66dd2019-05-01 17:54:10 -07002061 // matching criteria values in priority order for best matching output so far
2062 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002063
Eric Laurent16c66dd2019-05-01 17:54:10 -07002064 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2065 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2066 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002067
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002068 for (audio_io_handle_t output : outputs) {
2069 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002070 // matching criteria values in priority order for current output
2071 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002072
Eric Laurent16c66dd2019-05-01 17:54:10 -07002073 if (outputDesc->isDuplicated()) {
2074 continue;
2075 }
2076 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2077 continue;
2078 }
Eric Laurent8838a382014-09-08 16:44:28 -07002079
Eric Laurent16c66dd2019-05-01 17:54:10 -07002080 // If haptic channel is specified, use the haptic output if present.
2081 // When using haptic output, same audio format and sample rate are required.
2082 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002083 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002084 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2085 continue;
2086 }
2087 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002088 && format == outputDesc->getFormat()
2089 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002090 currentMatchCriteria[0] = outputHapticChannelCount;
2091 }
2092
2093 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002094 const int matchingFunctionalFlags =
2095 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2096 const int totalFunctionalFlags =
2097 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2098 // Prefer matching functional flags, but subtract unnecessary functional flags.
2099 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002100
2101 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002102 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2103 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002104 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2105 channelCount <= outputChannelCount) {
2106 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002107 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2108 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002109 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002110 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002111 currentMatchCriteria[3] = outputChannelCount;
2112 }
2113
2114 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002115 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002116 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002117 }
2118
2119 // performance flags match
2120 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2121
2122 // format match
2123 if (format != AUDIO_FORMAT_INVALID) {
2124 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002125 PolicyAudioPort::kFormatDistanceMax -
2126 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002127 }
2128
2129 // primary output match
2130 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2131
2132 // compare match criteria by priority then value
2133 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2134 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2135 bestMatchCriteria = currentMatchCriteria;
2136 bestOutput = output;
2137
2138 std::stringstream result;
2139 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2140 std::ostream_iterator<int>(result, " "));
2141 ALOGV("%s new bestOutput %d criteria %s",
2142 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002143 }
2144 }
2145
Eric Laurent16c66dd2019-05-01 17:54:10 -07002146 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002147}
2148
Eric Laurent8fc147b2018-07-22 19:13:55 -07002149status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002150{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002151 ALOGV("%s portId %d", __FUNCTION__, portId);
2152
2153 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2154 if (outputDesc == 0) {
2155 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002156 return BAD_VALUE;
2157 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002158 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002159
Eric Laurent8fc147b2018-07-22 19:13:55 -07002160 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002161 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002162
Eric Laurent733ce942017-12-07 12:18:25 -08002163 status_t status = outputDesc->start();
2164 if (status != NO_ERROR) {
2165 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002166 }
2167
Eric Laurent97ac8712018-07-27 18:59:02 -07002168 uint32_t delayMs;
2169 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002170
2171 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002172 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002173 if (status == DEAD_OBJECT) {
2174 sp<SwAudioOutputDescriptor> desc =
2175 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2176 if (desc == nullptr) {
2177 // This is not common, it may indicate something wrong with the HAL.
2178 ALOGE("%s unable to open output with default config", __func__);
2179 return status;
2180 }
2181 desc->mUsePreferredMixerAttributes = true;
2182 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002183 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002184 }
jiabina84c3d32022-12-02 18:59:55 +00002185
2186 // If the client is the first one active on preferred mixer parameters, reopen the output
2187 // if the current mixer parameters doesn't match the preferred one.
2188 if (outputDesc->devices().size() == 1) {
2189 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2190 outputDesc->devices()[0]->getId(), client->strategy());
2191 if (info != nullptr && info->getUid() == client->uid()) {
2192 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2193 info->getConfigBase(), info->getFlags())) {
2194 stopSource(outputDesc, client);
2195 outputDesc->stop();
2196 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2197 config.channel_mask = info->getConfigBase().channel_mask;
2198 config.sample_rate = info->getConfigBase().sample_rate;
2199 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002200 sp<SwAudioOutputDescriptor> desc =
2201 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2202 if (desc == nullptr) {
2203 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002204 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002205 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002206 // Intentionally return error to let the client side resending request for
2207 // creating and starting.
2208 return DEAD_OBJECT;
2209 }
2210 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002211 if (info->getActiveClientCount() == 1 &&
2212 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2213 // If it is first bit-perfect client, reroute all clients that will be routed to
2214 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2215 PortHandleVector clientsToInvalidate;
2216 for (size_t i = 0; i < mOutputs.size(); i++) {
2217 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002218 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002219 continue;
2220 }
2221 for (const auto& c : mOutputs[i]->getClientIterable()) {
2222 clientsToInvalidate.push_back(c->portId());
2223 }
2224 }
2225 if (!clientsToInvalidate.empty()) {
2226 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2227 __func__);
2228 mpClientInterface->invalidateTracks(clientsToInvalidate);
2229 }
2230 }
jiabina84c3d32022-12-02 18:59:55 +00002231 }
2232 }
2233
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002234 if (client->hasPreferredDevice()) {
2235 // playback activity with preferred device impacts routing occurred, inform upper layers
2236 mpClientInterface->onRoutingUpdated();
2237 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002238 if (delayMs != 0) {
2239 usleep(delayMs * 1000);
2240 }
2241
2242 return status;
2243}
2244
Eric Laurent96d1dda2022-03-14 17:14:19 +01002245bool AudioPolicyManager::isLeUnicastActive() const {
2246 if (isInCall()) {
2247 return true;
2248 }
2249 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2250}
2251
2252bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2253 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2254 return false;
2255 }
2256 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2257 ALOGV("%s active %d", __func__, active);
2258 return active;
2259}
2260
Eric Laurent97ac8712018-07-27 18:59:02 -07002261status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2262 const sp<TrackClientDescriptor>& client,
2263 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002264{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002265 // cannot start playback of STREAM_TTS if any other output is being used
2266 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002267
2268 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002269 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002270 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002271 auto clientStrategy = client->strategy();
2272 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002273 if (stream == AUDIO_STREAM_TTS) {
2274 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002275 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002276 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002277 return INVALID_OPERATION;
2278 } else {
2279 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2280 }
2281 } else {
2282 // some playback other than beacon starts
2283 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2284 }
2285
Eric Laurent77305a62016-07-25 16:39:22 -07002286 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002287 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002288 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002289
François Gaffie11d30102018-11-02 16:09:09 +01002290 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002291 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002292 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002293 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002294 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002295 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002296 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002297 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002298 } else {
2299 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002300 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002301 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2302 AUDIO_FORMAT_DEFAULT);
2303 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2304 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002305 }
2306
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002307 // requiresMuteCheck is false when we can bypass mute strategy.
2308 // It covers a common case when there is no materially active audio
2309 // and muting would result in unnecessary delay and dropped audio.
2310 const uint32_t outputLatencyMs = outputDesc->latency();
2311 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002312 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002313
Eric Laurente552edb2014-03-10 17:42:56 -07002314 // increment usage count for this stream on the requested output:
2315 // NOTE that the usage count is the same for duplicated output and hardware output which is
2316 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002317 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002318
2319 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002320 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002321 // Preferred device may be exclusive, use only if no other active clients on this output
2322 devices = DeviceVector(
2323 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2324 } else {
2325 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2326 }
François Gaffie11d30102018-11-02 16:09:09 +01002327 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002328 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002329 }
2330 }
Eric Laurente552edb2014-03-10 17:42:56 -07002331
François Gaffiec005e562018-11-06 15:04:49 +01002332 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002333 selectOutputForMusicEffects();
2334 }
2335
François Gaffie1c878552018-11-22 16:53:21 +01002336 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002337 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002338 if (devices.isEmpty()) {
2339 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002340 }
François Gaffiec005e562018-11-06 15:04:49 +01002341 bool shouldWait =
2342 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2343 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2344 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002345 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002346 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002347 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002348 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002349 // An output has a shared device if
2350 // - managed by the same hw module
2351 // - supports the currently selected device
2352 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002353 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002354
Eric Laurent77305a62016-07-25 16:39:22 -07002355 // force a device change if any other output is:
2356 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002357 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002358 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002359 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002360 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002361 // change the device currently selected by the other output.
2362 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002363 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002364 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002365 force = true;
2366 }
2367 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002368 // a notification so that audio focus effect can propagate, or that a mute/unmute
2369 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002370 const uint32_t latencyMs = desc->latency();
2371 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2372
2373 if (shouldWait && isActive && (waitMs < latencyMs)) {
2374 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002375 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002376
2377 // Require mute check if another output is on a shared device
2378 // and currently active to have proper drain and avoid pops.
2379 // Note restoring AudioTracks onto this output needs to invoke
2380 // a volume ramp if there is no mute.
2381 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002382 }
2383 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002384
jiabin3ff8d7d2022-12-13 06:27:44 +00002385 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2386 // If the output is open with preferred mixer attributes, but the routed device is
2387 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2388 // changed.
2389 return DEAD_OBJECT;
2390 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002391 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302392 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2393 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002394
Eric Laurente552edb2014-03-10 17:42:56 -07002395 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002396 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002397 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002398 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002399 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002400 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002401 outputDesc->useHwGain() /*force*/)) {
2402 // request AudioService to reinitialize the volume curves asynchronously
2403 ALOGE("checkAndSetVolume failed, requesting volume range init");
2404 mpClientInterface->onVolumeRangeInitRequest();
2405 };
Eric Laurente552edb2014-03-10 17:42:56 -07002406
2407 // update the outputs if starting an output with a stream that can affect notification
2408 // routing
2409 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002410
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002411 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002412 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002413 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002414 }
Eric Laurentdc462862016-07-19 12:29:53 -07002415
2416 if (waitMs > muteWaitMs) {
2417 *delayMs = waitMs - muteWaitMs;
2418 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002419
2420 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2421 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2422 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2423 // change occurs after the MixerThread starts and causes a stream volume
2424 // glitch.
2425 //
2426 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002427 }
Eric Laurentdc462862016-07-19 12:29:53 -07002428
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002429 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002430 mEngine->getForceUse(
2431 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002432 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002433 }
2434
Eric Laurent97ac8712018-07-27 18:59:02 -07002435 // Automatically enable the remote submix input when output is started on a re routing mix
2436 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002437 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2438 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002439 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2440 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2441 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002442 "remote-submix",
2443 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002444 }
2445
Eric Laurent96d1dda2022-03-14 17:14:19 +01002446 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2447
Eric Laurente552edb2014-03-10 17:42:56 -07002448 return NO_ERROR;
2449}
2450
Eric Laurent96d1dda2022-03-14 17:14:19 +01002451void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2452 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2453 bool isUnicastActive = isLeUnicastActive();
2454
2455 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002456 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002457 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2458 for (size_t i = 0; i < mOutputs.size(); i++) {
2459 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2460 if (desc != ignoredOutput && desc->isActive()
2461 && ((isUnicastActive &&
2462 !desc->devices().
2463 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2464 || (wasUnicastActive &&
2465 !desc->devices().getDevicesFromTypes(
2466 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2467 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2468 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002469 if (desc->mUsePreferredMixerAttributes && force) {
2470 // If the device is using preferred mixer attributes, the output need to reopen
2471 // with default configuration when the new selected devices are different from
2472 // current routing devices.
2473 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2474 continue;
2475 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302476 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002477 // re-apply device specific volume if not done by setOutputDevice()
2478 if (!force) {
2479 applyStreamVolumes(desc, newDevices.types(), delayMs);
2480 }
2481 }
2482 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002483 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002484 }
2485}
2486
Eric Laurent8fc147b2018-07-22 19:13:55 -07002487status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002488{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002489 ALOGV("%s portId %d", __FUNCTION__, portId);
2490
2491 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2492 if (outputDesc == 0) {
2493 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002494 return BAD_VALUE;
2495 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002496 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002497
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002498 if (client->hasPreferredDevice(true)) {
2499 // playback activity with preferred device impacts routing occurred, inform upper layers
2500 mpClientInterface->onRoutingUpdated();
2501 }
2502
Eric Laurent97ac8712018-07-27 18:59:02 -07002503 ALOGV("stopOutput() output %d, stream %d, session %d",
2504 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002505
Eric Laurent97ac8712018-07-27 18:59:02 -07002506 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002507
Eric Laurent733ce942017-12-07 12:18:25 -08002508 if (status == NO_ERROR ) {
2509 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002510 } else {
2511 return status;
2512 }
2513
2514 if (outputDesc->devices().size() == 1) {
2515 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2516 outputDesc->devices()[0]->getId(), client->strategy());
2517 if (info != nullptr && info->getUid() == client->uid()) {
2518 info->decreaseActiveClient();
2519 if (info->getActiveClientCount() == 0) {
2520 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2521 }
2522 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002523 }
2524 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002525}
2526
Eric Laurent97ac8712018-07-27 18:59:02 -07002527status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2528 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002529{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002530 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002531 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002532 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002533 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002534
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002535 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2536
François Gaffie1c878552018-11-22 16:53:21 +01002537 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2538 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002539 // Automatically disable the remote submix input when output is stopped on a
2540 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002541 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002542 if (isSingleDeviceType(
2543 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002544 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002545 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002546 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2547 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002548 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002549 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002550 }
2551 }
2552 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002553 if (client->hasPreferredDevice(true) &&
2554 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002555 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002556 forceDeviceUpdate = true;
2557 }
2558
Eric Laurente552edb2014-03-10 17:42:56 -07002559 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002560 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002561
Eric Laurente552edb2014-03-10 17:42:56 -07002562 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002563 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002564 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002565 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002566
2567 // If the routing does not change, if an output is routed on a device using HwGain
2568 // (aka setAudioPortConfig) and there are still active clients following different
2569 // volume group(s), force reapply volume
2570 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2571 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2572
Eric Laurente552edb2014-03-10 17:42:56 -07002573 // delay the device switch by twice the latency because stopOutput() is executed when
2574 // the track stop() command is received and at that time the audio track buffer can
2575 // still contain data that needs to be drained. The latency only covers the audio HAL
2576 // and kernel buffers. Also the latency does not always include additional delay in the
2577 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302578 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002579 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002580
2581 // force restoring the device selection on other active outputs if it differs from the
2582 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002583 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002584 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002585 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002586 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002587 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002588 desc->isActive() &&
2589 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002590 (newDevices != desc->devices())) {
2591 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2592 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002593
jiabin3ff8d7d2022-12-13 06:27:44 +00002594 if (desc->mUsePreferredMixerAttributes && force) {
2595 // If the device is using preferred mixer attributes, the output need to
2596 // reopen with default configuration when the new selected devices are
2597 // different from current routing devices.
2598 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2599 continue;
2600 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302601 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002602
Eric Laurent57de36c2016-09-28 16:59:11 -07002603 // re-apply device specific volume if not done by setOutputDevice()
2604 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002605 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002606 }
Eric Laurente552edb2014-03-10 17:42:56 -07002607 }
2608 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002609 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002610 // update the outputs if stopping one with a stream that can affect notification routing
2611 handleNotificationRoutingForStream(stream);
2612 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002613
2614 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2615 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002616 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002617 }
2618
François Gaffiec005e562018-11-06 15:04:49 +01002619 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002620 selectOutputForMusicEffects();
2621 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002622
2623 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2624
Eric Laurente552edb2014-03-10 17:42:56 -07002625 return NO_ERROR;
2626 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002627 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002628 return INVALID_OPERATION;
2629 }
2630}
2631
jiabinbce0c1d2020-10-05 11:20:18 -07002632bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002633{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002634 ALOGV("%s portId %d", __FUNCTION__, portId);
2635
2636 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2637 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002638 // If an output descriptor is closed due to a device routing change,
2639 // then there are race conditions with releaseOutput from tracks
2640 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2641 // destroyed shortly thereafter.
2642 //
2643 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002644 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002645 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002646 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002647
2648 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002649
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302650 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2651 if (outputDesc->isClientActive(client)) {
2652 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2653 stopOutput(portId);
2654 }
2655
Eric Laurent8fc147b2018-07-22 19:13:55 -07002656 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2657 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002658 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002659 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002660 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002661 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002662 if (--outputDesc->mDirectOpenCount == 0) {
2663 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002664 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002665 }
2666 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302667
Andy Hung39efb7a2018-09-26 15:39:28 -07002668 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002669 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2670 // The output is pending reopened to query dynamic profiles and
2671 // there is no active clients
2672 closeOutput(outputDesc->mIoHandle);
2673 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2674 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2675 if (newOutputDesc == nullptr) {
2676 ALOGE("%s failed to open output", __func__);
2677 }
2678 return true;
2679 }
2680 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002681}
2682
Eric Laurentcaf7f482014-11-25 17:50:47 -08002683status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2684 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002685 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002686 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002687 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002688 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002689 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002690 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002691 input_type_t *inputType,
2692 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002693{
François Gaffiec005e562018-11-06 15:04:49 +01002694 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002695 "flags %#x attributes=%s requested device ID %d",
2696 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2697 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002698
Eric Laurentad2e7b92017-09-14 20:06:42 -07002699 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002700 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002701 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002702 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002703 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002704 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002705 sp<RecordClientDescriptor> clientDesc;
2706 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002707 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002708 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002709
2710 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2711 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2712 return INVALID_OPERATION;
2713 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002714
Francois Gaffie716e1432019-01-14 16:58:59 +01002715 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2716 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002717 }
2718
Paul McLean466dc8e2015-04-17 13:15:36 -06002719 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002720 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002721 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002722
Eric Laurentad2e7b92017-09-14 20:06:42 -07002723 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2724 // possible
2725 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2726 *input != AUDIO_IO_HANDLE_NONE) {
2727 ssize_t index = mInputs.indexOfKey(*input);
2728 if (index < 0) {
2729 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2730 status = BAD_VALUE;
2731 goto error;
2732 }
2733 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002734 RecordClientVector clients = inputDesc->getClientsForSession(session);
2735 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002736 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2737 status = BAD_VALUE;
2738 goto error;
2739 }
2740 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2741 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002742 // corresponds to a new client and is only permitted from the same UID.
2743 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002744 if (clients.size() > 1) {
2745 for (const auto& client : clients) {
2746 // The client map is ordered by key values (portId) and portIds are allocated
2747 // incrementaly. So the first client in this list is the one opened by audio flinger
2748 // when the mmap stream is created and should be ignored as it does not correspond
2749 // to an actual client
2750 if (client == *clients.cbegin()) {
2751 continue;
2752 }
2753 if (uid != client->uid() && !client->isSilenced()) {
2754 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2755 uid, client->portId(), client->uid());
2756 status = INVALID_OPERATION;
2757 goto error;
2758 }
Eric Laurent331679c2018-04-16 17:03:16 -07002759 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002760 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002761 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002762 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002763
Eric Laurentfecbceb2021-02-09 14:46:43 +01002764 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002765 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002766 }
2767
2768 *input = AUDIO_IO_HANDLE_NONE;
2769 *inputType = API_INPUT_INVALID;
2770
Francois Gaffie716e1432019-01-14 16:58:59 +01002771 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002772 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002773 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002774 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002775 ALOGW("%s could not find input mix for attr %s",
2776 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002777 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002778 }
jiabinc1de2df2019-05-07 14:26:40 -07002779 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2780 String8(attr->tags + strlen("addr=")),
2781 AUDIO_FORMAT_DEFAULT);
2782 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002783 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002784 __func__, attributes.source, attributes.tags);
2785 status = BAD_VALUE;
2786 goto error;
2787 }
2788
Kevin Rocard25f9b052019-02-27 15:08:54 -08002789 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2790 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2791 } else {
2792 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2793 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002794 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002795 if (explicitRoutingDevice != nullptr) {
2796 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002797 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002798 // Prevent from storing invalid requested device id in clients
2799 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002800 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002801 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2802 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002803 }
François Gaffie11d30102018-11-02 16:09:09 +01002804 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002805 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002806 status = BAD_VALUE;
2807 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002808 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002809 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2810 *inputType = API_INPUT_MIX_CAPTURE;
2811 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002812 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2813 // there is an external policy, but this input is attached to a mix of recorders,
2814 // meaning it receives audio injected into the framework, so the recorder doesn't
2815 // know about it and is therefore considered "legacy"
2816 *inputType = API_INPUT_LEGACY;
2817 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002818 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002819 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002820 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002821 } else {
2822 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002823 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002824
Eric Laurent599c7582015-12-07 18:05:55 -08002825 }
2826
François Gaffiec005e562018-11-06 15:04:49 +01002827 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002828 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002829 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002830 AudioProfileVector profiles;
2831 status_t ret = getProfilesForDevices(
2832 DeviceVector(device), profiles, flags, true /*isInput*/);
2833 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002834 const auto channels = profiles[0]->getChannels();
2835 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2836 config->channel_mask = *channels.begin();
2837 }
2838 const auto sampleRates = profiles[0]->getSampleRates();
2839 if (!sampleRates.empty() &&
2840 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2841 config->sample_rate = *sampleRates.begin();
2842 }
jiabinf1c73972022-04-14 16:28:52 -07002843 config->format = profiles[0]->getFormat();
2844 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002845 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002846 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002847
Eric Laurent8f42ea12018-08-08 09:08:25 -07002848exit:
2849
François Gaffiec005e562018-11-06 15:04:49 +01002850 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2851 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002852
Francois Gaffie716e1432019-01-14 16:58:59 +01002853 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002854 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002855 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002856
Mikhail Naganov2996f672019-04-18 12:29:59 -07002857 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002858 requestedDeviceId, attributes.source, flags,
2859 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002860 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002861 // Move (if found) effect for the client session to its input
2862 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002863 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002864
2865 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2866 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002867
Eric Laurent599c7582015-12-07 18:05:55 -08002868 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002869
2870error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002871 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002872}
2873
2874
François Gaffie11d30102018-11-02 16:09:09 +01002875audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002876 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002877 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002878 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002879 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002880 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002881{
2882 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002883 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002884 bool isSoundTrigger = false;
2885
François Gaffiec005e562018-11-06 15:04:49 +01002886 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002887 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2888 if (index >= 0) {
2889 input = mSoundTriggerSessions.valueFor(session);
2890 isSoundTrigger = true;
2891 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2892 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2893 } else {
2894 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002895 }
François Gaffiec005e562018-11-06 15:04:49 +01002896 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002897 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002898 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002899 }
2900
Carter Hsua3abb402021-10-26 11:11:20 +08002901 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2902 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2903 }
2904
Eric Laurentfe231122017-11-17 17:48:06 -08002905 // sampling rate and flags may be updated by getInputProfile
2906 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2907 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002908 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002909 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002910 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002911 // find a compatible input profile (not necessarily identical in parameters)
2912 sp<IOProfile> profile = getInputProfile(
2913 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2914 if (profile == nullptr) {
2915 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002916 }
jiabin2fd710d2022-05-02 23:20:22 +00002917
Glenn Kasten05ddca52016-02-11 08:17:12 -08002918 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002919 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002920 if (samplingRate == 0) {
2921 samplingRate = profileSamplingRate;
2922 }
Eric Laurente552edb2014-03-10 17:42:56 -07002923
Eric Laurent322b4d22015-04-03 15:57:54 -07002924 if (profile->getModuleHandle() == 0) {
2925 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002926 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002927 }
2928
Eric Laurentec376dc2021-04-08 20:41:22 +02002929 // Reuse an already opened input if a client with the same session ID already exists
2930 // on that input
2931 for (size_t i = 0; i < mInputs.size(); i++) {
2932 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2933 if (desc->mProfile != profile) {
2934 continue;
2935 }
2936 RecordClientVector clients = desc->clientsList();
2937 for (const auto &client : clients) {
2938 if (session == client->session()) {
2939 return desc->mIoHandle;
2940 }
2941 }
2942 }
2943
Eric Laurent3974e3b2017-12-07 17:58:43 -08002944 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002945 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002946 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002947 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002948 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002949 continue;
2950 }
2951 // if sound trigger, reuse input if used by other sound trigger on same session
2952 // else
2953 // reuse input if active client app is not in IDLE state
2954 //
2955 RecordClientVector clients = desc->clientsList();
2956 bool doClose = false;
2957 for (const auto& client : clients) {
2958 if (isSoundTrigger != client->isSoundTrigger()) {
2959 continue;
2960 }
2961 if (client->isSoundTrigger()) {
2962 if (session == client->session()) {
2963 return desc->mIoHandle;
2964 }
2965 continue;
2966 }
2967 if (client->active() && client->appState() != APP_STATE_IDLE) {
2968 return desc->mIoHandle;
2969 }
2970 doClose = true;
2971 }
2972 if (doClose) {
2973 closeInput(desc->mIoHandle);
2974 } else {
2975 i++;
2976 }
2977 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002978 }
2979
Eric Laurentfe231122017-11-17 17:48:06 -08002980 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002981
Eric Laurentfe231122017-11-17 17:48:06 -08002982 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2983 lConfig.sample_rate = profileSamplingRate;
2984 lConfig.channel_mask = profileChannelMask;
2985 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002986
François Gaffie11d30102018-11-02 16:09:09 +01002987 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002988
2989 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002990 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002991 (profileSamplingRate != lConfig.sample_rate) ||
2992 !audio_formats_match(profileFormat, lConfig.format) ||
2993 (profileChannelMask != lConfig.channel_mask)) {
2994 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002995 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002996 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002997 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002998 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002999 }
Eric Laurent599c7582015-12-07 18:05:55 -08003000 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07003001 }
3002
Eric Laurentc722f302014-12-10 11:21:49 -08003003 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003004
Eric Laurent599c7582015-12-07 18:05:55 -08003005 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003006 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003007
Eric Laurent599c7582015-12-07 18:05:55 -08003008 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003009}
3010
Eric Laurent4eb58f12018-12-07 16:41:02 -08003011status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003012{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003013 ALOGV("%s portId %d", __FUNCTION__, portId);
3014
3015 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3016 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003017 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003018 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003019 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003020 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003021 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003022 if (client->active()) {
3023 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3024 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003025 }
3026
Eric Laurent8f42ea12018-08-08 09:08:25 -07003027 audio_session_t session = client->session();
3028
Eric Laurent4eb58f12018-12-07 16:41:02 -08003029 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003030
Eric Laurent4eb58f12018-12-07 16:41:02 -08003031 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003032
Eric Laurent4eb58f12018-12-07 16:41:02 -08003033 status_t status = inputDesc->start();
3034 if (status != NO_ERROR) {
3035 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003036 }
Eric Laurente552edb2014-03-10 17:42:56 -07003037
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003038 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003039 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003040 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003041
Eric Laurent8f42ea12018-08-08 09:08:25 -07003042 // indicate active capture to sound trigger service if starting capture from a mic on
3043 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003044 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003045 if (device != nullptr) {
3046 status = setInputDevice(input, device, true /* force */);
3047 } else {
3048 ALOGW("%s no new input device can be found for descriptor %d",
3049 __FUNCTION__, inputDesc->getId());
3050 status = BAD_VALUE;
3051 }
Eric Laurente552edb2014-03-10 17:42:56 -07003052
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003053 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003054 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003055 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003056 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003057 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3058 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003059 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003060 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003061
François Gaffie11d30102018-11-02 16:09:09 +01003062 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3063 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003064 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003065 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003066 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003067
Eric Laurent8f42ea12018-08-08 09:08:25 -07003068 // automatically enable the remote submix output when input is started if not
3069 // used by a policy mix of type MIX_TYPE_RECORDERS
3070 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003071 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003072 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003073 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003074 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003075 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3076 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003077 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003078 if (address != "") {
3079 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3080 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003081 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003082 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003083 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003084 } else if (status != NO_ERROR) {
3085 // Restore client activity state.
3086 inputDesc->setClientActive(client, false);
3087 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003088 }
3089
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003090 ALOGV("%s input %d source = %d status = %d exit",
3091 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003092
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003093 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003094}
3095
Eric Laurent8fc147b2018-07-22 19:13:55 -07003096status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003097{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003098 ALOGV("%s portId %d", __FUNCTION__, portId);
3099
3100 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3101 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003102 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003103 return BAD_VALUE;
3104 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003105 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003106 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003107 if (!client->active()) {
3108 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003109 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003110 }
Carter Hsue6139d52021-07-08 10:30:20 +08003111 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003112 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003113
Eric Laurent8f42ea12018-08-08 09:08:25 -07003114 inputDesc->stop();
3115 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003116 auto current_source = inputDesc->source();
3117 setInputDevice(input, getNewInputDevice(inputDesc),
3118 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003119 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003120 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003121 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003122 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003123 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3124 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003125 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003126 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003127
3128 // automatically disable the remote submix output when input is stopped if not
3129 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003130 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003131 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003132 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003133 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003134 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3135 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003136 }
3137 if (address != "") {
3138 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3139 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003140 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003141 }
3142 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003143 resetInputDevice(input);
3144
3145 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3146 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003147 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3148 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003149 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003150 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003151 }
3152 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003153 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003154 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003155}
3156
Eric Laurent8fc147b2018-07-22 19:13:55 -07003157void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003158{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003159 ALOGV("%s portId %d", __FUNCTION__, portId);
3160
3161 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3162 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003163 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003164 return;
3165 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003166 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003167 audio_io_handle_t input = inputDesc->mIoHandle;
3168
Eric Laurent8f42ea12018-08-08 09:08:25 -07003169 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003170
Andy Hung39efb7a2018-09-26 15:39:28 -07003171 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003172 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003173 if (inputDesc->getClientCount() > 0) {
3174 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003175 return;
3176 }
3177
Eric Laurent05b90f82014-08-27 15:32:29 -07003178 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003179 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003180 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003181}
3182
Eric Laurent8f42ea12018-08-08 09:08:25 -07003183void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003184{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003185 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003186
3187 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003188 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003189 }
3190}
3191
Eric Laurent8f42ea12018-08-08 09:08:25 -07003192void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3193{
3194 stopInput(portId);
3195 releaseInput(portId);
3196}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003197
Eric Laurent0dd51852019-04-19 18:18:58 -07003198void AudioPolicyManager::checkCloseInputs() {
3199 // After connecting or disconnecting an input device, close input if:
3200 // - it has no client (was just opened to check profile) OR
3201 // - none of its supported devices are connected anymore OR
3202 // - one of its clients cannot be routed to one of its supported
3203 // devices anymore. Otherwise update device selection
3204 std::vector<audio_io_handle_t> inputsToClose;
3205 for (size_t i = 0; i < mInputs.size(); i++) {
3206 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3207 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003208 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003209 inputsToClose.push_back(mInputs.keyAt(i));
3210 } else {
3211 bool close = false;
3212 for (const auto& client : input->clientsList()) {
3213 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003214 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3215 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003216 if (!input->supportedDevices().contains(device)) {
3217 close = true;
3218 break;
3219 }
3220 }
3221 if (close) {
3222 inputsToClose.push_back(mInputs.keyAt(i));
3223 } else {
3224 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3225 }
3226 }
3227 }
3228
3229 for (const audio_io_handle_t handle : inputsToClose) {
3230 ALOGV("%s closing input %d", __func__, handle);
3231 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003232 }
Eric Laurentd4692962014-05-05 18:13:44 -07003233}
3234
François Gaffie251c7f02018-11-07 10:41:08 +01003235void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003236{
3237 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003238 if (indexMin < 0 || indexMax < 0) {
3239 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3240 return;
3241 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003242 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003243
3244 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003245 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3246 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003247 continue;
3248 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003249 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003250 }
Eric Laurente552edb2014-03-10 17:42:56 -07003251}
3252
Eric Laurente0720872014-03-11 09:30:41 -07003253status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003254 int index,
3255 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003256{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003257 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003258 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3259 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3260 return NO_ERROR;
3261 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003262 ALOGV("%s: stream %s attributes=%s", __func__,
3263 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003264 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003265}
3266
Eric Laurente0720872014-03-11 09:30:41 -07003267status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003268 int *index,
3269 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003270{
François Gaffiec005e562018-11-06 15:04:49 +01003271 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3272 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003273 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003274 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003275 deviceTypes = mEngine->getOutputDevicesForStream(
3276 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003277 }
jiabin9a3361e2019-10-01 09:38:30 -07003278 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003279}
3280
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003281status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003282 int index,
3283 audio_devices_t device)
3284{
3285 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003286 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3287 if (group == VOLUME_GROUP_NONE) {
3288 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003289 return BAD_VALUE;
3290 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003291 ALOGV("%s: group %d matching with %s index %d",
3292 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003293 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003294 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003295 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003296 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3297 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3298 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3299 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003300 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3301
3302 status = setVolumeCurveIndex(index, device, curves);
3303 if (status != NO_ERROR) {
3304 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3305 return status;
3306 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003307
jiabin9a3361e2019-10-01 09:38:30 -07003308 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003309 auto curCurvAttrs = curves.getAttributes();
3310 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3311 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003312 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003313 } else if (!curves.getStreamTypes().empty()) {
3314 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003315 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003316 } else {
3317 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3318 return BAD_VALUE;
3319 }
jiabin9a3361e2019-10-01 09:38:30 -07003320 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3321 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003322
François Gaffiecfe17322018-11-07 13:41:29 +01003323 // update volume on all outputs and streams matching the following:
3324 // - The requested stream (or a stream matching for volume control) is active on the output
3325 // - The device (or devices) selected by the engine for this stream includes
3326 // the requested device
3327 // - For non default requested device, currently selected device on the output is either the
3328 // requested device or one of the devices selected by the engine for this stream
3329 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3330 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003331 for (size_t i = 0; i < mOutputs.size(); i++) {
3332 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003333 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003334
jiabin9a3361e2019-10-01 09:38:30 -07003335 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3336 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003337 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003338
3339 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003340 continue;
3341 }
3342 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3343 curDevices.find(device) == curDevices.end()) {
3344 continue;
3345 }
3346 bool applyVolume = false;
3347 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3348 curSrcDevices.insert(device);
3349 applyVolume = (curSrcDevices.find(
3350 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3351 } else {
3352 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3353 }
3354 if (!applyVolume) {
3355 continue; // next output
3356 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003357 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3358 // If a higher priority strategy is active, and the output is routed to a device with a
3359 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003360 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003361 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003362 // If the volume source is active with higher priority source, ensure at least Sw Muted
3363 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003364 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3365 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3366 false /*preferredDevice*/);
3367 if (activeClients.empty()) {
3368 continue;
3369 }
3370 bool isPreempted = false;
3371 bool isHigherPriority = productStrategy < strategy;
3372 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003373 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003374 ALOGV("%s: Strategy=%d (\nrequester:\n"
3375 " group %d, volumeGroup=%d attributes=%s)\n"
3376 " higher priority source active:\n"
3377 " volumeGroup=%d attributes=%s) \n"
3378 " on output %zu, bailing out", __func__, productStrategy,
3379 group, group, toString(attributes).c_str(),
3380 client->volumeSource(), toString(client->attributes()).c_str(), i);
3381 applyVolume = false;
3382 isPreempted = true;
3383 break;
3384 }
3385 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003386 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003387 applyVolume = true;
3388 }
3389 }
3390 if (isPreempted || applyVolume) {
3391 break;
3392 }
3393 }
3394 if (!applyVolume) {
3395 continue; // next output
3396 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003397 }
François Gaffieed91f582020-01-31 10:35:37 +01003398 //FIXME: workaround for truncated touch sounds
3399 // delayed volume change for system stream to be removed when the problem is
3400 // handled by system UI
3401 status_t volStatus = checkAndSetVolume(
3402 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003403 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003404 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3405 if (volStatus != NO_ERROR) {
3406 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003407 }
3408 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003409
3410 // update voice volume if the an active call route exists
3411 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3412 && (curSrcDevices.find(
3413 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3414 != curSrcDevices.end())) {
3415 bool isVoiceVolSrc;
3416 bool isBtScoVolSrc;
3417 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3418 isVoiceVolSrc, isBtScoVolSrc, __func__)
3419 && (isVoiceVolSrc || isBtScoVolSrc)) {
3420 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3421 }
3422 }
3423
François Gaffiecfe17322018-11-07 13:41:29 +01003424 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3425 return status;
3426}
3427
François Gaffieaaac0fd2018-11-22 17:56:39 +01003428status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003429 audio_devices_t device,
3430 IVolumeCurves &volumeCurves)
3431{
3432 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3433 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003434 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3435 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003436 (index > volumeCurves.getVolumeIndexMax())) {
3437 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3438 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3439 return BAD_VALUE;
3440 }
3441 if (!audio_is_output_device(device)) {
3442 return BAD_VALUE;
3443 }
3444
3445 // Force max volume if stream cannot be muted
3446 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3447
François Gaffieaaac0fd2018-11-22 17:56:39 +01003448 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003449 volumeCurves.addCurrentVolumeIndex(device, index);
3450 return NO_ERROR;
3451}
3452
3453status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3454 int &index,
3455 audio_devices_t device)
3456{
3457 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3458 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003459 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003460 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003461 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003462 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003463 }
jiabin9a3361e2019-10-01 09:38:30 -07003464 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003465}
3466
3467status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3468 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003469 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003470{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003471 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003472 return BAD_VALUE;
3473 }
jiabin9a3361e2019-10-01 09:38:30 -07003474 index = curves.getVolumeIndex(deviceTypes);
3475 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003476 return NO_ERROR;
3477}
3478
3479status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3480 int &index)
3481{
3482 index = getVolumeCurves(attr).getVolumeIndexMin();
3483 return NO_ERROR;
3484}
3485
3486status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3487 int &index)
3488{
3489 index = getVolumeCurves(attr).getVolumeIndexMax();
3490 return NO_ERROR;
3491}
3492
Eric Laurent36829f92017-04-07 19:04:42 -07003493audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003494{
3495 // select one output among several suitable for global effects.
3496 // The priority is as follows:
3497 // 1: An offloaded output. If the effect ends up not being offloadable,
3498 // AudioFlinger will invalidate the track and the offloaded output
3499 // will be closed causing the effect to be moved to a PCM output.
3500 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003501 // 3: The primary output
3502 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003503
François Gaffiec005e562018-11-06 15:04:49 +01003504 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3505 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003506 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003507
Eric Laurent36829f92017-04-07 19:04:42 -07003508 if (outputs.size() == 0) {
3509 return AUDIO_IO_HANDLE_NONE;
3510 }
Eric Laurente552edb2014-03-10 17:42:56 -07003511
Eric Laurent36829f92017-04-07 19:04:42 -07003512 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3513 bool activeOnly = true;
3514
3515 while (output == AUDIO_IO_HANDLE_NONE) {
3516 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3517 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3518 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3519
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003520 for (audio_io_handle_t output : outputs) {
3521 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003522 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003523 continue;
3524 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003525 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3526 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003527 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003528 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003529 }
3530 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003531 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003532 }
3533 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003534 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003535 }
3536 }
3537 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3538 output = outputOffloaded;
3539 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3540 output = outputDeepBuffer;
3541 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3542 output = outputPrimary;
3543 } else {
3544 output = outputs[0];
3545 }
3546 activeOnly = false;
3547 }
3548
3549 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003550 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3551 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003552 mMusicEffectOutput = output;
3553 }
3554
3555 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003556 return output;
3557}
3558
Eric Laurent36829f92017-04-07 19:04:42 -07003559audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3560{
3561 return selectOutputForMusicEffects();
3562}
3563
Eric Laurente0720872014-03-11 09:30:41 -07003564status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003565 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003566 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003567 int session,
3568 int id)
3569{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003570 if (session != AUDIO_SESSION_DEVICE) {
3571 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003572 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003573 index = mInputs.indexOfKey(io);
3574 if (index < 0) {
3575 ALOGW("registerEffect() unknown io %d", io);
3576 return INVALID_OPERATION;
3577 }
Eric Laurente552edb2014-03-10 17:42:56 -07003578 }
3579 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003580 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3581 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3582 || strategy == PRODUCT_STRATEGY_NONE));
3583 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003584}
3585
Eric Laurentc241b0d2018-11-28 09:08:49 -08003586status_t AudioPolicyManager::unregisterEffect(int id)
3587{
3588 if (mEffects.getEffect(id) == nullptr) {
3589 return INVALID_OPERATION;
3590 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003591 if (mEffects.isEffectEnabled(id)) {
3592 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3593 setEffectEnabled(id, false);
3594 }
3595 return mEffects.unregisterEffect(id);
3596}
3597
3598status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3599{
3600 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3601 if (effect == nullptr) {
3602 return INVALID_OPERATION;
3603 }
3604
3605 status_t status = mEffects.setEffectEnabled(id, enabled);
3606 if (status == NO_ERROR) {
3607 mInputs.trackEffectEnabled(effect, enabled);
3608 }
3609 return status;
3610}
3611
Eric Laurent6c796322019-04-09 14:13:17 -07003612
3613status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3614{
3615 mEffects.moveEffects(ids, io);
3616 return NO_ERROR;
3617}
3618
Eric Laurentc75307b2015-03-17 15:29:32 -07003619bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3620{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003621 auto vs = toVolumeSource(stream, false);
3622 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003623}
3624
3625bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3626{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003627 auto vs = toVolumeSource(stream, false);
3628 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003629}
3630
Eric Laurente0720872014-03-11 09:30:41 -07003631bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003632{
3633 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003634 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003635 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003636 return true;
3637 }
3638 }
3639 return false;
3640}
3641
Eric Laurent275e8e92014-11-30 15:14:47 -08003642// Register a list of custom mixes with their attributes and format.
3643// When a mix is registered, corresponding input and output profiles are
3644// added to the remote submix hw module. The profile contains only the
3645// parameters (sampling rate, format...) specified by the mix.
3646// The corresponding input remote submix device is also connected.
3647//
3648// When a remote submix device is connected, the address is checked to select the
3649// appropriate profile and the corresponding input or output stream is opened.
3650//
3651// When capture starts, getInputForAttr() will:
3652// - 1 look for a mix matching the address passed in attribtutes tags if any
3653// - 2 if none found, getDeviceForInputSource() will:
3654// - 2.1 look for a mix matching the attributes source
3655// - 2.2 if none found, default to device selection by policy rules
3656// At this time, the corresponding output remote submix device is also connected
3657// and active playback use cases can be transferred to this mix if needed when reconnecting
3658// after AudioTracks are invalidated
3659//
3660// When playback starts, getOutputForAttr() will:
3661// - 1 look for a mix matching the address passed in attribtutes tags if any
3662// - 2 if none found, look for a mix matching the attributes usage
3663// - 3 if none found, default to device and output selection by policy rules.
3664
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003665status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003666{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003667 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3668 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003669 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003670 sp<HwModule> rSubmixModule;
3671 // examine each mix's route type
3672 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003673 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003674 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3675 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3676 ALOGE("Unsupported Policy Mix %zu of %zu: "
3677 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3678 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003679 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003680 break;
3681 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003682 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3683 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003684 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003685 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3686 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003687 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003688 rSubmixModule = mHwModules.getModuleFromName(
3689 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3690 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003691 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003692 i);
3693 res = INVALID_OPERATION;
3694 break;
3695 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003696 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003697
Eric Laurent97ac8712018-07-27 18:59:02 -07003698 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003699 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003700 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003701 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003702 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3703 } else {
3704 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3705 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003706 }
François Gaffie036e1e92015-03-19 10:16:24 +01003707
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003708 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003709 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003710 res = INVALID_OPERATION;
3711 break;
3712 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003713 audio_config_t outputConfig = mix.mFormat;
3714 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003715 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3716 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003717 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3718 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003719 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003720 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3721 audio_is_linear_pcm(outputConfig.format)
3722 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003723 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003724 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3725 audio_is_linear_pcm(inputConfig.format)
3726 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003727
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003728 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003729 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003730 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003731 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003732 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003733 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003734 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003735 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3736 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003737 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003738 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003739 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003740
3741 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3742 mix.mDeviceType, mix.mDeviceAddress,
3743 String8(), AUDIO_FORMAT_DEFAULT);
3744 if (device == nullptr) {
3745 res = INVALID_OPERATION;
3746 break;
3747 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003748
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003749 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003750 // First try to find an already opened output supporting the device
3751 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003752 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003753
Eric Laurentc529cf62020-04-17 18:19:10 -07003754 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003755 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003756 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003757 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003758 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003759 } else {
3760 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003761 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003762 }
3763 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003764 // If no output found, try to find a direct output profile supporting the device
3765 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3766 sp<HwModule> module = mHwModules[i];
3767 for (size_t j = 0;
3768 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3769 j++) {
3770 sp<IOProfile> profile = module->getOutputProfiles()[j];
3771 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3772 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3773 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003774 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003775 res = INVALID_OPERATION;
3776 } else {
3777 foundOutput = true;
3778 }
3779 }
3780 }
3781 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003782 if (res != NO_ERROR) {
3783 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003784 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003785 res = INVALID_OPERATION;
3786 break;
3787 } else if (!foundOutput) {
3788 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003789 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003790 res = INVALID_OPERATION;
3791 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003792 } else {
3793 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003794 }
Eric Laurentc722f302014-12-10 11:21:49 -08003795 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003796 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003797 if (res != NO_ERROR) {
3798 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003799 } else if (checkOutputs) {
3800 checkForDeviceAndOutputChanges();
3801 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003802 }
3803 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003804}
3805
3806status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3807{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003808 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003809 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003810 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003811 sp<HwModule> rSubmixModule;
3812 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003813 for (const auto& mix : mixes) {
3814 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003815
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003816 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003817 rSubmixModule = mHwModules.getModuleFromName(
3818 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3819 if (rSubmixModule == 0) {
3820 res = INVALID_OPERATION;
3821 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003822 }
3823 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003824
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003825 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003826
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003827 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003828 res = INVALID_OPERATION;
3829 continue;
3830 }
3831
Kevin Rocard04ed0462019-05-02 17:53:24 -07003832 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003833 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003834 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3835 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003836 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003837 AUDIO_FORMAT_DEFAULT);
3838 if (res != OK) {
3839 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003840 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003841 }
3842 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003843 }
jiabin5740f082019-08-19 15:08:30 -07003844 rSubmixModule->removeOutputProfile(address.c_str());
3845 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003846
Kevin Rocard153f92d2018-12-18 18:33:28 -08003847 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003848 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003849 res = INVALID_OPERATION;
3850 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003851 } else {
3852 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003853 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003854 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003855 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003856 if (res == NO_ERROR && checkOutputs) {
3857 checkForDeviceAndOutputChanges();
3858 updateCallAndOutputRouting();
3859 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003860 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003861}
3862
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003863status_t AudioPolicyManager::updatePolicyMix(
3864 const AudioMix& mix,
3865 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3866 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3867 if (res == NO_ERROR) {
3868 checkForDeviceAndOutputChanges();
3869 updateCallAndOutputRouting();
3870 }
3871 return res;
3872}
3873
Mikhail Naganov100f0122018-11-29 11:22:16 -08003874void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3875{
3876 size_t i = 0;
3877 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3878 for (const auto& fmt : mManualSurroundFormats) {
3879 if (i++ != 0) dst->append(", ");
3880 std::string sfmt;
3881 FormatConverter::toString(fmt, sfmt);
3882 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3883 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3884 }
3885}
3886
Eric Laurentc529cf62020-04-17 18:19:10 -07003887// Returns true if all devices types match the predicate and are supported by one HW module
3888bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003889 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003890 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003891 const char *context,
3892 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003893 for (size_t i = 0; i < devices.size(); i++) {
3894 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003895 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003896 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003897 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003898 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003899 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003900 return false;
3901 }
3902 }
3903 return true;
3904}
3905
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003906void AudioPolicyManager::changeOutputDevicesMuteState(
3907 const AudioDeviceTypeAddrVector& devices) {
3908 ALOGVV("%s() num devices %zu", __func__, devices.size());
3909
3910 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3911 getSoftwareOutputsForDevices(devices);
3912
3913 for (size_t i = 0; i < outputs.size(); i++) {
3914 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3915 DeviceVector prevDevices = outputDesc->devices();
3916 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3917 }
3918}
3919
3920std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3921 const AudioDeviceTypeAddrVector& devices) const
3922{
3923 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3924 DeviceVector deviceDescriptors;
3925 for (size_t j = 0; j < devices.size(); j++) {
3926 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3927 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3928 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3929 ALOGE("%s: device type %#x address %s not supported or not an output device",
3930 __func__, devices[j].mType, devices[j].getAddress());
3931 continue;
3932 }
3933 deviceDescriptors.add(desc);
3934 }
3935 for (size_t i = 0; i < mOutputs.size(); i++) {
3936 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3937 continue;
3938 }
3939 outputs.push_back(mOutputs.valueAt(i));
3940 }
3941 return outputs;
3942}
3943
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003944status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003945 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003946 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003947 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3948 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003949 }
3950 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003951 if (res != NO_ERROR) {
3952 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3953 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003954 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003955
3956 checkForDeviceAndOutputChanges();
3957 updateCallAndOutputRouting();
3958
3959 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003960}
3961
3962status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3963 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003964 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3965 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003966 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003967 __FUNCTION__, uid);
3968 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003969 }
3970
Eric Laurentc529cf62020-04-17 18:19:10 -07003971 checkForDeviceAndOutputChanges();
3972 updateCallAndOutputRouting();
3973
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003974 return res;
3975}
3976
Eric Laurent2517af32020-11-25 15:31:27 +01003977
jiabin0a488932020-08-07 17:32:40 -07003978status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3979 device_role_t role,
3980 const AudioDeviceTypeAddrVector &devices) {
3981 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3982 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003983
Eric Laurentc529cf62020-04-17 18:19:10 -07003984 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003985 return BAD_VALUE;
3986 }
jiabin0a488932020-08-07 17:32:40 -07003987 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003988 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003989 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3990 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003991 return status;
3992 }
3993
3994 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003995
3996 bool forceVolumeReeval = false;
3997 // FIXME: workaround for truncated touch sounds
3998 // to be removed when the problem is handled by system UI
3999 uint32_t delayMs = 0;
4000 if (strategy == mCommunnicationStrategy) {
4001 forceVolumeReeval = true;
4002 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4003 updateInputRouting();
4004 }
4005 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004006
4007 return NO_ERROR;
4008}
4009
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004010void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4011 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004012{
4013 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004014 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004015 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004016 // Only apply special touch sound delay once
4017 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004018 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004019 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004020 for (size_t i = 0; i < mOutputs.size(); i++) {
4021 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4022 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004023 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4024 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004025 // As done in setDeviceConnectionState, we could also fix default device issue by
4026 // preventing the force re-routing in case of default dev that distinguishes on address.
4027 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004028 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004029 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4030 // If the device is using preferred mixer attributes, the output need to reopen
4031 // with default configuration when the new selected devices are different from
4032 // current routing devices.
4033 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4034 continue;
4035 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304036
4037 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4038 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004039 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004040 // Only apply special touch sound delay once
4041 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004042 }
4043 if (forceVolumeReeval && !newDevices.isEmpty()) {
4044 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4045 }
4046 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004047 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004048 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004049}
4050
Eric Laurent2517af32020-11-25 15:31:27 +01004051void AudioPolicyManager::updateInputRouting() {
4052 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304053 // Skip for hotword recording as the input device switch
4054 // is handled within sound trigger HAL
4055 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4056 continue;
4057 }
Eric Laurent2517af32020-11-25 15:31:27 +01004058 auto newDevice = getNewInputDevice(activeDesc);
4059 // Force new input selection if the new device can not be reached via current input
4060 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4061 setInputDevice(activeDesc->mIoHandle, newDevice);
4062 } else {
4063 closeInput(activeDesc->mIoHandle);
4064 }
4065 }
4066}
4067
Paul Wang5d7cdb52022-11-22 09:45:06 +00004068status_t
4069AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4070 device_role_t role,
4071 const AudioDeviceTypeAddrVector &devices) {
4072 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4073 dumpAudioDeviceTypeAddrVector(devices).c_str());
4074
Eric Laurent78fedbf2023-03-09 14:40:44 +01004075 if (!areAllDevicesSupported(
4076 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004077 return BAD_VALUE;
4078 }
4079 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4080 if (status != NO_ERROR) {
4081 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4082 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4083 return status;
4084 }
4085
4086 checkForDeviceAndOutputChanges();
4087
4088 bool forceVolumeReeval = false;
4089 // TODO(b/263479999): workaround for truncated touch sounds
4090 // to be removed when the problem is handled by system UI
4091 uint32_t delayMs = 0;
4092 if (strategy == mCommunnicationStrategy) {
4093 forceVolumeReeval = true;
4094 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4095 updateInputRouting();
4096 }
4097 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4098
4099 return NO_ERROR;
4100}
4101
4102status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4103 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004104{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004105 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004106
Paul Wang5d7cdb52022-11-22 09:45:06 +00004107 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004108 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004109 ALOGW_IF(status != NAME_NOT_FOUND,
4110 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004111 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004112 return status;
4113 }
4114
4115 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004116
4117 bool forceVolumeReeval = false;
4118 // FIXME: workaround for truncated touch sounds
4119 // to be removed when the problem is handled by system UI
4120 uint32_t delayMs = 0;
4121 if (strategy == mCommunnicationStrategy) {
4122 forceVolumeReeval = true;
4123 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4124 updateInputRouting();
4125 }
4126 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004127
4128 return NO_ERROR;
4129}
4130
jiabin0a488932020-08-07 17:32:40 -07004131status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4132 device_role_t role,
4133 AudioDeviceTypeAddrVector &devices) {
4134 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004135}
4136
Jiabin Huang3b98d322020-09-03 17:54:16 +00004137status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4138 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4139 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4140 dumpAudioDeviceTypeAddrVector(devices).c_str());
4141
Mikhail Naganov55773032020-10-01 15:08:13 -07004142 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004143 return BAD_VALUE;
4144 }
4145 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4146 ALOGW_IF(status != NO_ERROR,
4147 "Engine could not set preferred devices %s for audio source %d role %d",
4148 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4149
4150 return status;
4151}
4152
4153status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4154 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4155 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4156 dumpAudioDeviceTypeAddrVector(devices).c_str());
4157
Mikhail Naganov55773032020-10-01 15:08:13 -07004158 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004159 return BAD_VALUE;
4160 }
4161 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4162 ALOGW_IF(status != NO_ERROR,
4163 "Engine could not add preferred devices %s for audio source %d role %d",
4164 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4165
Eric Laurent2517af32020-11-25 15:31:27 +01004166 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004167 return status;
4168}
4169
4170status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4171 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4172{
4173 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4174 dumpAudioDeviceTypeAddrVector(devices).c_str());
4175
Eric Laurent78fedbf2023-03-09 14:40:44 +01004176 if (!areAllDevicesSupported(
4177 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004178 return BAD_VALUE;
4179 }
4180
4181 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4182 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004183 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004184 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004185 if (status == NO_ERROR) {
4186 updateInputRouting();
4187 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004188 return status;
4189}
4190
4191status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4192 device_role_t role) {
4193 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4194
4195 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004196 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004197 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004198 if (status == NO_ERROR) {
4199 updateInputRouting();
4200 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004201 return status;
4202}
4203
4204status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4205 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4206 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4207}
4208
Oscar Azucena90e77632019-11-27 17:12:28 -08004209status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004210 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004211 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004212 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4213 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004214 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004215 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4216 if (status != NO_ERROR) {
4217 ALOGE("%s() could not set device affinity for userId %d",
4218 __FUNCTION__, userId);
4219 return status;
4220 }
4221
4222 // reevaluate outputs for all devices
4223 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004224 changeOutputDevicesMuteState(devices);
4225 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4226 true /* skipDelays */);
4227 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004228
4229 return NO_ERROR;
4230}
4231
4232status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004233 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004234 AudioDeviceTypeAddrVector devices;
4235 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004236 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4237 if (status != NO_ERROR) {
4238 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4239 __FUNCTION__, userId);
4240 return status;
4241 }
4242
4243 // reevaluate outputs for all devices
4244 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004245 changeOutputDevicesMuteState(devices);
4246 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4247 true /* skipDelays */);
4248 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004249
4250 return NO_ERROR;
4251}
4252
Andy Hungc29d82b2018-10-05 12:23:17 -07004253void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004254{
Andy Hungc29d82b2018-10-05 12:23:17 -07004255 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004256 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004257 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004258 std::string stateLiteral;
4259 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004260 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004261 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4262 "communications", "media", "record", "dock", "system",
4263 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4264 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4265 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004266 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4267 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4268 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4269 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4270 dst->append(" (MANUAL: ");
4271 dumpManualSurroundFormats(dst);
4272 dst->append(")");
4273 }
4274 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004275 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004276 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4277 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004278 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004279 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004280
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004281 dst->append("\n");
4282 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4283 dst->append("\n");
4284 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004285 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004286 mOutputs.dump(dst);
4287 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004288 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004289 mAudioPatches.dump(dst);
4290 mPolicyMixes.dump(dst);
4291 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004292
Kevin Rocardb99cc752019-03-21 20:52:24 -07004293 dst->appendFormat(" AllowedCapturePolicies:\n");
4294 for (auto& policy : mAllowedCapturePolicies) {
4295 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4296 }
4297
jiabina84c3d32022-12-02 18:59:55 +00004298 dst->appendFormat(" Preferred mixer audio configuration:\n");
4299 for (const auto it : mPreferredMixerAttrInfos) {
4300 dst->appendFormat(" - device port id: %d\n", it.first);
4301 for (const auto preferredMixerInfoIt : it.second) {
4302 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4303 preferredMixerInfoIt.second->dump(dst);
4304 }
4305 }
4306
François Gaffiec005e562018-11-06 15:04:49 +01004307 dst->appendFormat("\nPolicy Engine dump:\n");
4308 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004309}
4310
4311status_t AudioPolicyManager::dump(int fd)
4312{
4313 String8 result;
4314 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004315 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004316 return NO_ERROR;
4317}
4318
Kevin Rocardb99cc752019-03-21 20:52:24 -07004319status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4320{
4321 mAllowedCapturePolicies[uid] = capturePolicy;
4322 return NO_ERROR;
4323}
4324
Eric Laurente552edb2014-03-10 17:42:56 -07004325// This function checks for the parameters which can be offloaded.
4326// This can be enhanced depending on the capability of the DSP and policy
4327// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004328audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004329{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004330 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004331 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004332 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004333 offloadInfo.format,
4334 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4335 offloadInfo.has_video);
4336
jiabin2b9d5a12021-12-10 01:06:29 +00004337 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004338 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004339 }
4340
4341 // See if there is a profile to support this.
4342 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004343 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004344 offloadInfo.sample_rate,
4345 offloadInfo.format,
4346 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004347 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4348 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004349 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4350 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4351 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004352 if (profile == nullptr) {
4353 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4354 }
4355 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4356 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4357 }
4358 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004359}
4360
Michael Chana94fbb22018-04-24 14:31:19 +10004361bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4362 const audio_attributes_t& attributes) {
4363 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004364 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004365 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4366 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004367 config.sample_rate,
4368 config.format,
4369 config.channel_mask,
4370 output_flags,
4371 true /* directOnly */);
4372 ALOGV("%s() profile %sfound with name: %s, "
4373 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4374 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004375 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004376 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004377
4378 // also try the MSD module if compatible profile not found
4379 if (profile == nullptr) {
4380 profile = getMsdProfileForOutput(outputDevices,
4381 config.sample_rate,
4382 config.format,
4383 config.channel_mask,
4384 output_flags,
4385 true /* directOnly */);
4386 ALOGV("%s() MSD profile %sfound with name: %s, "
4387 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4388 __FUNCTION__, profile != 0 ? "" : "NOT ",
4389 (profile != 0 ? profile->getTagName().c_str() : "null"),
4390 config.sample_rate, config.format, config.channel_mask, output_flags);
4391 }
4392 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004393}
4394
jiabin2b9d5a12021-12-10 01:06:29 +00004395bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4396 bool durationIgnored) {
4397 if (mMasterMono) {
4398 return false; // no offloading if mono is set.
4399 }
4400
4401 // Check if offload has been disabled
4402 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4403 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4404 return false;
4405 }
4406
4407 // Check if stream type is music, then only allow offload as of now.
4408 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4409 {
4410 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4411 return false;
4412 }
4413
4414 //TODO: enable audio offloading with video when ready
4415 const bool allowOffloadWithVideo =
4416 property_get_bool("audio.offload.video", false /* default_value */);
4417 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4418 ALOGV("%s: has_video == true, returning false", __func__);
4419 return false;
4420 }
4421
4422 //If duration is less than minimum value defined in property, return false
4423 const int min_duration_secs = property_get_int32(
4424 "audio.offload.min.duration.secs", -1 /* default_value */);
4425 if (!durationIgnored) {
4426 if (min_duration_secs >= 0) {
4427 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4428 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4429 __func__, min_duration_secs);
4430 return false;
4431 }
4432 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4433 ALOGV("%s: Offload denied by duration < default min(=%u)",
4434 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4435 return false;
4436 }
4437 }
4438
4439 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4440 // creating an offloaded track and tearing it down immediately after start when audioflinger
4441 // detects there is an active non offloadable effect.
4442 // FIXME: We should check the audio session here but we do not have it in this context.
4443 // This may prevent offloading in rare situations where effects are left active by apps
4444 // in the background.
4445 if (mEffects.isNonOffloadableEffectEnabled()) {
4446 return false;
4447 }
4448
4449 return true;
4450}
4451
4452audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4453 const audio_config_t *config) {
4454 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4455 offloadInfo.format = config->format;
4456 offloadInfo.sample_rate = config->sample_rate;
4457 offloadInfo.channel_mask = config->channel_mask;
4458 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4459 offloadInfo.has_video = false;
4460 offloadInfo.is_streaming = false;
4461 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4462
4463 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4464 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4465 audio_flags_to_audio_output_flags(attr->flags, &flags);
4466 // only retain flags that will drive compressed offload or passthrough
4467 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4468 if (offloadPossible) {
4469 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4470 }
4471 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4472
Dorin Drimusfae3c642022-03-17 18:36:30 +01004473 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004474 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004475 DeviceVector outputDevices = engineOutputDevices;
4476 // the MSD module checks for different conditions and output devices
4477 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4478 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4479 continue;
4480 }
4481 outputDevices = getMsdAudioOutDevices();
4482 }
jiabin2b9d5a12021-12-10 01:06:29 +00004483 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004484 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004485 config->sample_rate, nullptr /*updatedSamplingRate*/,
4486 config->format, nullptr /*updatedFormat*/,
4487 config->channel_mask, nullptr /*updatedChannelMask*/,
4488 flags)) {
4489 continue;
4490 }
4491 // reject profiles not corresponding to a device currently available
4492 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4493 continue;
4494 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004495 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4496 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004497 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004498 != AUDIO_DIRECT_NOT_SUPPORTED) {
4499 // Already reports offload gapless supported. No need to report offload support.
4500 continue;
4501 }
4502 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4503 != AUDIO_OUTPUT_FLAG_NONE) {
4504 // If offload gapless is reported, no need to report offload support.
4505 directMode = (audio_direct_mode_t) ((directMode &
4506 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4507 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4508 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004509 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004510 }
4511 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004512 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004513 }
4514 }
4515 }
4516 return directMode;
4517}
4518
Dorin Drimusf2196d82022-01-03 12:11:18 +01004519status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4520 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004521 if (mEffects.isNonOffloadableEffectEnabled()) {
4522 return OK;
4523 }
jiabinf1c73972022-04-14 16:28:52 -07004524 DeviceVector devices;
4525 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004526 if (status != OK) {
4527 return status;
4528 }
4529 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4530 if (devices.empty()) {
4531 return OK; // no output devices for the attributes
4532 }
jiabinf1c73972022-04-14 16:28:52 -07004533 return getProfilesForDevices(devices, audioProfilesVector,
4534 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004535}
4536
jiabina84c3d32022-12-02 18:59:55 +00004537status_t AudioPolicyManager::getSupportedMixerAttributes(
4538 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4539 ALOGV("%s, portId=%d", __func__, portId);
4540 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4541 if (deviceDescriptor == nullptr) {
4542 ALOGE("%s the requested device is currently unavailable", __func__);
4543 return BAD_VALUE;
4544 }
jiabin96daffc2023-05-11 17:51:55 +00004545 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4546 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4547 deviceDescriptor->type());
4548 return BAD_VALUE;
4549 }
jiabina84c3d32022-12-02 18:59:55 +00004550 for (const auto& hwModule : mHwModules) {
4551 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4552 if (curProfile->supportsDevice(deviceDescriptor)) {
4553 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4554 }
4555 }
4556 }
4557 return NO_ERROR;
4558}
4559
4560status_t AudioPolicyManager::setPreferredMixerAttributes(
4561 const audio_attributes_t *attr,
4562 audio_port_handle_t portId,
4563 uid_t uid,
4564 const audio_mixer_attributes_t *mixerAttributes) {
4565 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4566 "mixerBehavior=%d}, uid=%d, portId=%u",
4567 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4568 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4569 mixerAttributes->mixer_behavior, uid, portId);
4570 if (attr->usage != AUDIO_USAGE_MEDIA) {
4571 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4572 return BAD_VALUE;
4573 }
4574 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4575 if (deviceDescriptor == nullptr) {
4576 ALOGE("%s the requested device is currently unavailable", __func__);
4577 return BAD_VALUE;
4578 }
4579 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4580 ALOGE("%s(%d), type=%d, is not a usb output device",
4581 __func__, portId, deviceDescriptor->type());
4582 return BAD_VALUE;
4583 }
4584
4585 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4586 audio_flags_to_audio_output_flags(attr->flags, &flags);
4587 flags = (audio_output_flags_t) (flags |
4588 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4589 sp<IOProfile> profile = nullptr;
4590 DeviceVector devices(deviceDescriptor);
4591 for (const auto& hwModule : mHwModules) {
4592 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4593 if (curProfile->hasDynamicAudioProfile()
4594 && curProfile->isCompatibleProfile(devices,
4595 mixerAttributes->config.sample_rate,
4596 nullptr /*updatedSamplingRate*/,
4597 mixerAttributes->config.format,
4598 nullptr /*updatedFormat*/,
4599 mixerAttributes->config.channel_mask,
4600 nullptr /*updatedChannelMask*/,
4601 flags,
4602 false /*exactMatchRequiredForInputFlags*/)) {
4603 profile = curProfile;
4604 break;
4605 }
4606 }
4607 }
4608 if (profile == nullptr) {
4609 ALOGE("%s, there is no compatible profile found", __func__);
4610 return BAD_VALUE;
4611 }
4612
4613 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4614 sp<PreferredMixerAttributesInfo>::make(
4615 uid, portId, profile, flags, *mixerAttributes);
4616 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4617 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4618
4619 // If 1) there is any client from the preferred mixer configuration owner that is currently
4620 // active and matches the strategy and 2) current output is on the preferred device and the
4621 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4622 // configuration.
4623 std::vector<audio_io_handle_t> outputsToReopen;
4624 for (size_t i = 0; i < mOutputs.size(); i++) {
4625 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004626 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4627 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4628 output->mUsePreferredMixerAttributes = true;
4629 } else {
4630 for (const auto &client: output->getActiveClients()) {
4631 if (client->uid() == uid && client->strategy() == strategy) {
4632 client->setIsInvalid();
4633 outputsToReopen.push_back(output->mIoHandle);
4634 }
jiabina84c3d32022-12-02 18:59:55 +00004635 }
4636 }
4637 }
4638 }
4639 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4640 config.sample_rate = mixerAttributes->config.sample_rate;
4641 config.channel_mask = mixerAttributes->config.channel_mask;
4642 config.format = mixerAttributes->config.format;
4643 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004644 sp<SwAudioOutputDescriptor> desc =
4645 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4646 if (desc == nullptr) {
4647 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4648 continue;
4649 }
4650 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004651 }
4652
4653 return NO_ERROR;
4654}
4655
4656sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004657 audio_port_handle_t devicePortId,
4658 product_strategy_t strategy,
4659 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004660 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4661 if (it == mPreferredMixerAttrInfos.end()) {
4662 return nullptr;
4663 }
jiabind9a58d32023-06-01 17:57:30 +00004664 if (activeBitPerfectPreferred) {
4665 for (auto [strategy, info] : it->second) {
4666 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4667 && info->getActiveClientCount() != 0) {
4668 return info;
4669 }
4670 }
jiabina84c3d32022-12-02 18:59:55 +00004671 }
jiabind9a58d32023-06-01 17:57:30 +00004672 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4673 return strategyMatchedMixerAttrInfoIt == it->second.end()
4674 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004675}
4676
4677status_t AudioPolicyManager::getPreferredMixerAttributes(
4678 const audio_attributes_t *attr,
4679 audio_port_handle_t portId,
4680 audio_mixer_attributes_t* mixerAttributes) {
4681 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4682 portId, mEngine->getProductStrategyForAttributes(*attr));
4683 if (info == nullptr) {
4684 return NAME_NOT_FOUND;
4685 }
4686 *mixerAttributes = info->getMixerAttributes();
4687 return NO_ERROR;
4688}
4689
4690status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4691 audio_port_handle_t portId,
4692 uid_t uid) {
4693 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4694 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4695 if (preferredMixerAttrInfo == nullptr) {
4696 return NAME_NOT_FOUND;
4697 }
4698 if (preferredMixerAttrInfo->getUid() != uid) {
4699 ALOGE("%s, requested uid=%d, owned uid=%d",
4700 __func__, uid, preferredMixerAttrInfo->getUid());
4701 return PERMISSION_DENIED;
4702 }
4703 mPreferredMixerAttrInfos[portId].erase(strategy);
4704 if (mPreferredMixerAttrInfos[portId].empty()) {
4705 mPreferredMixerAttrInfos.erase(portId);
4706 }
4707
4708 // Reconfig existing output
4709 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4710 for (size_t i = 0; i < mOutputs.size(); i++) {
4711 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4712 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4713 }
4714 }
4715 for (const auto output : potentialOutputsToReopen) {
4716 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4717 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4718 preferredMixerAttrInfo->getFlags())) {
4719 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4720 }
4721 }
4722 return NO_ERROR;
4723}
4724
Eric Laurent6a94d692014-05-20 11:18:06 -07004725status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4726 audio_port_type_t type,
4727 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004728 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004729 unsigned int *generation)
4730{
jiabin19cdba52020-11-24 11:28:58 -08004731 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4732 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004733 return BAD_VALUE;
4734 }
4735 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004736 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004737 *num_ports = 0;
4738 }
4739
4740 size_t portsWritten = 0;
4741 size_t portsMax = *num_ports;
4742 *num_ports = 0;
4743 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004744 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4745 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004746 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004747 for (const auto& dev : mAvailableOutputDevices) {
4748 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004749 continue;
4750 }
4751 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004752 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004753 }
4754 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004755 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004756 }
4757 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004758 for (const auto& dev : mAvailableInputDevices) {
4759 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004760 continue;
4761 }
4762 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004763 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004764 }
4765 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004766 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004767 }
4768 }
4769 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4770 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4771 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4772 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4773 }
4774 *num_ports += mInputs.size();
4775 }
4776 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004777 size_t numOutputs = 0;
4778 for (size_t i = 0; i < mOutputs.size(); i++) {
4779 if (!mOutputs[i]->isDuplicated()) {
4780 numOutputs++;
4781 if (portsWritten < portsMax) {
4782 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4783 }
4784 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004785 }
Eric Laurent84c70242014-06-23 08:46:27 -07004786 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004787 }
4788 }
jiabina84c3d32022-12-02 18:59:55 +00004789
Eric Laurent6a94d692014-05-20 11:18:06 -07004790 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004791 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004792 return NO_ERROR;
4793}
4794
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004795status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4796 std::vector<media::AudioPortFw>* _aidl_return) {
4797 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4798 audio_port_v7 port;
4799 dev->toAudioPort(&port);
4800 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4801 _aidl_return->push_back(std::move(aidlPort));
4802 return OK;
4803 };
4804
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004805 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004806 for (const auto& dev : module->getDeclaredDevices()) {
4807 if (role == media::AudioPortRole::NONE ||
4808 ((role == media::AudioPortRole::SOURCE)
4809 == audio_is_input_device(dev->type()))) {
4810 RETURN_STATUS_IF_ERROR(pushPort(dev));
4811 }
4812 }
4813 }
4814 return OK;
4815}
4816
jiabin19cdba52020-11-24 11:28:58 -08004817status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004818{
Eric Laurent99fcae42018-05-17 16:59:18 -07004819 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4820 return BAD_VALUE;
4821 }
4822 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4823 if (dev != 0) {
4824 dev->toAudioPort(port);
4825 return NO_ERROR;
4826 }
4827 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4828 if (dev != 0) {
4829 dev->toAudioPort(port);
4830 return NO_ERROR;
4831 }
4832 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4833 if (out != 0) {
4834 out->toAudioPort(port);
4835 return NO_ERROR;
4836 }
4837 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4838 if (in != 0) {
4839 in->toAudioPort(port);
4840 return NO_ERROR;
4841 }
4842 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004843}
4844
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004845status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4846 audio_patch_handle_t *handle,
4847 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004848{
François Gaffieafd4cea2019-11-18 15:50:22 +01004849 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004850 if (handle == NULL || patch == NULL) {
4851 return BAD_VALUE;
4852 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004853 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004854 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004855 return BAD_VALUE;
4856 }
4857 // only one source per audio patch supported for now
4858 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004859 return INVALID_OPERATION;
4860 }
Eric Laurent874c42872014-08-08 15:13:39 -07004861 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004862 return INVALID_OPERATION;
4863 }
Eric Laurent874c42872014-08-08 15:13:39 -07004864 for (size_t i = 0; i < patch->num_sinks; i++) {
4865 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4866 return INVALID_OPERATION;
4867 }
4868 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004869
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004870 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4871 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4872 if (srcDevice == nullptr || sinkDevice == nullptr) {
4873 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4874 return BAD_VALUE;
4875 }
4876 ALOGV("%s between source %s and sink %s", __func__,
4877 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4878 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4879 // Default attributes, default volume priority, not to infer with non raw audio patches.
4880 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4881 const struct audio_port_config *source = &patch->sources[0];
4882 sp<SourceClientDescriptor> sourceDesc =
Eric Laurent541a2002024-01-15 18:11:42 +01004883 new SourceClientDescriptor(
4884 portId, uid, attributes, *source, srcDevice, AUDIO_STREAM_PATCH,
4885 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes),
4886 true);
4887 sourceDesc->setPreferredDeviceId(sinkDevice->getId());
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004888
4889 status_t status =
4890 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4891
4892 if (status != NO_ERROR) {
4893 return INVALID_OPERATION;
4894 }
4895 mAudioSources.add(portId, sourceDesc);
4896 return NO_ERROR;
4897}
4898
4899status_t AudioPolicyManager::connectAudioSourceToSink(
4900 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4901 const struct audio_patch *patch,
4902 audio_patch_handle_t &handle,
4903 uid_t uid, uint32_t delayMs)
4904{
4905 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4906 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4907 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4908 return INVALID_OPERATION;
4909 }
4910 sourceDesc->connect(handle, sinkDevice);
4911 if (isMsdPatch(handle)) {
4912 return NO_ERROR;
4913 }
4914 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4915 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4916 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4917 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4918 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4919 goto FailurePatchAdded;
4920 }
4921 status = swOutput->start();
4922 if (status != NO_ERROR) {
4923 goto FailureSourceAdded;
4924 }
4925 swOutput->addClient(sourceDesc);
4926 status = startSource(swOutput, sourceDesc, &delayMs);
4927 if (status != NO_ERROR) {
4928 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4929 goto FailureSourceActive;
4930 }
4931 if (delayMs != 0) {
4932 usleep(delayMs * 1000);
4933 }
4934 return NO_ERROR;
4935
4936FailureSourceActive:
4937 swOutput->stop();
4938 releaseOutput(sourceDesc->portId());
4939FailureSourceAdded:
4940 sourceDesc->setSwOutput(nullptr);
4941FailurePatchAdded:
4942 releaseAudioPatchInternal(handle);
4943 return INVALID_OPERATION;
4944}
4945
4946status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4947 audio_patch_handle_t *handle,
4948 uid_t uid, uint32_t delayMs,
4949 const sp<SourceClientDescriptor>& sourceDesc)
4950{
4951 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004952 sp<AudioPatch> patchDesc;
4953 ssize_t index = mAudioPatches.indexOfKey(*handle);
4954
François Gaffieafd4cea2019-11-18 15:50:22 +01004955 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4956 patch->sources[0].role,
4957 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004958#if LOG_NDEBUG == 0
4959 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004960 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4961 patch->sinks[i].role,
4962 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004963 }
4964#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004965
4966 if (index >= 0) {
4967 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004968 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4969 __func__, mUidCached, patchDesc->getUid(), uid);
4970 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004971 return INVALID_OPERATION;
4972 }
4973 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004974 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004975 }
4976
4977 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004978 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004979 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004980 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004981 return BAD_VALUE;
4982 }
Eric Laurent84c70242014-06-23 08:46:27 -07004983 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4984 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004985 if (patchDesc != 0) {
4986 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004987 ALOGV("%s source id differs for patch current id %d new id %d",
4988 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004989 return BAD_VALUE;
4990 }
4991 }
Eric Laurent874c42872014-08-08 15:13:39 -07004992 DeviceVector devices;
4993 for (size_t i = 0; i < patch->num_sinks; i++) {
4994 // Only support mix to devices connection
4995 // TODO add support for mix to mix connection
4996 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004997 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004998 return INVALID_OPERATION;
4999 }
5000 sp<DeviceDescriptor> devDesc =
5001 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
5002 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005003 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07005004 return BAD_VALUE;
5005 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005006
François Gaffie11d30102018-11-02 16:09:09 +01005007 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07005008 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01005009 NULL, // updatedSamplingRate
5010 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005011 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01005012 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005013 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01005014 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005015 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005016 return INVALID_OPERATION;
5017 }
5018 devices.add(devDesc);
5019 }
5020 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005021 return INVALID_OPERATION;
5022 }
Eric Laurent874c42872014-08-08 15:13:39 -07005023
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005025 ALOGV("%s setting device %s on output %d",
5026 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305027 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005028 index = mAudioPatches.indexOfKey(*handle);
5029 if (index >= 0) {
5030 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005031 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005032 }
5033 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005034 patchDesc->setUid(uid);
5035 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005036 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005037 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005038 return INVALID_OPERATION;
5039 }
5040 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5041 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5042 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005043 // only one sink supported when connecting an input device to a mix
5044 if (patch->num_sinks > 1) {
5045 return INVALID_OPERATION;
5046 }
François Gaffie53615e22015-03-19 09:24:12 +01005047 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005048 if (inputDesc == NULL) {
5049 return BAD_VALUE;
5050 }
5051 if (patchDesc != 0) {
5052 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5053 return BAD_VALUE;
5054 }
5055 }
François Gaffie11d30102018-11-02 16:09:09 +01005056 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005057 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005058 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005059 return BAD_VALUE;
5060 }
5061
François Gaffie11d30102018-11-02 16:09:09 +01005062 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005063 patch->sinks[0].sample_rate,
5064 NULL, /*updatedSampleRate*/
5065 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005066 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005067 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005068 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005069 // FIXME for the parameter type,
5070 // and the NONE
5071 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005072 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005073 return INVALID_OPERATION;
5074 }
5075 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005076 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005077 device->toString().c_str(), inputDesc->mIoHandle);
5078 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005079 index = mAudioPatches.indexOfKey(*handle);
5080 if (index >= 0) {
5081 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005082 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005083 }
5084 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005085 patchDesc->setUid(uid);
5086 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005087 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005088 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005089 return INVALID_OPERATION;
5090 }
5091 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5092 // device to device connection
5093 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005094 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005095 return BAD_VALUE;
5096 }
5097 }
François Gaffie11d30102018-11-02 16:09:09 +01005098 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005099 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005100 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005101 return BAD_VALUE;
5102 }
Eric Laurent874c42872014-08-08 15:13:39 -07005103
Eric Laurent6a94d692014-05-20 11:18:06 -07005104 //update source and sink with our own data as the data passed in the patch may
5105 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005106 PatchBuilder patchBuilder;
5107 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005108
5109 // if first sink is to MSD, establish single MSD patch
5110 if (getMsdAudioOutDevices().contains(
5111 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5112 ALOGV("%s patching to MSD", __FUNCTION__);
5113 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5114 goto installPatch;
5115 }
5116
François Gaffieafd4cea2019-11-18 15:50:22 +01005117 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5118 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005119
Eric Laurent874c42872014-08-08 15:13:39 -07005120 for (size_t i = 0; i < patch->num_sinks; i++) {
5121 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005122 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005123 return INVALID_OPERATION;
5124 }
François Gaffie11d30102018-11-02 16:09:09 +01005125 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005126 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005127 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005128 return BAD_VALUE;
5129 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005130 audio_port_config sinkPortConfig = {};
5131 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5132 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005133
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005134 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5135 // volume management purpose (tracking activity)
5136 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5137 // in config XML to reach the sink so that is can be declared as available.
5138 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005139 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005140 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005141 // take care of dynamic routing for SwOutput selection,
5142 audio_attributes_t attributes = sourceDesc->attributes();
5143 audio_stream_type_t stream = sourceDesc->stream();
5144 audio_attributes_t resultAttr;
5145 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5146 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005147 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5148 config.channel_mask =
5149 (audio_channel_mask_get_representation(sourceMask)
5150 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5151 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005152 config.format = sourceDesc->config().format;
5153 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5154 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5155 bool isRequestedDeviceForExclusiveUse = false;
5156 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005157 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005158 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005159 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5160 &stream, sourceDesc->uid(), &config, &flags,
5161 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005162 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005163 if (output == AUDIO_IO_HANDLE_NONE) {
5164 ALOGV("%s no output for device %s",
5165 __FUNCTION__, sinkDevice->toString().c_str());
5166 return INVALID_OPERATION;
5167 }
5168 outputDesc = mOutputs.valueFor(output);
5169 if (outputDesc->isDuplicated()) {
5170 ALOGE("%s output is duplicated", __func__);
5171 return INVALID_OPERATION;
5172 }
François Gaffie7e39df22022-04-26 12:48:49 +02005173 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5174 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005175 } else {
5176 // Same for "raw patches" aka created from createAudioPatch API
5177 SortedVector<audio_io_handle_t> outputs =
5178 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5179 // if the sink device is reachable via an opened output stream, request to
5180 // go via this output stream by adding a second source to the patch
5181 // description
5182 output = selectOutput(outputs);
5183 if (output == AUDIO_IO_HANDLE_NONE) {
5184 ALOGE("%s no output available for internal patch sink", __func__);
5185 return INVALID_OPERATION;
5186 }
5187 outputDesc = mOutputs.valueFor(output);
5188 if (outputDesc->isDuplicated()) {
5189 ALOGV("%s output for device %s is duplicated",
5190 __func__, sinkDevice->toString().c_str());
5191 return INVALID_OPERATION;
5192 }
François Gaffie7e39df22022-04-26 12:48:49 +02005193 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005194 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005195 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005196 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005197 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005198 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005199 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5200 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005201 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5202 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005203 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005204 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005205 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005206 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005207 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005208 return INVALID_OPERATION;
5209 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005210 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005211 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005212 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005213 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005214 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005215 srcMixPortConfig.ext.mix.usecase.stream =
5216 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005217 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5218 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005219 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005220 }
Eric Laurent83b88082014-06-20 18:31:16 -07005221 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005222 }
5223 // TODO: check from routing capabilities in config file and other conflicting patches
5224
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005225installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005226 status_t status = installPatch(
5227 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005228 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005229 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005230 return INVALID_OPERATION;
5231 }
5232 } else {
5233 return BAD_VALUE;
5234 }
5235 } else {
5236 return BAD_VALUE;
5237 }
5238 return NO_ERROR;
5239}
5240
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005241status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005242{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005243 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005244 ssize_t index = mAudioPatches.indexOfKey(handle);
5245
5246 if (index < 0) {
5247 return BAD_VALUE;
5248 }
5249 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005250 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5251 __func__, mUidCached, patchDesc->getUid(), uid);
5252 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005253 return INVALID_OPERATION;
5254 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005255 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5256 for (size_t i = 0; i < mAudioSources.size(); i++) {
5257 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5258 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5259 portId = sourceDesc->portId();
5260 break;
5261 }
5262 }
5263 return portId != AUDIO_PORT_HANDLE_NONE ?
5264 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005265}
Eric Laurent6a94d692014-05-20 11:18:06 -07005266
François Gaffieafd4cea2019-11-18 15:50:22 +01005267status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005268 uint32_t delayMs,
5269 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005270{
5271 ALOGV("%s patch %d", __func__, handle);
5272 if (mAudioPatches.indexOfKey(handle) < 0) {
5273 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5274 return BAD_VALUE;
5275 }
5276 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005277 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005278 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005279 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005280 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005281 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005282 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 return BAD_VALUE;
5284 }
5285
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305286 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005287 getNewOutputDevices(outputDesc, true /*fromCache*/),
5288 true,
5289 0,
5290 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005291 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5292 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005293 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005294 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005295 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005296 return BAD_VALUE;
5297 }
5298 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005299 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 true,
5301 NULL);
5302 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005303 status_t status =
5304 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5305 ALOGV("%s patch panel returned %d patchHandle %d",
5306 __func__, status, patchDesc->getAfHandle());
5307 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005308 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005309 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005310 // SW or HW Bridge
5311 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5312 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005313 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005314 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5315 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5316 outputDesc = sourceDesc->swOutput().promote();
5317 }
5318 if (outputDesc == nullptr) {
5319 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5320 // releaseOutput has already called closeOutput in case of direct output
5321 return NO_ERROR;
5322 }
François Gaffie7e39df22022-04-26 12:48:49 +02005323 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005324 // While using a HwBridge, force reconsidering device only if not reusing an existing
5325 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005326 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005327 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5328 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5329 // Reconsider device only for cases:
5330 // 1 / Active Output
5331 // 2 / Inactive Output previously hosting HwBridge
5332 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5333 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5334 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305335 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005336 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5337 outputDesc->devices(),
5338 force,
5339 0,
5340 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005341 } else {
5342 return BAD_VALUE;
5343 }
5344 } else {
5345 return BAD_VALUE;
5346 }
5347 return NO_ERROR;
5348}
5349
5350status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5351 struct audio_patch *patches,
5352 unsigned int *generation)
5353{
François Gaffie53615e22015-03-19 09:24:12 +01005354 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005355 return BAD_VALUE;
5356 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005357 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005358 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005359}
5360
Eric Laurente1715a42014-05-20 11:30:42 -07005361status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005362{
Eric Laurente1715a42014-05-20 11:30:42 -07005363 ALOGV("setAudioPortConfig()");
5364
5365 if (config == NULL) {
5366 return BAD_VALUE;
5367 }
5368 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5369 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005370 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5371 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005372 }
5373
Eric Laurenta121f902014-06-03 13:32:54 -07005374 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005375 if (config->type == AUDIO_PORT_TYPE_MIX) {
5376 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005377 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005378 if (outputDesc == NULL) {
5379 return BAD_VALUE;
5380 }
Eric Laurent84c70242014-06-23 08:46:27 -07005381 ALOG_ASSERT(!outputDesc->isDuplicated(),
5382 "setAudioPortConfig() called on duplicated output %d",
5383 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005384 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005385 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005386 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005387 if (inputDesc == NULL) {
5388 return BAD_VALUE;
5389 }
Eric Laurenta121f902014-06-03 13:32:54 -07005390 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005391 } else {
5392 return BAD_VALUE;
5393 }
5394 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5395 sp<DeviceDescriptor> deviceDesc;
5396 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5397 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5398 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5399 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5400 } else {
5401 return BAD_VALUE;
5402 }
5403 if (deviceDesc == NULL) {
5404 return BAD_VALUE;
5405 }
Eric Laurenta121f902014-06-03 13:32:54 -07005406 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005407 } else {
5408 return BAD_VALUE;
5409 }
5410
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005411 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005412 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5413 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005414 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005415 audioPortConfig->toAudioPortConfig(&newConfig, config);
5416 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005417 }
Eric Laurenta121f902014-06-03 13:32:54 -07005418 if (status != NO_ERROR) {
5419 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005420 }
Eric Laurente1715a42014-05-20 11:30:42 -07005421
5422 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005423}
5424
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005425void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5426{
Eric Laurentd60560a2015-04-10 11:31:20 -07005427 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005428 clearAudioPatches(uid);
5429 clearSessionRoutes(uid);
5430}
5431
Eric Laurent6a94d692014-05-20 11:18:06 -07005432void AudioPolicyManager::clearAudioPatches(uid_t uid)
5433{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005434 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005435 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005436 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005437 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005438 }
5439 }
5440}
5441
François Gaffiec005e562018-11-06 15:04:49 +01005442void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005443{
François Gaffiec005e562018-11-06 15:04:49 +01005444 // Take the first attributes following the product strategy as it is used to retrieve the routed
5445 // device. All attributes wihin a strategy follows the same "routing strategy"
5446 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5447 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005448 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005449 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005450 for (size_t j = 0; j < mOutputs.size(); j++) {
5451 if (mOutputs.keyAt(j) == ouptutToSkip) {
5452 continue;
5453 }
5454 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005455 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005456 continue;
5457 }
5458 // If the default device for this strategy is on another output mix,
5459 // invalidate all tracks in this strategy to force re connection.
5460 // Otherwise select new device on the output mix.
5461 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005462 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005463 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005464 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5465 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5466 // If the device is using preferred mixer attributes, the output need to reopen
5467 // with default configuration when the new selected devices are different from
5468 // current routing devices.
5469 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5470 continue;
5471 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305472 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005473 }
5474 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005475 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005476}
5477
5478void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5479{
5480 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005481 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005482 for (size_t i = 0; i < mOutputs.size(); i++) {
5483 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005484 for (const auto& client : outputDesc->getClientIterable()) {
5485 if (client->hasPreferredDevice() && client->uid() == uid) {
5486 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005487 auto clientStrategy = client->strategy();
5488 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5489 end(affectedStrategies)) {
5490 continue;
5491 }
5492 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005493 }
5494 }
5495 }
5496 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005497 for (const auto& strategy : affectedStrategies) {
5498 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005499 }
5500
5501 // remove input routes associated with this uid
5502 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005503 for (size_t i = 0; i < mInputs.size(); i++) {
5504 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005505 for (const auto& client : inputDesc->getClientIterable()) {
5506 if (client->hasPreferredDevice() && client->uid() == uid) {
5507 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5508 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005509 }
5510 }
5511 }
5512 // reroute inputs if necessary
5513 SortedVector<audio_io_handle_t> inputsToClose;
5514 for (size_t i = 0; i < mInputs.size(); i++) {
5515 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005516 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005517 inputsToClose.add(inputDesc->mIoHandle);
5518 }
5519 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005520 for (const auto& input : inputsToClose) {
5521 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005522 }
5523}
5524
Eric Laurentd60560a2015-04-10 11:31:20 -07005525void AudioPolicyManager::clearAudioSources(uid_t uid)
5526{
5527 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005528 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5529 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005530 stopAudioSource(mAudioSources.keyAt(i));
5531 }
5532 }
5533}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005534
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005535status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5536 audio_io_handle_t *ioHandle,
5537 audio_devices_t *device)
5538{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005539 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5540 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005541 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005542 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5543 if (deviceDesc == nullptr) {
5544 return INVALID_OPERATION;
5545 }
5546 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005547
François Gaffiedf372692015-03-19 10:43:27 +01005548 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005549}
5550
Eric Laurentd60560a2015-04-10 11:31:20 -07005551status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005552 const audio_attributes_t *attributes,
5553 audio_port_handle_t *portId,
Eric Laurent541a2002024-01-15 18:11:42 +01005554 uid_t uid, bool internal)
Eric Laurent554a2772015-04-10 11:29:24 -07005555{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005556 ALOGV("%s", __FUNCTION__);
5557 *portId = AUDIO_PORT_HANDLE_NONE;
5558
5559 if (source == NULL || attributes == NULL || portId == NULL) {
5560 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5561 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005562 return BAD_VALUE;
5563 }
5564
Eric Laurentd60560a2015-04-10 11:31:20 -07005565 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5566 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005567 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5568 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005569 return INVALID_OPERATION;
5570 }
5571
François Gaffie11d30102018-11-02 16:09:09 +01005572 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005573 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005574 String8(source->ext.device.address),
5575 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005576 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005577 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005578 return BAD_VALUE;
5579 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005580
jiabin4ef93452019-09-10 14:29:54 -07005581 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005582
François Gaffieaaac0fd2018-11-22 17:56:39 +01005583 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005584 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005585 mEngine->getStreamTypeForAttributes(*attributes),
5586 mEngine->getProductStrategyForAttributes(*attributes),
Eric Laurent541a2002024-01-15 18:11:42 +01005587 toVolumeSource(*attributes), internal);
Eric Laurentd60560a2015-04-10 11:31:20 -07005588
5589 status_t status = connectAudioSource(sourceDesc);
5590 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005591 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005592 }
5593 return status;
5594}
5595
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005596status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005597{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005598 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005599
5600 // make sure we only have one patch per source.
5601 disconnectAudioSource(sourceDesc);
5602
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005603 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005604 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5605 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5606 sourceDesc->srcDevice()->type(),
5607 String8(sourceDesc->srcDevice()->address().c_str()),
5608 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005609 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005610 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005611 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005612 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005613 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5614 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5615 return INVALID_OPERATION;
5616 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005617 PatchBuilder patchBuilder;
5618 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5619 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005620
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005621 return connectAudioSourceToSink(
5622 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005623}
5624
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005625status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005626{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005627 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5628 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005629 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005630 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005631 return BAD_VALUE;
5632 }
5633 status_t status = disconnectAudioSource(sourceDesc);
5634
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005635 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005636 return status;
5637}
5638
Andy Hung2ddee192015-12-18 17:34:44 -08005639status_t AudioPolicyManager::setMasterMono(bool mono)
5640{
5641 if (mMasterMono == mono) {
5642 return NO_ERROR;
5643 }
5644 mMasterMono = mono;
5645 // if enabling mono we close all offloaded devices, which will invalidate the
5646 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5647 // for recreating the new AudioTrack as non-offloaded PCM.
5648 //
5649 // If disabling mono, we leave all tracks as is: we don't know which clients
5650 // and tracks are able to be recreated as offloaded. The next "song" should
5651 // play back offloaded.
5652 if (mMasterMono) {
5653 Vector<audio_io_handle_t> offloaded;
5654 for (size_t i = 0; i < mOutputs.size(); ++i) {
5655 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5656 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5657 offloaded.push(desc->mIoHandle);
5658 }
5659 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005660 for (const auto& handle : offloaded) {
5661 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005662 }
5663 }
5664 // update master mono for all remaining outputs
5665 for (size_t i = 0; i < mOutputs.size(); ++i) {
5666 updateMono(mOutputs.keyAt(i));
5667 }
5668 return NO_ERROR;
5669}
5670
5671status_t AudioPolicyManager::getMasterMono(bool *mono)
5672{
5673 *mono = mMasterMono;
5674 return NO_ERROR;
5675}
5676
Eric Laurentac9cef52017-06-09 15:46:26 -07005677float AudioPolicyManager::getStreamVolumeDB(
5678 audio_stream_type_t stream, int index, audio_devices_t device)
5679{
jiabin9a3361e2019-10-01 09:38:30 -07005680 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005681}
5682
jiabin81772902018-04-02 17:52:27 -07005683status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5684 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005685 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005686{
Kriti Dang6537def2021-03-02 13:46:59 +01005687 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5688 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005689 return BAD_VALUE;
5690 }
Kriti Dang6537def2021-03-02 13:46:59 +01005691 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5692 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005693
5694 size_t formatsWritten = 0;
5695 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005696
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005697 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005698 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5699 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005700 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005701 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005702 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005703 bool formatEnabled = true;
5704 switch (forceUse) {
5705 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005706 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005707 break;
5708 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5709 formatEnabled = false;
5710 break;
5711 default: // AUTO or ALWAYS => true
5712 break;
jiabin81772902018-04-02 17:52:27 -07005713 }
5714 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5715 }
jiabin81772902018-04-02 17:52:27 -07005716 }
5717 return NO_ERROR;
5718}
5719
Kriti Dang6537def2021-03-02 13:46:59 +01005720status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5721 audio_format_t *surroundFormats) {
5722 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5723 return BAD_VALUE;
5724 }
5725 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5726 __func__, *numSurroundFormats, surroundFormats);
5727
5728 size_t formatsWritten = 0;
5729 size_t formatsMax = *numSurroundFormats;
5730 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5731
5732 // Return formats from all device profiles that have already been resolved by
5733 // checkOutputsForDevice().
5734 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5735 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5736 audio_devices_t deviceType = device->type();
5737 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5738 // returns formats reported by HDMI devices.
5739 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5740 continue;
5741 }
5742 // Formats reported by sink devices
5743 std::unordered_set<audio_format_t> formatset;
5744 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5745 formatset.insert(it->second.begin(), it->second.end());
5746 }
5747
5748 // Formats hard-coded in the in policy configuration file (if any).
5749 FormatVector encodedFormats = device->encodedFormats();
5750 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5751 // Filter the formats which are supported by the vendor hardware.
5752 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005753 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005754 formats.insert(*it);
5755 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005756 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005757 if (pair.second.count(*it) != 0) {
5758 formats.insert(pair.first);
5759 break;
5760 }
5761 }
5762 }
5763 }
5764 }
5765 *numSurroundFormats = formats.size();
5766 for (const auto& format: formats) {
5767 if (formatsWritten < formatsMax) {
5768 surroundFormats[formatsWritten++] = format;
5769 }
5770 }
5771 return NO_ERROR;
5772}
5773
jiabin81772902018-04-02 17:52:27 -07005774status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5775{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005776 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005777 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5778 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005779 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005780 return BAD_VALUE;
5781 }
5782
Mikhail Naganov100f0122018-11-29 11:22:16 -08005783 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5784 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005785 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005786 return INVALID_OPERATION;
5787 }
5788
Mikhail Naganov100f0122018-11-29 11:22:16 -08005789 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005790 return NO_ERROR;
5791 }
5792
Mikhail Naganov100f0122018-11-29 11:22:16 -08005793 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005794 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005795 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005796 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005797 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005798 }
5799 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005800 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005801 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005802 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005803 }
5804 }
5805
5806 sp<SwAudioOutputDescriptor> outputDesc;
5807 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005808 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5809 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005810 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5811 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005812 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005813 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005814 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5815 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5816 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005817 name.c_str(),
5818 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005819 if (status != NO_ERROR) {
5820 continue;
5821 }
5822 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5823 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5824 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005825 name.c_str(),
5826 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005827 profileUpdated |= (status == NO_ERROR);
5828 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005829 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005830 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005831 AUDIO_DEVICE_IN_HDMI);
5832 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5833 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005834 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005835 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005836 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5837 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5838 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005839 name.c_str(),
5840 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005841 if (status != NO_ERROR) {
5842 continue;
5843 }
5844 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5845 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5846 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005847 name.c_str(),
5848 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005849 profileUpdated |= (status == NO_ERROR);
5850 }
5851
jiabin81772902018-04-02 17:52:27 -07005852 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005853 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005854 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005855 }
5856
5857 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5858}
5859
Eric Laurent5ada82e2019-08-29 17:53:54 -07005860void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005861{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005862 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005863 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005864 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005865 }
5866}
5867
jiabin6012f912018-11-02 17:06:30 -07005868bool AudioPolicyManager::isHapticPlaybackSupported()
5869{
5870 for (const auto& hwModule : mHwModules) {
5871 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5872 for (const auto &outProfile : outputProfiles) {
5873 struct audio_port audioPort;
5874 outProfile->toAudioPort(&audioPort);
5875 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5876 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5877 return true;
5878 }
5879 }
5880 }
5881 }
5882 return false;
5883}
5884
Carter Hsu325a8eb2022-01-19 19:56:51 +08005885bool AudioPolicyManager::isUltrasoundSupported()
5886{
5887 bool hasUltrasoundOutput = false;
5888 bool hasUltrasoundInput = false;
5889 for (const auto& hwModule : mHwModules) {
5890 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5891 if (!hasUltrasoundOutput) {
5892 for (const auto &outProfile : outputProfiles) {
5893 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5894 hasUltrasoundOutput = true;
5895 break;
5896 }
5897 }
5898 }
5899
5900 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5901 if (!hasUltrasoundInput) {
5902 for (const auto &inputProfile : inputProfiles) {
5903 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5904 hasUltrasoundInput = true;
5905 break;
5906 }
5907 }
5908 }
5909
5910 if (hasUltrasoundOutput && hasUltrasoundInput)
5911 return true;
5912 }
5913 return false;
5914}
5915
Atneya Nair698f5ef2022-12-15 16:15:09 -08005916bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5917{
5918 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5919 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5920 for (const auto& hwModule : mHwModules) {
5921 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5922 for (const auto &inputProfile : inputProfiles) {
5923 if ((inputProfile->getFlags() & mask) == mask) {
5924 return true;
5925 }
5926 }
5927 }
5928 return false;
5929}
5930
Eric Laurent8340e672019-11-06 11:01:08 -08005931bool AudioPolicyManager::isCallScreenModeSupported()
5932{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005933 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005934}
5935
5936
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005937status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005938{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005939 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005940 if (!sourceDesc->isConnected()) {
5941 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5942 return NO_ERROR;
5943 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005944 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5945 if (swOutput != 0) {
5946 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005947 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005948 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005949 }
jiabinbce0c1d2020-10-05 11:20:18 -07005950 if (releaseOutput(sourceDesc->portId())) {
5951 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5952 // no need to release audio patch here but just return NO_ERROR.
5953 return NO_ERROR;
5954 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005955 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005956 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005957 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005958 // close Hwoutput and remove from mHwOutputs
5959 } else {
5960 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5961 }
5962 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005963 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005964 sourceDesc->disconnect();
5965 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005966}
5967
François Gaffiec005e562018-11-06 15:04:49 +01005968sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5969 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005970{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005971 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005972 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005973 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005974 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005975 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5976 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005977 source = sourceDesc;
5978 break;
5979 }
5980 }
5981 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005982}
5983
Eric Laurentb4f42a92022-01-17 17:37:31 +01005984bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005985 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005986 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005987{
5988 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5989 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005990 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005991 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005992 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5993 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5994 return false;
5995 }
5996 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5997 return false;
5998 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005999 }
6000
Eric Laurentd332bc82023-08-04 11:45:23 +02006001 // The caller can have the audio config criteria ignored by either passing a null ptr or
6002 // the AUDIO_CONFIG_INITIALIZER value.
6003 // If an audio config is specified, current policy is to only allow spatialization for
6004 // some positional channel masks and PCM format
6005
6006 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006007 const bool channel_mask_spatialized =
6008 com_android_media_audio_stereo_spatialization()
6009 ? audio_channel_mask_contains_stereo(config->channel_mask)
6010 : audio_is_channel_mask_spatialized(config->channel_mask);
6011 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006012 return false;
6013 }
6014 if (!audio_is_linear_pcm(config->format)) {
6015 return false;
6016 }
6017 }
6018
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006019 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006020 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006021 if (profile == nullptr) {
6022 return false;
6023 }
6024
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006025 return true;
6026}
6027
6028void AudioPolicyManager::checkVirtualizerClientRoutes() {
6029 std::set<audio_stream_type_t> streamsToInvalidate;
6030 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006031 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6032 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006033 audio_attributes_t attr = client->attributes();
6034 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6035 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6036 audio_config_base_t clientConfig = client->config();
6037 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006038 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006039 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006040 streamsToInvalidate.insert(client->stream());
6041 }
6042 }
6043 }
6044
jiabinc44b3462022-12-08 12:52:31 -08006045 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006046}
6047
Eric Laurente191d1b2022-04-15 11:59:25 +02006048
6049bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6050 const sp<SwAudioOutputDescriptor>& outputDesc) {
6051 if (outputDesc->isDuplicated()) {
6052 return false;
6053 }
6054 DeviceVector devices = outputDesc->supportedDevices();
6055 for (size_t i = 0; i < mOutputs.size(); i++) {
6056 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6057 if (desc == outputDesc || desc->isDuplicated()) {
6058 continue;
6059 }
6060 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6061 if (!sharedDevices.isEmpty()
6062 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6063 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6064 return false;
6065 }
6066 }
6067 return true;
6068}
6069
6070
Eric Laurentfa0f6742021-08-17 18:39:44 +02006071status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006072 const audio_attributes_t *attr,
6073 audio_io_handle_t *output) {
6074 *output = AUDIO_IO_HANDLE_NONE;
6075
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006076 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6077 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6078 audio_config_t *configPtr = nullptr;
6079 audio_config_t config;
6080 if (mixerConfig != nullptr) {
6081 config = audio_config_initializer(mixerConfig);
6082 configPtr = &config;
6083 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006084 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006085 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006086 return BAD_VALUE;
6087 }
6088
6089 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006090 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006091 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006092 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006093 return BAD_VALUE;
6094 }
6095
Eric Laurente191d1b2022-04-15 11:59:25 +02006096 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006097 for (size_t i = 0; i < mOutputs.size(); i++) {
6098 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006099 if (!desc->isDuplicated()
6100 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6101 spatializerOutputs.push_back(desc);
6102 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006103 }
6104 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006105 mSpatializerOutput.clear();
6106 bool outputsChanged = false;
6107 for (const auto& desc : spatializerOutputs) {
6108 if (desc->mProfile == profile
6109 && (configPtr == nullptr
6110 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6111 mSpatializerOutput = desc;
6112 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6113 } else {
6114 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6115 " and devices %s", __func__, desc->mIoHandle,
6116 configPtr != nullptr ? configPtr->channel_mask : 0,
6117 devices.toString().c_str());
6118 closeOutput(desc->mIoHandle);
6119 outputsChanged = true;
6120 }
Eric Laurent39095982021-08-24 18:29:27 +02006121 }
6122
Eric Laurente191d1b2022-04-15 11:59:25 +02006123 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006124 sp<SwAudioOutputDescriptor> desc =
6125 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006126 if (desc != nullptr) {
6127 mSpatializerOutput = desc;
6128 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006129 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006130 }
6131
6132 checkVirtualizerClientRoutes();
6133
Eric Laurente191d1b2022-04-15 11:59:25 +02006134 if (outputsChanged) {
6135 mPreviousOutputs = mOutputs;
6136 mpClientInterface->onAudioPortListUpdate();
6137 }
6138
6139 if (mSpatializerOutput == nullptr) {
6140 ALOGV("%s could not open spatializer output with requested config", __func__);
6141 return BAD_VALUE;
6142 }
Eric Laurent39095982021-08-24 18:29:27 +02006143 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006144 ALOGV("%s returning new spatializer output %d", __func__, *output);
6145 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006146}
6147
Eric Laurentfa0f6742021-08-17 18:39:44 +02006148status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6149 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006150 return INVALID_OPERATION;
6151 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006152 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006153 return BAD_VALUE;
6154 }
Eric Laurent39095982021-08-24 18:29:27 +02006155
Eric Laurente191d1b2022-04-15 11:59:25 +02006156 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6157 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6158 closeOutput(mSpatializerOutput->mIoHandle);
6159 //from now on mSpatializerOutput is null
6160 checkVirtualizerClientRoutes();
6161 }
Eric Laurent39095982021-08-24 18:29:27 +02006162
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006163 return NO_ERROR;
6164}
6165
Eric Laurente552edb2014-03-10 17:42:56 -07006166// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006167// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006168// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006169uint32_t AudioPolicyManager::nextAudioPortGeneration()
6170{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006171 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006172}
6173
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006174AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006175 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006176 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006177 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006178 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006179 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006180 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006181 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006182 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006183 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006184 mAudioPortGeneration(1),
6185 mBeaconMuteRefCount(0),
6186 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006187 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006188 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006189 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006190 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006191{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006192}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006193
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006194status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006195 if (mEngine == nullptr) {
6196 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006197 }
6198 mEngine->setObserver(this);
6199 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006200 if (status != NO_ERROR) {
6201 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6202 return status;
6203 }
François Gaffie2110e042015-03-24 08:41:51 +01006204
jiabin29230182023-04-04 21:02:36 +00006205 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6206 // at the end of this function.
6207 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006208 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6209 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6210
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006211 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006212 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006213 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006214
Eric Laurent3a4311c2014-03-17 12:00:47 -07006215 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006216 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6217 defaultOutputDevice == nullptr ||
6218 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6219 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6220 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006221 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006222 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006223 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006224
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006225 // Silence ALOGV statements
6226 property_set("log.tag." LOG_TAG, "D");
6227
Eric Laurente552edb2014-03-10 17:42:56 -07006228 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006229 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006230}
6231
Eric Laurente0720872014-03-11 09:30:41 -07006232AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006233{
Eric Laurente552edb2014-03-10 17:42:56 -07006234 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006235 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006236 }
6237 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006238 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006239 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006240 mAvailableOutputDevices.clear();
6241 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006242 mOutputs.clear();
6243 mInputs.clear();
6244 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006245 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006246 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006247}
6248
Eric Laurente0720872014-03-11 09:30:41 -07006249status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006250{
Eric Laurent87ffa392015-05-22 10:32:38 -07006251 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006252}
6253
Eric Laurente552edb2014-03-10 17:42:56 -07006254// ---
6255
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006256void AudioPolicyManager::onNewAudioModulesAvailable()
6257{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006258 DeviceVector newDevices;
6259 onNewAudioModulesAvailableInt(&newDevices);
6260 if (!newDevices.empty()) {
6261 nextAudioPortGeneration();
6262 mpClientInterface->onAudioPortListUpdate();
6263 }
6264}
6265
6266void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6267{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006268 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006269 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6270 continue;
6271 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006272 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006273 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6274 handle != AUDIO_MODULE_HANDLE_NONE) {
6275 hwModule->setHandle(handle);
6276 } else {
6277 ALOGW("could not load HW module %s", hwModule->getName());
6278 continue;
6279 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006280 }
6281 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006282 // open all output streams needed to access attached devices.
6283 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006284 // This also validates mAvailableOutputDevices list
6285 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6286 if (!outProfile->canOpenNewIo()) {
6287 ALOGE("Invalid Output profile max open count %u for profile %s",
6288 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6289 continue;
6290 }
6291 if (!outProfile->hasSupportedDevices()) {
6292 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6293 continue;
6294 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006295 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6296 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006297 mTtsOutputAvailable = true;
6298 }
6299
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006300 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006301 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006302 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006303 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6304 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006305 } else {
6306 // choose first device present in profile's SupportedDevices also part of
6307 // mAvailableOutputDevices.
6308 if (availProfileDevices.isEmpty()) {
6309 continue;
6310 }
6311 supportedDevice = availProfileDevices.itemAt(0);
6312 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006313 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006314 continue;
6315 }
6316 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6317 mpClientInterface);
6318 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006319 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6320 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006321 AUDIO_STREAM_DEFAULT,
6322 AUDIO_OUTPUT_FLAG_NONE, &output);
6323 if (status != NO_ERROR) {
6324 ALOGW("Cannot open output stream for devices %s on hw module %s",
6325 supportedDevice->toString().c_str(), hwModule->getName());
6326 continue;
6327 }
6328 for (const auto &device : availProfileDevices) {
6329 // give a valid ID to an attached device once confirmed it is reachable
6330 if (!device->isAttached()) {
6331 device->attach(hwModule);
6332 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006333 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006334 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006335 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6336 }
6337 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006338 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006339 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6340 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006341 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006342 }
Eric Laurent39095982021-08-24 18:29:27 +02006343 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006344 outputDesc->close();
6345 } else {
6346 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306347 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006348 DeviceVector(supportedDevice),
6349 true,
6350 0,
6351 NULL);
6352 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006353 }
6354 // open input streams needed to access attached devices to validate
6355 // mAvailableInputDevices list
6356 for (const auto& inProfile : hwModule->getInputProfiles()) {
6357 if (!inProfile->canOpenNewIo()) {
6358 ALOGE("Invalid Input profile max open count %u for profile %s",
6359 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6360 continue;
6361 }
6362 if (!inProfile->hasSupportedDevices()) {
6363 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6364 continue;
6365 }
6366 // chose first device present in profile's SupportedDevices also part of
6367 // available input devices
6368 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006369 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006370 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006371 ALOGV("%s: Input device list is empty! for profile %s",
6372 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006373 continue;
6374 }
6375 sp<AudioInputDescriptor> inputDesc =
6376 new AudioInputDescriptor(inProfile, mpClientInterface);
6377
6378 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6379 status_t status = inputDesc->open(nullptr,
6380 availProfileDevices.itemAt(0),
6381 AUDIO_SOURCE_MIC,
6382 AUDIO_INPUT_FLAG_NONE,
6383 &input);
6384 if (status != NO_ERROR) {
6385 ALOGW("Cannot open input stream for device %s on hw module %s",
6386 availProfileDevices.toString().c_str(),
6387 hwModule->getName());
6388 continue;
6389 }
6390 for (const auto &device : availProfileDevices) {
6391 // give a valid ID to an attached device once confirmed it is reachable
6392 if (!device->isAttached()) {
6393 device->attach(hwModule);
6394 device->importAudioPortAndPickAudioProfile(inProfile, true);
6395 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006396 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006397 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6398 }
6399 }
6400 inputDesc->close();
6401 }
6402 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006403
6404 // Check if spatializer outputs can be closed until used.
6405 // mOutputs vector never contains duplicated outputs at this point.
6406 std::vector<audio_io_handle_t> outputsClosed;
6407 for (size_t i = 0; i < mOutputs.size(); i++) {
6408 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6409 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6410 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6411 outputsClosed.push_back(desc->mIoHandle);
6412 desc->close();
6413 }
6414 }
6415 for (auto output : outputsClosed) {
6416 removeOutput(output);
6417 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006418}
6419
Eric Laurent98e38192018-02-15 18:31:53 -08006420void AudioPolicyManager::addOutput(audio_io_handle_t output,
6421 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006422{
Eric Laurent1c333e22014-05-20 10:48:17 -07006423 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006424 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006425 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006426 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006427 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006428}
6429
François Gaffie53615e22015-03-19 09:24:12 +01006430void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6431{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006432 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6433 ALOGV("%s: removing primary output", __func__);
6434 mPrimaryOutput = nullptr;
6435 }
François Gaffie53615e22015-03-19 09:24:12 +01006436 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006437 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006438}
6439
Eric Laurent98e38192018-02-15 18:31:53 -08006440void AudioPolicyManager::addInput(audio_io_handle_t input,
6441 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006442{
Eric Laurent1c333e22014-05-20 10:48:17 -07006443 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006444 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006445}
Eric Laurente552edb2014-03-10 17:42:56 -07006446
François Gaffie11d30102018-11-02 16:09:09 +01006447status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006448 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006449 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006450{
François Gaffie11d30102018-11-02 16:09:09 +01006451 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006452 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006453 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006454
François Gaffie11d30102018-11-02 16:09:09 +01006455 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006456 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006457 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006458 }
Eric Laurente552edb2014-03-10 17:42:56 -07006459
Eric Laurent3b73df72014-03-11 09:06:29 -07006460 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006461 // first call getAudioPort to get the supported attributes from the HAL
6462 struct audio_port_v7 port = {};
6463 device->toAudioPort(&port);
6464 status_t status = mpClientInterface->getAudioPort(&port);
6465 if (status == NO_ERROR) {
6466 device->importAudioPort(port);
6467 }
6468
6469 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006470 for (size_t i = 0; i < mOutputs.size(); i++) {
6471 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006472 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006473 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006474 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6475 mOutputs.keyAt(i), device->toString().c_str());
6476 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006477 }
6478 }
6479 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006480 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006481 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006482 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6483 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006484 if (profile->supportsDevice(device)) {
6485 profiles.add(profile);
6486 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6487 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006488 }
6489 }
6490 }
6491
Eric Laurent7b279bb2015-12-14 10:18:23 -08006492 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006493
Eric Laurente552edb2014-03-10 17:42:56 -07006494 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006495 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006496 return BAD_VALUE;
6497 }
6498
6499 // open outputs for matching profiles if needed. Direct outputs are also opened to
6500 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6501 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006502 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006503
6504 // nothing to do if one output is already opened for this profile
6505 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006506 for (j = 0; j < outputs.size(); j++) {
6507 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006508 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006509 // matching profile: save the sample rates, format and channel masks supported
6510 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006511 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006512 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006513 }
Eric Laurente552edb2014-03-10 17:42:56 -07006514 break;
6515 }
6516 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006517 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006518 continue;
6519 }
6520
Eric Laurent3974e3b2017-12-07 17:58:43 -08006521 if (!profile->canOpenNewIo()) {
6522 ALOGW("Max Output number %u already opened for this profile %s",
6523 profile->maxOpenCount, profile->getTagName().c_str());
6524 continue;
6525 }
6526
Eric Laurent83efe1c2017-07-09 16:51:08 -07006527 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006528 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006529 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6530 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006531 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006532 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006533 profiles.removeAt(profile_index);
6534 profile_index--;
6535 } else {
6536 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006537 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006538 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006539 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6540 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006541 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006542 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006543
François Gaffie11d30102018-11-02 16:09:09 +01006544 if (device_distinguishes_on_address(deviceType)) {
6545 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6546 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306547 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6548 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006549 }
Eric Laurente552edb2014-03-10 17:42:56 -07006550 ALOGV("checkOutputsForDevice(): adding output %d", output);
6551 }
6552 }
6553
6554 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006555 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006556 return BAD_VALUE;
6557 }
Eric Laurentd4692962014-05-05 18:13:44 -07006558 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006559 // check if one opened output is not needed any more after disconnecting one device
6560 for (size_t i = 0; i < mOutputs.size(); i++) {
6561 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006562 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006563 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006564 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006565 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006566 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006567 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006568 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6569 mOutputs.keyAt(i));
6570 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006571 }
Eric Laurente552edb2014-03-10 17:42:56 -07006572 }
6573 }
Eric Laurentd4692962014-05-05 18:13:44 -07006574 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006575 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006576 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6577 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006578 if (!profile->supportsDevice(device)) {
6579 continue;
6580 }
6581 ALOGV("checkOutputsForDevice(): "
6582 "clearing direct output profile %zu on module %s",
6583 j, hwModule->getName());
6584 profile->clearAudioProfiles();
6585 if (!profile->hasDynamicAudioProfile()) {
6586 continue;
6587 }
6588 // When a device is disconnected, if there is an IOProfile that contains dynamic
6589 // profiles and supports the disconnected device, call getAudioPort to repopulate
6590 // the capabilities of the devices that is supported by the IOProfile.
6591 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6592 if (supportedDevice == device ||
6593 !mAvailableOutputDevices.contains(supportedDevice)) {
6594 continue;
6595 }
6596 struct audio_port_v7 port;
6597 supportedDevice->toAudioPort(&port);
6598 status_t status = mpClientInterface->getAudioPort(&port);
6599 if (status == NO_ERROR) {
6600 supportedDevice->importAudioPort(port);
6601 }
Eric Laurente552edb2014-03-10 17:42:56 -07006602 }
6603 }
6604 }
6605 }
6606 return NO_ERROR;
6607}
6608
François Gaffie11d30102018-11-02 16:09:09 +01006609status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006610 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006611{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006612 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006613
François Gaffie11d30102018-11-02 16:09:09 +01006614 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006615 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006616 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006617 }
6618
Eric Laurentd4692962014-05-05 18:13:44 -07006619 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006620 // first call getAudioPort to get the supported attributes from the HAL
6621 struct audio_port_v7 port = {};
6622 device->toAudioPort(&port);
6623 status_t status = mpClientInterface->getAudioPort(&port);
6624 if (status == NO_ERROR) {
6625 device->importAudioPort(port);
6626 }
6627
Eric Laurent0dd51852019-04-19 18:18:58 -07006628 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006629 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006630 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006631 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006632 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006633 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006634 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006635
François Gaffie11d30102018-11-02 16:09:09 +01006636 if (profile->supportsDevice(device)) {
6637 profiles.add(profile);
6638 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6639 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006640 }
6641 }
6642 }
6643
Eric Laurent0dd51852019-04-19 18:18:58 -07006644 if (profiles.isEmpty()) {
6645 ALOGW("%s: No input profile available for device %s",
6646 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006647 return BAD_VALUE;
6648 }
6649
6650 // open inputs for matching profiles if needed. Direct inputs are also opened to
6651 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6652 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6653
Eric Laurent1c333e22014-05-20 10:48:17 -07006654 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006655
Eric Laurentd4692962014-05-05 18:13:44 -07006656 // nothing to do if one input is already opened for this profile
6657 size_t input_index;
6658 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6659 desc = mInputs.valueAt(input_index);
6660 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006661 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006662 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006663 }
Eric Laurentd4692962014-05-05 18:13:44 -07006664 break;
6665 }
6666 }
6667 if (input_index != mInputs.size()) {
6668 continue;
6669 }
6670
Eric Laurent3974e3b2017-12-07 17:58:43 -08006671 if (!profile->canOpenNewIo()) {
6672 ALOGW("Max Input number %u already opened for this profile %s",
6673 profile->maxOpenCount, profile->getTagName().c_str());
6674 continue;
6675 }
6676
Eric Laurentfe231122017-11-17 17:48:06 -08006677 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006678 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006679 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006680
Eric Laurentcf2c0212014-07-25 16:20:43 -07006681 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006682 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006683 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006684 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006685 mpClientInterface->setParameters(input, String8(param));
6686 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006687 }
jiabin12537fc2023-10-12 17:56:08 +00006688 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006689 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006690 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006691 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006692 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006693 }
6694
Eric Laurent0dd51852019-04-19 18:18:58 -07006695 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006696 addInput(input, desc);
6697 }
6698 } // endif input != 0
6699
Eric Laurentcf2c0212014-07-25 16:20:43 -07006700 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006701 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006702 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006703 profiles.removeAt(profile_index);
6704 profile_index--;
6705 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006706 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006707 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006708 }
Eric Laurentd4692962014-05-05 18:13:44 -07006709 ALOGV("checkInputsForDevice(): adding input %d", input);
6710 }
6711 } // end scan profiles
6712
6713 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006714 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006715 return BAD_VALUE;
6716 }
6717 } else {
6718 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006719 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006720 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006721 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006722 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006723 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006724 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006725 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006726 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6727 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006728 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006729 }
6730 }
6731 }
6732 } // end disconnect
6733
6734 return NO_ERROR;
6735}
6736
6737
Eric Laurente0720872014-03-11 09:30:41 -07006738void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006739{
6740 ALOGV("closeOutput(%d)", output);
6741
François Gaffie1c878552018-11-22 16:53:21 +01006742 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6743 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006744 ALOGW("closeOutput() unknown output %d", output);
6745 return;
6746 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006747 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006748 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006749
Eric Laurente552edb2014-03-10 17:42:56 -07006750 // look for duplicated outputs connected to the output being removed.
6751 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006752 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6753 if (dupOutput->isDuplicated() &&
6754 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6755 sp<SwAudioOutputDescriptor> remainingOutput =
6756 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006757 // As all active tracks on duplicated output will be deleted,
6758 // and as they were also referenced on the other output, the reference
6759 // count for their stream type must be adjusted accordingly on
6760 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006761 const bool wasActive = remainingOutput->isActive();
6762 // Note: no-op on the closing output where all clients has already been set inactive
6763 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006764 // stop() will be a no op if the output is still active but is needed in case all
6765 // active streams refcounts where cleared above
6766 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006767 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006768 }
Eric Laurente552edb2014-03-10 17:42:56 -07006769 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6770 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6771
6772 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006773 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006774 }
6775 }
6776
Eric Laurent05b90f82014-08-27 15:32:29 -07006777 nextAudioPortGeneration();
6778
François Gaffie1c878552018-11-22 16:53:21 +01006779 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006780 if (index >= 0) {
6781 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006782 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6783 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006784 mAudioPatches.removeItemsAt(index);
6785 mpClientInterface->onAudioPatchListUpdate();
6786 }
6787
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006788 if (closingOutputWasActive) {
6789 closingOutput->stop();
6790 }
François Gaffie1c878552018-11-22 16:53:21 +01006791 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006792 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6793 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6794 for (const auto device : closingOutput->devices()) {
6795 device->setPreferredConfig(nullptr);
6796 }
6797 }
Eric Laurente552edb2014-03-10 17:42:56 -07006798
François Gaffie53615e22015-03-19 09:24:12 +01006799 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006800 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006801 if (closingOutput == mSpatializerOutput) {
6802 mSpatializerOutput.clear();
6803 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006804
6805 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6806 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006807 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006808 bool directOutputOpen = false;
6809 for (size_t i = 0; i < mOutputs.size(); i++) {
6810 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6811 directOutputOpen = true;
6812 break;
6813 }
6814 }
6815 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006816 ALOGV("no direct outputs open, reset MSD patches");
6817 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6818 // how output devices for patching are resolved. Avoid by caching and reusing the
6819 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6820 // devices to patch to. This may be complicated by the fact that devices may become
6821 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006822 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006823 }
6824 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006825}
6826
6827void AudioPolicyManager::closeInput(audio_io_handle_t input)
6828{
6829 ALOGV("closeInput(%d)", input);
6830
6831 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6832 if (inputDesc == NULL) {
6833 ALOGW("closeInput() unknown input %d", input);
6834 return;
6835 }
6836
Eric Laurent6a94d692014-05-20 11:18:06 -07006837 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006838
François Gaffie11d30102018-11-02 16:09:09 +01006839 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006840 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006841 if (index >= 0) {
6842 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006843 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6844 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006845 mAudioPatches.removeItemsAt(index);
6846 mpClientInterface->onAudioPatchListUpdate();
6847 }
6848
François Gaffie6ebbce02023-07-19 13:27:53 +02006849 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006850 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006851 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006852
François Gaffie11d30102018-11-02 16:09:09 +01006853 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6854 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006855 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006856 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006857 }
Eric Laurente552edb2014-03-10 17:42:56 -07006858}
6859
François Gaffie11d30102018-11-02 16:09:09 +01006860SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6861 const DeviceVector &devices,
6862 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006863{
6864 SortedVector<audio_io_handle_t> outputs;
6865
François Gaffie11d30102018-11-02 16:09:09 +01006866 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006867 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006868 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006869 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006870 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006871 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006872 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006873 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006874 outputs.add(openOutputs.keyAt(i));
6875 }
6876 }
6877 return outputs;
6878}
6879
Mikhail Naganov37977152018-07-11 15:54:44 -07006880void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6881{
6882 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6883 // output is suspended before any tracks are moved to it
6884 checkA2dpSuspend();
6885 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006886 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006887 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006888 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006889 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006890 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6891 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6892 // configuration changes will ultimately be rerouted correctly. We can still avoid
6893 // unnecessary rerouting by caching and reusing the arguments to
6894 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6895 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006896 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006897 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006898 // an event that changed routing likely occurred, inform upper layers
6899 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006900}
6901
François Gaffiec005e562018-11-06 15:04:49 +01006902bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6903 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006904{
François Gaffiec005e562018-11-06 15:04:49 +01006905 return mEngine->getProductStrategyForAttributes(lAttr) ==
6906 mEngine->getProductStrategyForAttributes(rAttr);
6907}
6908
Francois Gaffieff1eb522020-05-06 18:37:04 +02006909void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6910{
6911 for (size_t i = 0; i < mAudioSources.size(); i++) {
6912 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6913 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006914 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006915 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006916 connectAudioSource(sourceDesc);
6917 }
6918 }
6919}
6920
6921void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6922{
6923 for (size_t i = 0; i < mAudioSources.size(); i++) {
6924 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6925 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6926 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6927 disconnectAudioSource(sourceDesc);
6928 }
6929 }
6930}
6931
François Gaffiec005e562018-11-06 15:04:49 +01006932void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6933{
6934 auto psId = mEngine->getProductStrategyForAttributes(attr);
6935
6936 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6937 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006938
François Gaffie11d30102018-11-02 16:09:09 +01006939 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6940 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006941
Eric Laurentc209fe42020-06-05 18:11:23 -07006942 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006943 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006944 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006945 // take into account dynamic audio policies related changes: if a client is now associated
6946 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006947 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006948 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6949 if (desc->isDuplicated()) {
6950 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006951 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006952 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6953 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6954 continue;
6955 }
6956 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006957 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006958 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6959 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6960 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006961 if (status != OK) {
6962 continue;
6963 }
yucliuf4de36d2020-09-14 14:57:56 -07006964 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006965 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006966 maxLatency = desc->latency();
6967 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006968 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006969 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006970 }
6971 }
6972
Eric Laurent56ed8842022-11-15 16:04:41 +01006973 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006974 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6975 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006976 for (audio_io_handle_t srcOut : srcOutputs) {
6977 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006978 if (desc == nullptr) continue;
6979
6980 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006981 maxLatency = desc->latency();
6982 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006983
Eric Laurent56ed8842022-11-15 16:04:41 +01006984 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006985 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006986 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006987 // a client on a non direct outputs has necessarily a linear PCM format
6988 // so we can call selectOutput() safely
6989 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6990 client->flags(),
6991 client->config().format,
6992 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006993 client->config().sample_rate,
6994 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006995 if (newOutput != srcOut) {
6996 invalidate = true;
6997 break;
6998 }
6999 } else {
7000 sp<IOProfile> profile = getProfileForOutput(newDevices,
7001 client->config().sample_rate,
7002 client->config().format,
7003 client->config().channel_mask,
7004 client->flags(),
7005 true /* directOnly */);
7006 if (profile != desc->mProfile) {
7007 invalidate = true;
7008 break;
7009 }
7010 }
7011 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007012 // mute strategy while moving tracks from one output to another
7013 if (invalidate) {
7014 invalidatedOutputs.push_back(desc);
7015 if (desc->isStrategyActive(psId)) {
7016 setStrategyMute(psId, true, desc);
7017 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7018 newDevices.types());
7019 }
Eric Laurente552edb2014-03-10 17:42:56 -07007020 }
François Gaffiec005e562018-11-06 15:04:49 +01007021 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007022 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007023 connectAudioSource(source);
7024 }
Eric Laurente552edb2014-03-10 17:42:56 -07007025 }
7026
Eric Laurent56ed8842022-11-15 16:04:41 +01007027 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7028 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7029 std::to_string(srcOutputs[0]).c_str(),
7030 std::to_string(dstOutputs[0]).c_str());
7031
François Gaffiec005e562018-11-06 15:04:49 +01007032 // Move effects associated to this stream from previous output to new output
7033 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007034 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007035 }
François Gaffiec005e562018-11-06 15:04:49 +01007036 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007037 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007038 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007039 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007040 desc->setTracksInvalidatedStatusByStrategy(psId);
7041 }
Eric Laurente552edb2014-03-10 17:42:56 -07007042 }
7043 }
7044}
7045
Eric Laurente0720872014-03-11 09:30:41 -07007046void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007047{
François Gaffiec005e562018-11-06 15:04:49 +01007048 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7049 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7050 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007051 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007052 }
Eric Laurente552edb2014-03-10 17:42:56 -07007053}
7054
Kevin Rocard153f92d2018-12-18 18:33:28 -08007055void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007056 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007057 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007058 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007059 for (size_t i = 0; i < mOutputs.size(); i++) {
7060 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7061 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007062 sp<AudioPolicyMix> primaryMix;
7063 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007064 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007065 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7066 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7067 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007068 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7069 for (auto &secondaryMix : secondaryMixes) {
7070 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7071 if (outputDesc != nullptr &&
7072 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7073 secondaryDescs.push_back(outputDesc);
7074 }
7075 }
7076
jiabinc44b3462022-12-08 12:52:31 -08007077 if (status != OK &&
7078 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7079 // When it failed to query secondary output, only invalidate the client that is not
7080 // MMAP. The reason is that MMAP stream will not support secondary output.
7081 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007082 } else if (!std::equal(
7083 client->getSecondaryOutputs().begin(),
7084 client->getSecondaryOutputs().end(),
7085 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007086 if (!audio_is_linear_pcm(client->config().format)) {
7087 // If the format is not PCM, the tracks should be invalidated to get correct
7088 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007089 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007090 } else {
7091 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7092 std::vector<audio_io_handle_t> secondaryOutputIds;
7093 for (const auto &secondaryDesc: secondaryDescs) {
7094 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7095 weakSecondaryDescs.push_back(secondaryDesc);
7096 }
7097 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7098 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007099 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007100 }
7101 }
7102 }
jiabin10a03f12021-05-07 23:46:28 +00007103 if (!trackSecondaryOutputs.empty()) {
7104 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7105 }
jiabinc44b3462022-12-08 12:52:31 -08007106 if (!clientsToInvalidate.empty()) {
7107 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7108 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007109 }
7110}
7111
Eric Laurent2517af32020-11-25 15:31:27 +01007112bool AudioPolicyManager::isScoRequestedForComm() const {
7113 AudioDeviceTypeAddrVector devices;
7114 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7115 for (const auto &device : devices) {
7116 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7117 return true;
7118 }
7119 }
7120 return false;
7121}
7122
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007123bool AudioPolicyManager::isHearingAidUsedForComm() const {
7124 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7125 true /*fromCache*/);
7126 for (const auto &device : devices) {
7127 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7128 return true;
7129 }
7130 }
7131 return false;
7132}
7133
7134
Eric Laurente0720872014-03-11 09:30:41 -07007135void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007136{
François Gaffie53615e22015-03-19 09:24:12 +01007137 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007138 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007139 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007140 return;
7141 }
7142
Eric Laurent3a4311c2014-03-17 12:00:47 -07007143 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007144 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7145 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007146 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007147
7148 // if suspended, restore A2DP output if:
7149 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007150 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007151 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007152 //
Eric Laurentf732e072016-08-03 19:30:28 -07007153 // if not suspended, suspend A2DP output if:
7154 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007155 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007156 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007157 //
7158 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007159 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007160 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007161 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007162 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007163
7164 mpClientInterface->restoreOutput(a2dpOutput);
7165 mA2dpSuspended = false;
7166 }
7167 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007168 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007169 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007170 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007171 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007172
7173 mpClientInterface->suspendOutput(a2dpOutput);
7174 mA2dpSuspended = true;
7175 }
7176 }
7177}
7178
François Gaffie11d30102018-11-02 16:09:09 +01007179DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7180 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007181{
François Gaffiedb1755b2023-09-01 11:50:35 +02007182 if (outputDesc == nullptr) {
7183 return DeviceVector{};
7184 }
François Gaffie11d30102018-11-02 16:09:09 +01007185
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007186 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007187 if (index >= 0) {
7188 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007189 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007190 ALOGV("%s device %s forced by patch %d", __func__,
7191 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7192 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007193 }
7194 }
7195
Dean Wheatley514b4312020-06-17 21:45:00 +10007196 // Do not retrieve engine device for outputs through MSD
7197 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7198 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7199 return outputDesc->devices();
7200 }
7201
Eric Laurent97ac8712018-07-27 18:59:02 -07007202 // Honor explicit routing requests only if no client using default routing is active on this
7203 // input: a specific app can not force routing for other apps by setting a preferred device.
7204 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007205 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007206 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007207 if (device != nullptr) {
7208 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007209 }
7210
François Gaffiea807ef92018-11-05 10:44:33 +01007211 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7212 // of setForceUse / Default Bus device here
7213 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7214 if (device != nullptr) {
7215 return DeviceVector(device);
7216 }
7217
François Gaffiedb1755b2023-09-01 11:50:35 +02007218 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007219 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7220 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7221 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307222 auto hasStreamActive = [&](auto stream) {
7223 return hasStream(streams, stream) && isStreamActive(stream, 0);
7224 };
Eric Laurent484e9272018-06-07 17:29:23 -07007225
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307226 auto doGetOutputDevicesForVoice = [&]() {
7227 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007228 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307229 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007230 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7231 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307232 };
7233
7234 // With low-latency playing on speaker, music on WFD, when the first low-latency
7235 // output is stopped, getNewOutputDevices checks for a product strategy
7236 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007237 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307238 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7239 // stream is associated to the output descriptor.
7240 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7241 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7242 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7243 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007244 // Retrieval of devices for voice DL is done on primary output profile, cannot
7245 // check the route (would force modifying configuration file for this profile)
7246 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7247 break;
7248 }
Eric Laurente552edb2014-03-10 17:42:56 -07007249 }
François Gaffiec005e562018-11-06 15:04:49 +01007250 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007251 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007252}
7253
François Gaffie11d30102018-11-02 16:09:09 +01007254sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7255 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007256{
François Gaffie11d30102018-11-02 16:09:09 +01007257 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007258
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007259 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007260 if (index >= 0) {
7261 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007262 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007263 ALOGV("getNewInputDevice() device %s forced by patch %d",
7264 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7265 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007266 }
7267 }
7268
Eric Laurent97ac8712018-07-27 18:59:02 -07007269 // Honor explicit routing requests only if no client using default routing is active on this
7270 // input: a specific app can not force routing for other apps by setting a preferred device.
7271 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007272 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7273 if (device != nullptr) {
7274 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007275 }
7276
Eric Laurentdc95a252018-04-12 12:46:56 -07007277 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007278 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007279 audio_attributes_t attributes;
7280 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007281 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007282 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7283 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007284 attributes = topClient->attributes();
7285 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007286 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007287 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007288 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7289 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007290 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007291 }
7292
Francois Gaffie716e1432019-01-14 16:58:59 +01007293 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7294 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007295 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007296 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007297 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007298 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007299
Eric Laurente552edb2014-03-10 17:42:56 -07007300 return device;
7301}
7302
Eric Laurent794fde22016-03-11 09:50:45 -08007303bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7304 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007305 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007306}
7307
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007308status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007309 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007310 if (devices == nullptr) {
7311 return BAD_VALUE;
7312 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007313
Andy Hung6d23c0f2022-02-16 09:37:15 -08007314 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007315 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7316 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007317 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007318 for (const auto& device : curDevices) {
7319 devices->push_back(device->getDeviceTypeAddr());
7320 }
7321 return NO_ERROR;
7322}
7323
Eric Laurente0720872014-03-11 09:30:41 -07007324void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007325 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007326 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007327 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007328 updateDevicesAndOutputs();
7329 break;
7330 default:
7331 break;
7332 }
7333}
7334
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007335uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007336
7337 // skip beacon mute management if a dedicated TTS output is available
7338 if (mTtsOutputAvailable) {
7339 return 0;
7340 }
7341
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007342 switch(event) {
7343 case STARTING_OUTPUT:
7344 mBeaconMuteRefCount++;
7345 break;
7346 case STOPPING_OUTPUT:
7347 if (mBeaconMuteRefCount > 0) {
7348 mBeaconMuteRefCount--;
7349 }
7350 break;
7351 case STARTING_BEACON:
7352 mBeaconPlayingRefCount++;
7353 break;
7354 case STOPPING_BEACON:
7355 if (mBeaconPlayingRefCount > 0) {
7356 mBeaconPlayingRefCount--;
7357 }
7358 break;
7359 }
7360
7361 if (mBeaconMuteRefCount > 0) {
7362 // any playback causes beacon to be muted
7363 return setBeaconMute(true);
7364 } else {
7365 // no other playback: unmute when beacon starts playing, mute when it stops
7366 return setBeaconMute(mBeaconPlayingRefCount == 0);
7367 }
7368}
7369
7370uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7371 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7372 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7373 // keep track of muted state to avoid repeating mute/unmute operations
7374 if (mBeaconMuted != mute) {
7375 // mute/unmute AUDIO_STREAM_TTS on all outputs
7376 ALOGV("\t muting %d", mute);
7377 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007378 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7379 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7380 ALOGV("\t no tts volume source available");
7381 return 0;
7382 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007383 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007384 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007385 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007386 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007387 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007388 maxLatency = latency;
7389 }
7390 }
7391 mBeaconMuted = mute;
7392 return maxLatency;
7393 }
7394 return 0;
7395}
7396
Eric Laurente0720872014-03-11 09:30:41 -07007397void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007398{
François Gaffiec005e562018-11-06 15:04:49 +01007399 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007400 mPreviousOutputs = mOutputs;
7401}
7402
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007403uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007404 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007405 uint32_t delayMs)
7406{
7407 // mute/unmute strategies using an incompatible device combination
7408 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7409 // if unmuting, unmute only after the specified delay
7410 if (outputDesc->isDuplicated()) {
7411 return 0;
7412 }
7413
7414 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007415 DeviceVector devices = outputDesc->devices();
7416 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007417
François Gaffiec005e562018-11-06 15:04:49 +01007418 auto productStrategies = mEngine->getOrderedProductStrategies();
7419 for (const auto &productStrategy : productStrategies) {
7420 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7421 DeviceVector curDevices =
7422 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7423 curDevices = curDevices.filter(outputDesc->supportedDevices());
7424 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007425 bool doMute = false;
7426
François Gaffiec005e562018-11-06 15:04:49 +01007427 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007428 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007429 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7430 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007431 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007432 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007433 }
Eric Laurent99401132014-05-07 19:48:15 -07007434 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007435 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007436 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007437 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007438 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007439 continue;
7440 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307441 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007442 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7443 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7444 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007445 if (mute) {
7446 // FIXME: should not need to double latency if volume could be applied
7447 // immediately by the audioflinger mixer. We must account for the delay
7448 // between now and the next time the audioflinger thread for this output
7449 // will process a buffer (which corresponds to one buffer size,
7450 // usually 1/2 or 1/4 of the latency).
7451 if (muteWaitMs < desc->latency() * 2) {
7452 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007453 }
7454 }
7455 }
7456 }
7457 }
7458 }
7459
Eric Laurent99401132014-05-07 19:48:15 -07007460 // temporary mute output if device selection changes to avoid volume bursts due to
7461 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007462 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007463 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007464
Eric Laurentdc462862016-07-19 12:29:53 -07007465 if (muteWaitMs < tempMuteWaitMs) {
7466 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007467 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007468
7469 // If recommended duration is defined, replace temporary mute duration to avoid
7470 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7471 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7472 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7473 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7474 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7475
François Gaffieaaac0fd2018-11-22 17:56:39 +01007476 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7477 // make sure that we do not start the temporary mute period too early in case of
7478 // delayed device change
7479 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7480 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007481 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007482 }
7483 }
7484
Eric Laurente552edb2014-03-10 17:42:56 -07007485 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7486 if (muteWaitMs > delayMs) {
7487 muteWaitMs -= delayMs;
7488 usleep(muteWaitMs * 1000);
7489 return muteWaitMs;
7490 }
7491 return 0;
7492}
7493
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307494uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7495 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007496 const DeviceVector &devices,
7497 bool force,
7498 int delayMs,
7499 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007500 bool requiresMuteCheck, bool requiresVolumeCheck,
7501 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007502{
jiabin3ff8d7d2022-12-13 06:27:44 +00007503 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307504 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7505 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7506 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007507 uint32_t muteWaitMs;
7508
7509 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307510 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007511 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307512 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007513 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007514 return muteWaitMs;
7515 }
Eric Laurente552edb2014-03-10 17:42:56 -07007516
7517 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007518 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007519 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007520 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007521
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307522 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7523 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007524
7525 if (!filteredDevices.isEmpty()) {
7526 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007527 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007528
7529 // if the outputs are not materially active, there is no need to mute.
7530 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007531 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007532 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307533 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7534 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007535 muteWaitMs = 0;
7536 }
Eric Laurente552edb2014-03-10 17:42:56 -07007537
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007538 bool outputRouted = outputDesc->isRouted();
7539
Eric Laurent79ea9582020-06-11 18:49:24 -07007540 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7541 // output profile or if new device is not supported AND previous device(s) is(are) still
7542 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007543 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307544 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7545 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007546 // restore previous device after evaluating strategy mute state
7547 outputDesc->setDevices(prevDevices);
7548 return muteWaitMs;
7549 }
7550
Eric Laurente552edb2014-03-10 17:42:56 -07007551 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007552 // the requested device is AUDIO_DEVICE_NONE
7553 // OR the requested device is the same as current device
7554 // AND force is not specified
7555 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007556 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007557 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307558 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7559 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7560 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007561 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307562 ALOGV("%s %s setting same device on routed output, force apply volumes",
7563 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007564 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7565 }
Eric Laurente552edb2014-03-10 17:42:56 -07007566 return muteWaitMs;
7567 }
7568
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307569 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7570 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007571
Eric Laurente552edb2014-03-10 17:42:56 -07007572 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007573 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007574 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007575 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007576 PatchBuilder patchBuilder;
7577 patchBuilder.addSource(outputDesc);
7578 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7579 for (const auto &filteredDevice : filteredDevices) {
7580 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007581 }
7582
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007583 // Add half reported latency to delayMs when muteWaitMs is null in order
7584 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007585 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7586 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7587 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007588 }
Eric Laurente552edb2014-03-10 17:42:56 -07007589
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007590 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7591 if (!skipMuteDelay) {
7592 // update stream volumes according to new device
7593 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7594 }
Eric Laurente552edb2014-03-10 17:42:56 -07007595
7596 return muteWaitMs;
7597}
7598
Eric Laurentc75307b2015-03-17 15:29:32 -07007599status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007600 int delayMs,
7601 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007602{
Eric Laurent6a94d692014-05-20 11:18:06 -07007603 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007604 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7605 return INVALID_OPERATION;
7606 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007607 if (patchHandle) {
7608 index = mAudioPatches.indexOfKey(*patchHandle);
7609 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007610 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007611 }
7612 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007613 return INVALID_OPERATION;
7614 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007615 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007616 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007617 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007618 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007619 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007620 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007621 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007622 return status;
7623}
7624
7625status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007626 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007627 bool force,
7628 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007629{
7630 status_t status = NO_ERROR;
7631
Eric Laurent1f2f2232014-06-02 12:01:23 -07007632 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007633 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7634 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007635
François Gaffie11d30102018-11-02 16:09:09 +01007636 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007637 PatchBuilder patchBuilder;
7638 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007639 // AUDIO_SOURCE_HOTWORD is for internal use only:
7640 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007641 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7642 auto result = usecase;
7643 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7644 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7645 }
7646 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007647 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007648 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007649 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007650 }
7651 }
7652 return status;
7653}
7654
Eric Laurent6a94d692014-05-20 11:18:06 -07007655status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7656 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007657{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007658 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007659 ssize_t index;
7660 if (patchHandle) {
7661 index = mAudioPatches.indexOfKey(*patchHandle);
7662 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007663 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007664 }
7665 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007666 return INVALID_OPERATION;
7667 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007668 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007669 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007670 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007671 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007672 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007673 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007674 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007675 return status;
7676}
7677
François Gaffie11d30102018-11-02 16:09:09 +01007678sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007679 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007680 audio_format_t& format,
7681 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007682 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007683{
7684 // Choose an input profile based on the requested capture parameters: select the first available
7685 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007686 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007687 //
7688 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7689 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007690
Atneya Nair0f0a8032022-12-12 16:20:12 -08007691 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7692 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7693 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7694
7695 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007696
jiabin2fd710d2022-05-02 23:20:22 +00007697 for (;;) {
7698 sp<IOProfile> firstInexact = nullptr;
7699 uint32_t updatedSamplingRate = 0;
7700 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7701 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7702 for (const auto& hwModule : mHwModules) {
7703 for (const auto& profile : hwModule->getInputProfiles()) {
7704 // profile->log();
7705 //updatedFormat = format;
7706 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7707 &samplingRate /*updatedSamplingRate*/,
7708 format,
7709 &format, /*updatedFormat*/
7710 channelMask,
7711 &channelMask /*updatedChannelMask*/,
7712 // FIXME ugly cast
7713 (audio_output_flags_t) flags,
7714 true /*exactMatchRequiredForInputFlags*/)) {
7715 return profile;
7716 }
7717 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7718 samplingRate,
7719 &updatedSamplingRate,
7720 format,
7721 &updatedFormat,
7722 channelMask,
7723 &updatedChannelMask,
7724 // FIXME ugly cast
7725 (audio_output_flags_t) flags,
7726 false /*exactMatchRequiredForInputFlags*/)) {
7727 firstInexact = profile;
7728 }
7729 }
7730 }
7731
7732 if (firstInexact != nullptr) {
7733 samplingRate = updatedSamplingRate;
7734 format = updatedFormat;
7735 channelMask = updatedChannelMask;
7736 return firstInexact;
7737 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7738 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7739 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7740 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7741 flags = AUDIO_INPUT_FLAG_NONE;
7742 } else { // fail
7743 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7744 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7745 samplingRate, format, channelMask, oriFlags);
7746 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007747 }
7748 }
jiabin2fd710d2022-05-02 23:20:22 +00007749
7750 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007751}
7752
François Gaffieaaac0fd2018-11-22 17:56:39 +01007753float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7754 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007755 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007756 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007757{
jiabin9a3361e2019-10-01 09:38:30 -07007758 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007759
7760 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7761 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7762 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7763 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007764 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7765 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7766 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7767 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7768 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007769 // Verify that the current volume source is not the ringer volume to prevent recursively
7770 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7771 // to the same volume group.
7772 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007773 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7774 mOutputs.isActive(ringVolumeSrc, 0)) {
7775 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007776 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007777 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007778 }
7779
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007780 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007781 if ((volumeSource != callVolumeSrc && (isInCall() ||
7782 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007783 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007784 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7785 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007786 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7787 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7788 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007789 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007790 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007791 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007792 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007793 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007794 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007795 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7796 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7797 // programmatically muted.
7798 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7799 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7800 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007801 bool exemptFromCapping =
7802 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7803 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007804 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7805 volumeSource, volumeDb);
7806 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007807 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7808 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7809 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007810 }
7811 }
Eric Laurente552edb2014-03-10 17:42:56 -07007812 // if a headset is connected, apply the following rules to ring tones and notifications
7813 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007814 // - always attenuate notifications volume by 6dB
7815 // - attenuate ring tones volume by 6dB unless music is not playing and
7816 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007817 // - if music is playing, always limit the volume to current music volume,
7818 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007819 if (!Intersection(deviceTypes,
7820 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7821 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007822 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7823 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007824 ((volumeSource == alarmVolumeSrc ||
7825 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007826 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7827 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7828 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007829 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7830 curves.canBeMuted()) {
7831
Eric Laurente552edb2014-03-10 17:42:56 -07007832 // when the phone is ringing we must consider that music could have been paused just before
7833 // by the music application and behave as if music was active if the last music track was
7834 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007835 // Verify that the current volume source is not the music volume to prevent recursively
7836 // calling to compute volume. This could happen in cases where music and
7837 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7838 if (volumeSource != musicVolumeSrc &&
7839 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7840 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007841 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007842 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007843 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7844 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007845 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007846 float musicVolDb = computeVolume(musicCurves,
7847 musicVolumeSrc,
7848 musicCurves.getVolumeIndex(musicDevice),
7849 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007850 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7851 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7852 if (volumeDb > minVolDb) {
7853 volumeDb = minVolDb;
7854 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007855 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007856 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7857 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7858 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007859 // on A2DP, also ensure notification volume is not too low compared to media when
7860 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007861 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007862 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007863 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7864 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007865 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7866 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007867 }
7868 }
jiabin9a3361e2019-10-01 09:38:30 -07007869 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007870 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007871 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007872 }
7873 }
7874
François Gaffie43c73442018-11-08 08:21:55 +01007875 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007876}
7877
Eric Laurent3839bc02018-07-10 18:33:34 -07007878int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007879 VolumeSource fromVolumeSource,
7880 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007881{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007882 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007883 return srcIndex;
7884 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007885 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7886 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007887 float minSrc = (float)srcCurves.getVolumeIndexMin();
7888 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7889 float minDst = (float)dstCurves.getVolumeIndexMin();
7890 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007891
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007892 // preserve mute request or correct range
7893 if (srcIndex < minSrc) {
7894 if (srcIndex == 0) {
7895 return 0;
7896 }
7897 srcIndex = minSrc;
7898 } else if (srcIndex > maxSrc) {
7899 srcIndex = maxSrc;
7900 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007901 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7902}
7903
François Gaffieaaac0fd2018-11-22 17:56:39 +01007904status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7905 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007906 int index,
7907 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007908 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007909 int delayMs,
7910 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007911{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007912 // do not change actual attributes volume if the attributes is muted
7913 if (outputDesc->isMuted(volumeSource)) {
7914 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7915 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007916 return NO_ERROR;
7917 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007918
Eric Laurentae6e88c2024-01-10 14:42:57 +01007919 bool isVoiceVolSrc;
7920 bool isBtScoVolSrc;
7921 if (!isVolumeConsistentForCalls(
7922 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07007923 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01007924 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07007925 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007926 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01007927
jiabin9a3361e2019-10-01 09:38:30 -07007928 if (deviceTypes.empty()) {
7929 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007930 index = curves.getVolumeIndex(deviceTypes);
7931 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7932 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007933 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007934
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007935 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7936 ALOGE("invalid volume index range");
7937 return BAD_VALUE;
7938 }
7939
jiabin9a3361e2019-10-01 09:38:30 -07007940 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7941 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007942 // Force VoIP volume to max for bluetooth SCO device except if muted
7943 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007944 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007945 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007946 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007947 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007948 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7949 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007950
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007951 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01007952 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007953 }
Eric Laurente552edb2014-03-10 17:42:56 -07007954 return NO_ERROR;
7955}
7956
Eric Laurentae6e88c2024-01-10 14:42:57 +01007957void AudioPolicyManager::setVoiceVolume(
7958 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
7959 float voiceVolume;
7960 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
7961 // by the headset
7962 if (isVoiceVolSrc) {
7963 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
7964 } else {
7965 voiceVolume = index == 0 ? 0.0 : 1.0;
7966 }
7967 if (voiceVolume != mLastVoiceVolume) {
7968 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7969 mLastVoiceVolume = voiceVolume;
7970 }
7971}
7972
7973bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
7974 const DeviceTypeSet& deviceTypes,
7975 bool& isVoiceVolSrc,
7976 bool& isBtScoVolSrc,
7977 const char* caller) {
7978 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7979 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7980 const bool isScoRequested = isScoRequestedForComm();
7981 const bool isHAUsed = isHearingAidUsedForComm();
7982
7983 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7984 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
7985
7986 if ((callVolSrc != btScoVolSrc) &&
7987 ((isVoiceVolSrc && isScoRequested) ||
7988 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7989 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
7990 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
7991 volumeSource, isScoRequested ? " " : " not ");
7992 return false;
7993 }
7994 return true;
7995}
7996
Eric Laurentc75307b2015-03-17 15:29:32 -07007997void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007998 const DeviceTypeSet& deviceTypes,
7999 int delayMs,
8000 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008001{
jiabincd510522020-01-22 09:40:55 -08008002 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008003 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8004 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8005 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008006 curves.getVolumeIndex(deviceTypes),
8007 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008008 }
8009}
8010
François Gaffiec005e562018-11-06 15:04:49 +01008011void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8012 bool on,
8013 const sp<AudioOutputDescriptor>& outputDesc,
8014 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008015 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008016{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008017 std::vector<VolumeSource> sourcesToMute;
8018 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8019 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8020 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008021 VolumeSource source = toVolumeSource(attributes, false);
8022 if ((source != VOLUME_SOURCE_NONE) &&
8023 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8024 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008025 sourcesToMute.push_back(source);
8026 }
Eric Laurente552edb2014-03-10 17:42:56 -07008027 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008028 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008029 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008030 }
8031
Eric Laurente552edb2014-03-10 17:42:56 -07008032}
8033
François Gaffieaaac0fd2018-11-22 17:56:39 +01008034void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8035 bool on,
8036 const sp<AudioOutputDescriptor>& outputDesc,
8037 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008038 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008039{
jiabin9a3361e2019-10-01 09:38:30 -07008040 if (deviceTypes.empty()) {
8041 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008042 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008043 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008044 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008045 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008046 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008047 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008048 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8049 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008050 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008051 }
8052 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008053 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8054 // ignored
8055 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008056 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008057 if (!outputDesc->isMuted(volumeSource)) {
8058 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008059 return;
8060 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008061 if (outputDesc->decMuteCount(volumeSource) == 0) {
8062 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008063 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008064 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008065 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008066 delayMs);
8067 }
8068 }
8069}
8070
François Gaffie53615e22015-03-19 09:24:12 +01008071bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8072{
François Gaffiec005e562018-11-06 15:04:49 +01008073 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008074 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8075 return true;
8076 }
8077
8078 // has known usage?
8079 switch (paa->usage) {
8080 case AUDIO_USAGE_UNKNOWN:
8081 case AUDIO_USAGE_MEDIA:
8082 case AUDIO_USAGE_VOICE_COMMUNICATION:
8083 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8084 case AUDIO_USAGE_ALARM:
8085 case AUDIO_USAGE_NOTIFICATION:
8086 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8087 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8088 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8089 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8090 case AUDIO_USAGE_NOTIFICATION_EVENT:
8091 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8092 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8093 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8094 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008095 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008096 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008097 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008098 case AUDIO_USAGE_EMERGENCY:
8099 case AUDIO_USAGE_SAFETY:
8100 case AUDIO_USAGE_VEHICLE_STATUS:
8101 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008102 break;
8103 default:
8104 return false;
8105 }
8106 return true;
8107}
8108
François Gaffie2110e042015-03-24 08:41:51 +01008109audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8110{
8111 return mEngine->getForceUse(usage);
8112}
8113
Eric Laurent96d1dda2022-03-14 17:14:19 +01008114bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008115 return isStateInCall(mEngine->getPhoneState());
8116}
8117
Eric Laurent96d1dda2022-03-14 17:14:19 +01008118bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008119 return is_state_in_call(state);
8120}
8121
Eric Laurentf9cccec2022-11-16 19:12:00 +01008122bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008123 audio_mode_t mode = mEngine->getPhoneState();
8124 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008125 || (mode == AUDIO_MODE_CALL_SCREEN)
8126 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008127}
8128
Eric Laurentf9cccec2022-11-16 19:12:00 +01008129bool AudioPolicyManager::isInCallOrScreening() const {
8130 audio_mode_t mode = mEngine->getPhoneState();
8131 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8132}
8133
Eric Laurentd60560a2015-04-10 11:31:20 -07008134void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8135{
8136 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008137 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008138 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008139 sourceDesc->sinkDevice()->equals(deviceDesc))
8140 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008141 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008142 }
8143 }
8144
8145 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8146 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8147 bool release = false;
8148 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8149 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8150 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8151 source->ext.device.type == deviceDesc->type()) {
8152 release = true;
8153 }
8154 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008155 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008156 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8157 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8158 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008159 sink->ext.device.type == deviceDesc->type() &&
8160 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8161 || strncmp(sink->ext.device.address, address,
8162 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008163 release = true;
8164 }
8165 }
8166 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008167 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8168 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008169 }
8170 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008171
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008172 mInputs.clearSessionRoutesForDevice(deviceDesc);
8173
Francois Gaffie716e1432019-01-14 16:58:59 +01008174 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008175}
8176
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008177void AudioPolicyManager::modifySurroundFormats(
8178 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008179 std::unordered_set<audio_format_t> enforcedSurround(
8180 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008181 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008182 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008183 allSurround.insert(pair.first);
8184 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8185 }
Phil Burk09bc4612016-02-24 15:58:15 -08008186
8187 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8188 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008189 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008190 // This is the resulting set of formats depending on the surround mode:
8191 // 'all surround' = allSurround
8192 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8193 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8194 // 'manual surround' = mManualSurroundFormats
8195 // AUTO: formats v 'enforced surround'
8196 // ALWAYS: formats v 'all surround' v 'enforced surround'
8197 // NEVER: formats ^ 'non-surround'
8198 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008199
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008200 std::unordered_set<audio_format_t> formatSet;
8201 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8202 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008203 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008204 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008205 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008206 formatSet.insert(*formatIter);
8207 }
8208 }
8209 } else {
8210 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8211 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008212 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008213
jiabin81772902018-04-02 17:52:27 -07008214 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008215 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008216 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8217 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8218 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008219 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008220 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8221 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8222 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008223 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008224 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008225 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008226 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008227 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008228 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008229}
8230
jiabin06e4bab2019-07-29 10:13:34 -07008231void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8232 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008233 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8234 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8235
8236 // If NEVER, then remove support for channelMasks > stereo.
8237 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008238 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8239 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008240 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008241 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008242 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008243 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008244 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008245 }
8246 }
jiabin81772902018-04-02 17:52:27 -07008247 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8248 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8249 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008250 bool supports5dot1 = false;
8251 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008252 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008253 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8254 supports5dot1 = true;
8255 break;
8256 }
8257 }
8258 // If not then add 5.1 support.
8259 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008260 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008261 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008262 }
Phil Burk09bc4612016-02-24 15:58:15 -08008263 }
8264}
8265
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008266void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008267 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008268 const sp<IOProfile>& profile) {
8269 if (!profile->hasDynamicAudioProfile()) {
8270 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008271 }
François Gaffie112b0af2015-11-19 16:13:25 +01008272
jiabin12537fc2023-10-12 17:56:08 +00008273 audio_port_v7 devicePort;
8274 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008275
jiabin12537fc2023-10-12 17:56:08 +00008276 audio_port_v7 mixPort;
8277 profile->toAudioPort(&mixPort);
8278 mixPort.ext.mix.handle = ioHandle;
8279
8280 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8281 if (status != NO_ERROR) {
8282 ALOGE("%s failed to query the attributes of the mix port", __func__);
8283 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008284 }
jiabin12537fc2023-10-12 17:56:08 +00008285
8286 std::set<audio_format_t> supportedFormats;
8287 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8288 supportedFormats.insert(mixPort.audio_profiles[i].format);
8289 }
8290 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8291 mReportedFormatsMap[devDesc] = formats;
8292
8293 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8294 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8295 modifySurroundFormats(devDesc, &formats);
8296 size_t modifiedNumProfiles = 0;
8297 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8298 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8299 formats.end()) {
8300 // Skip the format that is not present after modifying surround formats.
8301 continue;
8302 }
8303 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8304 sizeof(struct audio_profile));
8305 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8306 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8307 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8308 modifySurroundChannelMasks(&channels);
8309 std::copy(channels.begin(), channels.end(),
8310 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8311 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8312 }
8313 mixPort.num_audio_profiles = modifiedNumProfiles;
8314 }
8315 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008316}
Eric Laurentd60560a2015-04-10 11:31:20 -07008317
Mikhail Naganovdc769682018-05-04 15:34:08 -07008318status_t AudioPolicyManager::installPatch(const char *caller,
8319 audio_patch_handle_t *patchHandle,
8320 AudioIODescriptorInterface *ioDescriptor,
8321 const struct audio_patch *patch,
8322 int delayMs)
8323{
8324 ssize_t index = mAudioPatches.indexOfKey(
8325 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8326 *patchHandle : ioDescriptor->getPatchHandle());
8327 sp<AudioPatch> patchDesc;
8328 status_t status = installPatch(
8329 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8330 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008331 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008332 }
8333 return status;
8334}
8335
8336status_t AudioPolicyManager::installPatch(const char *caller,
8337 ssize_t index,
8338 audio_patch_handle_t *patchHandle,
8339 const struct audio_patch *patch,
8340 int delayMs,
8341 uid_t uid,
8342 sp<AudioPatch> *patchDescPtr)
8343{
8344 sp<AudioPatch> patchDesc;
8345 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8346 if (index >= 0) {
8347 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008348 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008349 }
8350
8351 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8352 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8353 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8354 if (status == NO_ERROR) {
8355 if (index < 0) {
8356 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008357 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008358 } else {
8359 patchDesc->mPatch = *patch;
8360 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008361 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008362 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008363 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008364 }
8365 nextAudioPortGeneration();
8366 mpClientInterface->onAudioPatchListUpdate();
8367 }
8368 if (patchDescPtr) *patchDescPtr = patchDesc;
8369 return status;
8370}
8371
jiabinbce0c1d2020-10-05 11:20:18 -07008372bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8373{
8374 const TrackClientVector activeClients = output->getActiveClients();
8375 if (activeClients.empty()) {
8376 return true;
8377 }
8378 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8379 if (index < 0) {
8380 ALOGE("%s, no audio patch found while there are active clients on output %d",
8381 __func__, output->getId());
8382 return false;
8383 }
8384 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8385 DeviceVector routedDevices;
8386 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8387 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8388 patchDesc->mPatch.sinks[i].id);
8389 if (device == nullptr) {
8390 ALOGE("%s, no audio device found with id(%d)",
8391 __func__, patchDesc->mPatch.sinks[i].id);
8392 return false;
8393 }
8394 routedDevices.add(device);
8395 }
8396 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008397 if (client->isInvalid()) {
8398 // No need to take care about invalidated clients.
8399 continue;
8400 }
jiabinbce0c1d2020-10-05 11:20:18 -07008401 sp<DeviceDescriptor> preferredDevice =
8402 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8403 if (mEngine->getOutputDevicesForAttributes(
8404 client->attributes(), preferredDevice, false) == routedDevices) {
8405 return false;
8406 }
8407 }
8408 return true;
8409}
8410
8411sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008412 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008413 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8414 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008415{
8416 for (const auto& device : devices) {
8417 // TODO: This should be checking if the profile supports the device combo.
8418 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008419 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8420 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008421 return nullptr;
8422 }
8423 }
8424 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8425 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008426 status_t status = desc->open(halConfig, mixerConfig, devices,
8427 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008428 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008429 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008430 return nullptr;
8431 }
jiabin14b50cc2023-12-13 19:01:52 +00008432 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8433 auto portConfig = desc->getConfig();
8434 for (const auto& device : devices) {
8435 device->setPreferredConfig(&portConfig);
8436 }
8437 }
jiabinbce0c1d2020-10-05 11:20:18 -07008438
8439 // Here is where the out_set_parameters() for card & device gets called
8440 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8441 const audio_devices_t deviceType = device->type();
8442 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008443 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008444 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8445 mpClientInterface->setParameters(output, String8(param));
8446 free(param);
8447 }
jiabin12537fc2023-10-12 17:56:08 +00008448 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008449 if (!profile->hasValidAudioProfile()) {
8450 ALOGW("%s() missing param", __func__);
8451 desc->close();
8452 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008453 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8454 // Reopen the output with the best audio profile picked by APM when the profile supports
8455 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008456 desc->close();
8457 output = AUDIO_IO_HANDLE_NONE;
8458 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8459 profile->pickAudioProfile(
8460 config.sample_rate, config.channel_mask, config.format);
8461 config.offload_info.sample_rate = config.sample_rate;
8462 config.offload_info.channel_mask = config.channel_mask;
8463 config.offload_info.format = config.format;
8464
jiabina84c3d32022-12-02 18:59:55 +00008465 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008466 if (status != NO_ERROR) {
8467 return nullptr;
8468 }
8469 }
8470
8471 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008472
baek.kim -61c20122022-07-27 10:05:32 +00008473 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8474 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8475
jiabinbce0c1d2020-10-05 11:20:18 -07008476 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8477 sp<AudioPolicyMix> policyMix;
8478 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8479 policyMix->setOutput(desc);
8480 desc->mPolicyMix = policyMix;
8481 } else {
8482 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008483 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008484 }
8485
baek.kim -61c20122022-07-27 10:05:32 +00008486 } else if (hasPrimaryOutput() && speaker != nullptr
8487 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008488 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8489 // no duplicated output for:
8490 // - direct outputs
8491 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008492 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008493 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8494
8495 //TODO: configure audio effect output stage here
8496
8497 // open a duplicating output thread for the new output and the primary output
8498 sp<SwAudioOutputDescriptor> dupOutputDesc =
8499 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8500 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8501 if (status == NO_ERROR) {
8502 // add duplicated output descriptor
8503 addOutput(duplicatedOutput, dupOutputDesc);
8504 } else {
8505 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8506 mPrimaryOutput->mIoHandle, output);
8507 desc->close();
8508 removeOutput(output);
8509 nextAudioPortGeneration();
8510 return nullptr;
8511 }
8512 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008513 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8514 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8515 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008516 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008517 }
jiabinbce0c1d2020-10-05 11:20:18 -07008518 return desc;
8519}
8520
jiabinf1c73972022-04-14 16:28:52 -07008521status_t AudioPolicyManager::getDevicesForAttributes(
8522 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8523 // Devices are determined in the following precedence:
8524 //
8525 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8526 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8527 //
8528 // If no such dynamic policy then
8529 // 2) Devices containing an active client using setPreferredDevice
8530 // with same strategy as the attributes.
8531 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8532 //
8533 // If no corresponding active client with setPreferredDevice then
8534 // 3) Devices associated with the strategy determined by the attributes
8535 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8536 //
8537 // See related getOutputForAttrInt().
8538
8539 // check dynamic policies but only for primary descriptors (secondary not used for audible
8540 // audio routing, only used for duplication for playback capture)
8541 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008542 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008543 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008544 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8545 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8546 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008547 if (status != OK) {
8548 return status;
8549 }
8550
8551 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8552 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8553 // as they are unaffected by device/stream volume
8554 // (per SwAudioOutputDescriptor::isFixedVolume()).
8555 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8556 ) {
8557 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8558 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8559 devices.add(deviceDesc);
8560 } else {
8561 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8562 // which selects setPreferredDevice if active. This means forVolume call
8563 // will take an active setPreferredDevice, if such exists.
8564
8565 devices = mEngine->getOutputDevicesForAttributes(
8566 attr, nullptr /* preferredDevice */, false /* fromCache */);
8567 }
8568
8569 if (forVolume) {
8570 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8571 // for single volume control in AudioService (such relationship should exist if
8572 // SPEAKER_SAFE is present).
8573 //
8574 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8575 DeviceVector speakerSafeDevices =
8576 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8577 if (!speakerSafeDevices.isEmpty()) {
8578 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8579 devices.remove(speakerSafeDevices);
8580 }
8581 }
8582
8583 return NO_ERROR;
8584}
8585
8586status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8587 AudioProfileVector& audioProfiles,
8588 uint32_t flags,
8589 bool isInput) {
8590 for (const auto& hwModule : mHwModules) {
8591 // the MSD module checks for different conditions
8592 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8593 continue;
8594 }
8595 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8596 : hwModule->getOutputProfiles();
8597 for (const auto& profile : ioProfiles) {
8598 if (!profile->areAllDevicesSupported(devices) ||
8599 !profile->isCompatibleProfileForFlags(
8600 flags, false /*exactMatchRequiredForInputFlags*/)) {
8601 continue;
8602 }
8603 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8604 }
8605 }
8606
8607 if (!isInput) {
8608 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8609 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8610 if (msdModule != nullptr) {
8611 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8612 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8613 for (const auto &profile: msdModule->getOutputProfiles()) {
8614 if (!profile->asAudioPort()->isDirectOutput()) {
8615 continue;
8616 }
8617 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8618 }
8619 } else {
8620 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8621 }
8622 }
8623 }
8624
8625 return NO_ERROR;
8626}
8627
jiabin3ff8d7d2022-12-13 06:27:44 +00008628sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8629 const audio_config_t *config,
8630 audio_output_flags_t flags,
8631 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008632 closeOutput(outputDesc->mIoHandle);
8633 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8634 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8635 if (preferredOutput == nullptr) {
8636 ALOGE("%s failed to reopen output device=%d, caller=%s",
8637 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008638 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008639 return preferredOutput;
8640}
8641
8642void AudioPolicyManager::reopenOutputsWithDevices(
8643 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8644 for (const auto& [output, devices] : outputsToReopen) {
8645 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8646 closeOutput(output);
8647 openOutputWithProfileAndDevice(desc->mProfile, devices);
8648 }
jiabina84c3d32022-12-02 18:59:55 +00008649}
8650
jiabinc44b3462022-12-08 12:52:31 -08008651PortHandleVector AudioPolicyManager::getClientsForStream(
8652 audio_stream_type_t streamType) const {
8653 PortHandleVector clients;
8654 for (size_t i = 0; i < mOutputs.size(); ++i) {
8655 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8656 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8657 }
8658 return clients;
8659}
8660
8661void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8662 PortHandleVector clients;
8663 for (auto stream : streams) {
8664 PortHandleVector clientsForStream = getClientsForStream(stream);
8665 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8666 }
8667 mpClientInterface->invalidateTracks(clients);
8668}
8669
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008670} // namespace android