blob: a5c407a6e97ed2db541996aa9343084cac8ec331 [file] [log] [blame]
Eric Laurente552edb2014-03-10 17:42:56 -07001/*
2 * Copyright (C) 2009 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +020017#include "utils/Errors.h"
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -070018#define LOG_TAG "APM_AudioPolicyManager"
Tomoharu Kasahara71c90912018-10-31 09:10:12 +090019
20// Need to keep the log statements even in production builds
21// to enable VERBOSE logging dynamically.
22// You can enable VERBOSE logging as follows:
23// adb shell setprop log.tag.APM_AudioPolicyManager V
24#define LOG_NDEBUG 0
Eric Laurente552edb2014-03-10 17:42:56 -070025
26//#define VERY_VERBOSE_LOGGING
27#ifdef VERY_VERBOSE_LOGGING
28#define ALOGVV ALOGV
29#else
30#define ALOGVV(a...) do { } while(0)
31#endif
32
Eric Laurent16c66dd2019-05-01 17:54:10 -070033#include <algorithm>
Eric Laurentd4692962014-05-05 18:13:44 -070034#include <inttypes.h>
jiabin10a03f12021-05-07 23:46:28 +000035#include <map>
Eric Laurente552edb2014-03-10 17:42:56 -070036#include <math.h>
Kevin Rocard153f92d2018-12-18 18:33:28 -080037#include <set>
Atneya Nair0f0a8032022-12-12 16:20:12 -080038#include <type_traits>
Mikhail Naganovd5e18052018-11-30 14:55:45 -080039#include <unordered_set>
Mikhail Naganov15be9d22017-11-08 14:18:13 +110040#include <vector>
Mikhail Naganov946c0032020-10-21 13:04:58 -070041
42#include <Serializer.h>
Nathalie Le Clair88fa2752021-11-23 13:03:41 +010043#include <android/media/audio/common/AudioPort.h>
Andy Hung481bfe32023-12-18 14:00:29 -080044#include <com_android_media_audio.h>
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);
Francois Gaffie601801d2021-06-22 13:27:39 +0200785 mCallRxSourceClient = startAudioSourceInternal(&source, &aa, 0/*uid*/);
786 ALOGE_IF(mCallRxSourceClient == nullptr,
787 "%s failed to start Telephony Rx AudioSource", __func__);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200788}
789
Francois Gaffie601801d2021-06-22 13:27:39 +0200790void AudioPolicyManager::disconnectTelephonyAudioSource(sp<SourceClientDescriptor> &clientDesc)
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200791{
Francois Gaffie601801d2021-06-22 13:27:39 +0200792 if (clientDesc == nullptr) {
793 return;
794 }
795 ALOGW_IF(stopAudioSource(clientDesc->portId()) != NO_ERROR,
796 "%s error stopping audio source", __func__);
797 clientDesc.clear();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200798}
799
800void AudioPolicyManager::connectTelephonyTxAudioSource(
801 const sp<DeviceDescriptor> &srcDevice, const sp<DeviceDescriptor> &sinkDevice,
802 uint32_t delayMs)
803{
Francois Gaffie601801d2021-06-22 13:27:39 +0200804 disconnectTelephonyAudioSource(mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200805 if (srcDevice == nullptr || sinkDevice == nullptr) {
806 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
807 return;
808 }
809 PatchBuilder patchBuilder;
810 patchBuilder.addSource(srcDevice).addSink(sinkDevice);
811 ALOGV("%s between source %s and sink %s", __func__,
812 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
Francois Gaffie601801d2021-06-22 13:27:39 +0200813 auto callTxSourceClientPortId = PolicyAudioPort::getNextUniqueId();
Eric Laurent78b07302022-10-07 16:20:34 +0200814 const auto aa = mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL);
815
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200816 struct audio_port_config source = {};
817 srcDevice->toAudioPortConfig(&source);
Francois Gaffie601801d2021-06-22 13:27:39 +0200818 mCallTxSourceClient = new InternalSourceClientDescriptor(
819 callTxSourceClientPortId, mUidCached, aa, source, srcDevice, sinkDevice,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200820 mCommunnicationStrategy, toVolumeSource(aa));
821 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
822 status_t status = connectAudioSourceToSink(
Francois Gaffie601801d2021-06-22 13:27:39 +0200823 mCallTxSourceClient, sinkDevice, patchBuilder.patch(), patchHandle, mUidCached,
824 delayMs);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200825 ALOGE_IF(status != NO_ERROR, "%s() error %d creating TX audio patch", __func__, status);
826 if (status == NO_ERROR) {
Francois Gaffie601801d2021-06-22 13:27:39 +0200827 mAudioSources.add(callTxSourceClientPortId, mCallTxSourceClient);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +0200828 }
Francois Gaffie51c9ccd2020-10-14 18:02:07 +0200829}
830
Eric Laurente0720872014-03-11 09:30:41 -0700831void AudioPolicyManager::setPhoneState(audio_mode_t state)
Eric Laurente552edb2014-03-10 17:42:56 -0700832{
833 ALOGV("setPhoneState() state %d", state);
François Gaffie2110e042015-03-24 08:41:51 +0100834 // store previous phone state for management of sonification strategy below
835 int oldState = mEngine->getPhoneState();
Eric Laurent96d1dda2022-03-14 17:14:19 +0100836 bool wasLeUnicastActive = isLeUnicastActive();
François Gaffie2110e042015-03-24 08:41:51 +0100837
838 if (mEngine->setPhoneState(state) != NO_ERROR) {
839 ALOGW("setPhoneState() invalid or same state %d", state);
Eric Laurente552edb2014-03-10 17:42:56 -0700840 return;
841 }
François Gaffie2110e042015-03-24 08:41:51 +0100842 /// Opens: can these line be executed after the switch of volume curves???
Eric Laurent63dea1d2015-07-02 17:10:28 -0700843 if (isStateInCall(oldState)) {
Eric Laurente552edb2014-03-10 17:42:56 -0700844 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700845 // force reevaluating accessibility routing when call stops
jiabinc44b3462022-12-08 12:52:31 -0800846 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700847 }
848
François Gaffie2110e042015-03-24 08:41:51 +0100849 /**
850 * Switching to or from incall state or switching between telephony and VoIP lead to force
851 * routing command.
852 */
Eric Laurent74b71512019-11-06 17:21:57 -0800853 bool force = ((isStateInCall(oldState) != isStateInCall(state))
854 || (isStateInCall(state) && (state != oldState)));
Eric Laurente552edb2014-03-10 17:42:56 -0700855
856 // check for device and output changes triggered by new phone state
Mikhail Naganov37977152018-07-11 15:54:44 -0700857 checkForDeviceAndOutputChanges();
Eric Laurente552edb2014-03-10 17:42:56 -0700858
Eric Laurente552edb2014-03-10 17:42:56 -0700859 int delayMs = 0;
860 if (isStateInCall(state)) {
861 nsecs_t sysTime = systemTime();
François Gaffiec005e562018-11-06 15:04:49 +0100862 auto musicStrategy = streamToStrategy(AUDIO_STREAM_MUSIC);
863 auto sonificationStrategy = streamToStrategy(AUDIO_STREAM_ALARM);
Eric Laurente552edb2014-03-10 17:42:56 -0700864 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -0700865 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -0700866 // mute media and sonification strategies and delay device switch by the largest
867 // latency of any output where either strategy is active.
868 // This avoid sending the ring tone or music tail into the earpiece or headset.
François Gaffiec005e562018-11-06 15:04:49 +0100869 if ((desc->isStrategyActive(musicStrategy, SONIFICATION_HEADSET_MUSIC_DELAY, sysTime) ||
870 desc->isStrategyActive(sonificationStrategy, SONIFICATION_HEADSET_MUSIC_DELAY,
871 sysTime)) &&
Eric Laurentc75307b2015-03-17 15:29:32 -0700872 (delayMs < (int)desc->latency()*2)) {
873 delayMs = desc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -0700874 }
François Gaffiec005e562018-11-06 15:04:49 +0100875 setStrategyMute(musicStrategy, true, desc);
876 setStrategyMute(musicStrategy, false, desc, MUTE_TIME_MS,
877 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
878 nullptr, true /*fromCache*/).types());
879 setStrategyMute(sonificationStrategy, true, desc);
880 setStrategyMute(sonificationStrategy, false, desc, MUTE_TIME_MS,
881 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_ALARM),
882 nullptr, true /*fromCache*/).types());
Eric Laurente552edb2014-03-10 17:42:56 -0700883 }
884 }
885
François Gaffiedb1755b2023-09-01 11:50:35 +0200886 if (state == AUDIO_MODE_IN_CALL) {
887 (void)updateCallRouting(false /*fromCache*/, delayMs);
888 } else {
889 if (oldState == AUDIO_MODE_IN_CALL) {
890 disconnectTelephonyAudioSource(mCallRxSourceClient);
891 disconnectTelephonyAudioSource(mCallTxSourceClient);
892 }
893 if (hasPrimaryOutput()) {
Francois Gaffie19fd6c52021-02-04 17:02:59 +0100894 DeviceVector rxDevices = getNewOutputDevices(mPrimaryOutput, false /*fromCache*/);
895 // force routing command to audio hardware when ending call
896 // even if no device change is needed
897 if (isStateInCall(oldState) && rxDevices.isEmpty()) {
898 rxDevices = mPrimaryOutput->devices();
899 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530900 setOutputDevices(__func__, mPrimaryOutput, rxDevices, force, 0);
Eric Laurentc2730ba2014-07-20 15:47:07 -0700901 }
Eric Laurentc2730ba2014-07-20 15:47:07 -0700902 }
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700903
jiabin3ff8d7d2022-12-13 06:27:44 +0000904 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700905 // reevaluate routing on all outputs in case tracks have been started during the call
906 for (size_t i = 0; i < mOutputs.size(); i++) {
907 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
François Gaffie11d30102018-11-02 16:09:09 +0100908 DeviceVector newDevices = getNewOutputDevices(desc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +0200909 if (state != AUDIO_MODE_IN_CALL || (desc != mPrimaryOutput && !isTelephonyRxOrTx(desc))) {
910 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +0000911 if (desc->mUsePreferredMixerAttributes && newDevices != desc->devices()) {
912 // If the device is using preferred mixer attributes, the output need to reopen
913 // with default configuration when the new selected devices are different from
914 // current routing devices.
915 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
916 continue;
917 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +0530918 setOutputDevices(__func__, desc, newDevices, forceRouting, 0 /*delayMs*/, nullptr,
Francois Gaffie601801d2021-06-22 13:27:39 +0200919 true /*requiresMuteCheck*/, !forceRouting /*requiresVolumeCheck*/);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700920 }
921 }
jiabin3ff8d7d2022-12-13 06:27:44 +0000922 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent2e2a8a92018-04-20 16:21:33 -0700923
Eric Laurent96d1dda2022-03-14 17:14:19 +0100924 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
925
Eric Laurente552edb2014-03-10 17:42:56 -0700926 if (isStateInCall(state)) {
927 ALOGV("setPhoneState() in call state management: new state is %d", state);
Eric Laurent63dea1d2015-07-02 17:10:28 -0700928 // force reevaluating accessibility routing when call starts
jiabinc44b3462022-12-08 12:52:31 -0800929 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurente552edb2014-03-10 17:42:56 -0700930 }
931
932 // Flag that ringtone volume must be limited to music volume until we exit MODE_RINGTONE
François Gaffiec005e562018-11-06 15:04:49 +0100933 mLimitRingtoneVolume = (state == AUDIO_MODE_RINGTONE &&
934 isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY));
Eric Laurente552edb2014-03-10 17:42:56 -0700935}
936
Jean-Michel Trivi887a9ed2015-03-31 18:02:24 -0700937audio_mode_t AudioPolicyManager::getPhoneState() {
938 return mEngine->getPhoneState();
939}
940
Eric Laurente0720872014-03-11 09:30:41 -0700941void AudioPolicyManager::setForceUse(audio_policy_force_use_t usage,
François Gaffie11d30102018-11-02 16:09:09 +0100942 audio_policy_forced_cfg_t config)
Eric Laurente552edb2014-03-10 17:42:56 -0700943{
François Gaffie2110e042015-03-24 08:41:51 +0100944 ALOGV("setForceUse() usage %d, config %d, mPhoneState %d", usage, config, mEngine->getPhoneState());
Eric Laurent8dc87a62017-05-16 19:00:40 -0700945 if (config == mEngine->getForceUse(usage)) {
946 return;
947 }
Eric Laurente552edb2014-03-10 17:42:56 -0700948
François Gaffie2110e042015-03-24 08:41:51 +0100949 if (mEngine->setForceUse(usage, config) != NO_ERROR) {
950 ALOGW("setForceUse() could not set force cfg %d for usage %d", config, usage);
951 return;
Eric Laurente552edb2014-03-10 17:42:56 -0700952 }
François Gaffie2110e042015-03-24 08:41:51 +0100953 bool forceVolumeReeval = (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) ||
954 (usage == AUDIO_POLICY_FORCE_FOR_DOCK) ||
955 (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM);
Eric Laurente552edb2014-03-10 17:42:56 -0700956
957 // check for device and output changes triggered by new force usage
Mikhail Naganov37977152018-07-11 15:54:44 -0700958 checkForDeviceAndOutputChanges();
Phil Burk09bc4612016-02-24 15:58:15 -0800959
Eric Laurent22fcda22019-05-17 16:28:47 -0700960 // force client reconnection to reevaluate flag AUDIO_FLAG_AUDIBILITY_ENFORCED
961 if (usage == AUDIO_POLICY_FORCE_FOR_SYSTEM) {
jiabinc44b3462022-12-08 12:52:31 -0800962 invalidateStreams({AUDIO_STREAM_SYSTEM, AUDIO_STREAM_ENFORCED_AUDIBLE});
Eric Laurent22fcda22019-05-17 16:28:47 -0700963 }
964
Eric Laurentdc462862016-07-19 12:29:53 -0700965 //FIXME: workaround for truncated touch sounds
966 // to be removed when the problem is handled by system UI
967 uint32_t delayMs = 0;
Eric Laurentdc462862016-07-19 12:29:53 -0700968 if (usage == AUDIO_POLICY_FORCE_FOR_COMMUNICATION) {
969 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
970 }
Jean-Michel Trivi30857152019-11-01 11:04:15 -0700971
972 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Eric Laurent2517af32020-11-25 15:31:27 +0100973 updateInputRouting();
Eric Laurente552edb2014-03-10 17:42:56 -0700974}
975
Eric Laurente0720872014-03-11 09:30:41 -0700976void AudioPolicyManager::setSystemProperty(const char* property, const char* value)
Eric Laurente552edb2014-03-10 17:42:56 -0700977{
978 ALOGV("setSystemProperty() property %s, value %s", property, value);
979}
980
Dorin Drimusecc9f422022-03-09 17:57:40 +0100981// Find an MSD output profile compatible with the parameters passed.
982// When "directOnly" is set, restrict search to profiles for direct outputs.
983sp<IOProfile> AudioPolicyManager::getMsdProfileForOutput(
984 const DeviceVector& devices,
985 uint32_t samplingRate,
986 audio_format_t format,
987 audio_channel_mask_t channelMask,
988 audio_output_flags_t flags,
989 bool directOnly)
990{
991 flags = getRelevantFlags(flags, directOnly);
992
993 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
994 if (msdModule != nullptr) {
995 // for the msd module check if there are patches to the output devices
996 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
997 HwModuleCollection modules;
998 modules.add(msdModule);
999 return searchCompatibleProfileHwModules(
1000 modules, getMsdAudioOutDevices(), samplingRate, format, channelMask,
1001 flags, directOnly);
1002 }
1003 }
1004 return nullptr;
1005}
1006
Michael Chana94fbb22018-04-24 14:31:19 +10001007// Find an output profile compatible with the parameters passed. When "directOnly" is set, restrict
1008// search to profiles for direct outputs.
1009sp<IOProfile> AudioPolicyManager::getProfileForOutput(
François Gaffie11d30102018-11-02 16:09:09 +01001010 const DeviceVector& devices,
Michael Chana94fbb22018-04-24 14:31:19 +10001011 uint32_t samplingRate,
1012 audio_format_t format,
1013 audio_channel_mask_t channelMask,
1014 audio_output_flags_t flags,
1015 bool directOnly)
Eric Laurente552edb2014-03-10 17:42:56 -07001016{
Dorin Drimusecc9f422022-03-09 17:57:40 +01001017 flags = getRelevantFlags(flags, directOnly);
1018
1019 return searchCompatibleProfileHwModules(
1020 mHwModules, devices, samplingRate, format, channelMask, flags, directOnly);
1021}
1022
1023audio_output_flags_t AudioPolicyManager::getRelevantFlags (
1024 audio_output_flags_t flags, bool directOnly) {
Michael Chana94fbb22018-04-24 14:31:19 +10001025 if (directOnly) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001026 // only retain flags that will drive the direct output profile selection
1027 // if explicitly requested
1028 static const uint32_t kRelevantFlags =
Michael Chana94fbb22018-04-24 14:31:19 +10001029 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD |
Dorin Drimusecc9f422022-03-09 17:57:40 +01001030 AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ);
1031 flags = (audio_output_flags_t)((flags & kRelevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
Michael Chana94fbb22018-04-24 14:31:19 +10001032 }
Dorin Drimusecc9f422022-03-09 17:57:40 +01001033 return flags;
1034}
Eric Laurent861a6282015-05-18 15:40:16 -07001035
Dorin Drimusecc9f422022-03-09 17:57:40 +01001036sp<IOProfile> AudioPolicyManager::searchCompatibleProfileHwModules (
1037 const HwModuleCollection& hwModules,
1038 const DeviceVector& devices,
1039 uint32_t samplingRate,
1040 audio_format_t format,
1041 audio_channel_mask_t channelMask,
1042 audio_output_flags_t flags,
1043 bool directOnly) {
Eric Laurent861a6282015-05-18 15:40:16 -07001044 sp<IOProfile> profile;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001045 for (const auto& hwModule : hwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08001046 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Dorin Drimusecc9f422022-03-09 17:57:40 +01001047 if (!curProfile->isCompatibleProfile(devices,
1048 samplingRate, NULL /*updatedSamplingRate*/,
1049 format, NULL /*updatedFormat*/,
1050 channelMask, NULL /*updatedChannelMask*/,
1051 flags)) {
1052 continue;
1053 }
1054 // reject profiles not corresponding to a device currently available
1055 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
1056 continue;
1057 }
1058 // reject profiles if connected device does not support codec
1059 if (!curProfile->devicesSupportEncodedFormats(devices.types())) {
1060 continue;
1061 }
1062 if (!directOnly) {
1063 return curProfile;
1064 }
1065
1066 // when searching for direct outputs, if several profiles are compatible, give priority
1067 // to one with offload capability
Patty Huang36028df2022-07-06 00:14:12 +08001068 if (profile != 0 &&
Dorin Drimusecc9f422022-03-09 17:57:40 +01001069 ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0)) {
Eric Laurent861a6282015-05-18 15:40:16 -07001070 continue;
Dorin Drimusecc9f422022-03-09 17:57:40 +01001071 }
1072 profile = curProfile;
1073 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1074 break;
1075 }
Eric Laurente552edb2014-03-10 17:42:56 -07001076 }
1077 }
Eric Laurent861a6282015-05-18 15:40:16 -07001078 return profile;
Eric Laurente552edb2014-03-10 17:42:56 -07001079}
1080
Eric Laurentfa0f6742021-08-17 18:39:44 +02001081sp<IOProfile> AudioPolicyManager::getSpatializerOutputProfile(
Eric Laurent39095982021-08-24 18:29:27 +02001082 const audio_config_t *config __unused, const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001083{
1084 for (const auto& hwModule : mHwModules) {
1085 for (const auto& curProfile : hwModule->getOutputProfiles()) {
Eric Laurent1c5e2e32021-08-18 18:50:28 +02001086 if (curProfile->getFlags() != AUDIO_OUTPUT_FLAG_SPATIALIZER) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001087 continue;
1088 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001089 if (!devices.empty()) {
Eric Laurent0c8f7cc2022-06-24 14:32:36 +02001090 // reject profiles not corresponding to a device currently available
1091 DeviceVector supportedDevices = curProfile->getSupportedDevices();
1092 if (!mAvailableOutputDevices.containsAtLeastOne(supportedDevices)) {
1093 continue;
1094 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001095 if (supportedDevices.getDevicesFromDeviceTypeAddrVec(devices).size()
1096 != devices.size()) {
1097 continue;
1098 }
1099 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001100 ALOGV("%s found profile %s", __func__, curProfile->getName().c_str());
1101 return curProfile;
1102 }
1103 }
1104 return nullptr;
1105}
1106
Eric Laurentf4e63452017-11-06 19:31:46 +00001107audio_io_handle_t AudioPolicyManager::getOutput(audio_stream_type_t stream)
Eric Laurente552edb2014-03-10 17:42:56 -07001108{
François Gaffiec005e562018-11-06 15:04:49 +01001109 DeviceVector devices = mEngine->getOutputDevicesForStream(stream, false /*fromCache*/);
Andy Hungc9901522017-11-10 20:07:54 -08001110
1111 // Note that related method getOutputForAttr() uses getOutputForDevice() not selectOutput().
1112 // We use selectOutput() here since we don't have the desired AudioTrack sample rate,
1113 // format, flags, etc. This may result in some discrepancy for functions that utilize
1114 // getOutput() solely on audio_stream_type such as AudioSystem::getOutputFrameCount()
1115 // and AudioSystem::getOutputSamplingRate().
1116
François Gaffie11d30102018-11-02 16:09:09 +01001117 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Mingyu Shih75563d32023-05-24 04:47:40 +08001118 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
1119 if (stream == AUDIO_STREAM_MUSIC &&
1120 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1121 flags = AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
1122 }
1123 const audio_io_handle_t output = selectOutput(outputs, flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001124
François Gaffie11d30102018-11-02 16:09:09 +01001125 ALOGV("getOutput() stream %d selected devices %s, output %d", stream,
1126 devices.toString().c_str(), output);
Eric Laurentf4e63452017-11-06 19:31:46 +00001127 return output;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001128}
1129
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001130status_t AudioPolicyManager::getAudioAttributes(audio_attributes_t *dstAttr,
1131 const audio_attributes_t *srcAttr,
1132 audio_stream_type_t srcStream)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001133{
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001134 if (srcAttr != NULL) {
1135 if (!isValidAttributes(srcAttr)) {
1136 ALOGE("%s invalid attributes: usage=%d content=%d flags=0x%x tags=[%s]",
1137 __func__,
1138 srcAttr->usage, srcAttr->content_type, srcAttr->flags,
1139 srcAttr->tags);
1140 return BAD_VALUE;
1141 }
1142 *dstAttr = *srcAttr;
1143 } else {
1144 if (srcStream < AUDIO_STREAM_MIN || srcStream >= AUDIO_STREAM_PUBLIC_CNT) {
1145 ALOGE("%s: invalid stream type", __func__);
1146 return BAD_VALUE;
1147 }
François Gaffiec005e562018-11-06 15:04:49 +01001148 *dstAttr = mEngine->getAttributesForStreamType(srcStream);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001149 }
Eric Laurent22fcda22019-05-17 16:28:47 -07001150
1151 // Only honor audibility enforced when required. The client will be
1152 // forced to reconnect if the forced usage changes.
1153 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) != AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001154 dstAttr->flags = static_cast<audio_flags_mask_t>(
1155 dstAttr->flags & ~AUDIO_FLAG_AUDIBILITY_ENFORCED);
Eric Laurent22fcda22019-05-17 16:28:47 -07001156 }
1157
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001158 return NO_ERROR;
1159}
1160
Kevin Rocard153f92d2018-12-18 18:33:28 -08001161status_t AudioPolicyManager::getOutputForAttrInt(
1162 audio_attributes_t *resultAttr,
1163 audio_io_handle_t *output,
1164 audio_session_t session,
1165 const audio_attributes_t *attr,
1166 audio_stream_type_t *stream,
1167 uid_t uid,
jiabinf1c73972022-04-14 16:28:52 -07001168 audio_config_t *config,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001169 audio_output_flags_t *flags,
1170 audio_port_handle_t *selectedDeviceId,
1171 bool *isRequestedDeviceForExclusiveUse,
Eric Laurentc529cf62020-04-17 18:19:10 -07001172 std::vector<sp<AudioPolicyMix>> *secondaryMixes,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001173 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001174 bool *isSpatialized,
1175 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001176{
François Gaffiec005e562018-11-06 15:04:49 +01001177 DeviceVector outputDevices;
Francois Gaffie716e1432019-01-14 16:58:59 +01001178 const audio_port_handle_t requestedPortId = *selectedDeviceId;
François Gaffie11d30102018-11-02 16:09:09 +01001179 DeviceVector msdDevices = getMsdAudioOutDevices();
François Gaffiec005e562018-11-06 15:04:49 +01001180 const sp<DeviceDescriptor> requestedDevice =
1181 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1182
Eric Laurent8a1095a2019-11-08 14:44:16 -08001183 *outputType = API_OUTPUT_INVALID;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001184 *isSpatialized = false;
1185
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001186 status_t status = getAudioAttributes(resultAttr, attr, *stream);
1187 if (status != NO_ERROR) {
1188 return status;
Eric Laurent8f42ea12018-08-08 09:08:25 -07001189 }
Kevin Rocardb99cc752019-03-21 20:52:24 -07001190 if (auto it = mAllowedCapturePolicies.find(uid); it != end(mAllowedCapturePolicies)) {
Mikhail Naganov55773032020-10-01 15:08:13 -07001191 resultAttr->flags = static_cast<audio_flags_mask_t>(resultAttr->flags | it->second);
Kevin Rocardb99cc752019-03-21 20:52:24 -07001192 }
François Gaffiec005e562018-11-06 15:04:49 +01001193 *stream = mEngine->getStreamTypeForAttributes(*resultAttr);
Eric Laurent8f42ea12018-08-08 09:08:25 -07001194
François Gaffiec005e562018-11-06 15:04:49 +01001195 ALOGV("%s() attributes=%s stream=%s session %d selectedDeviceId %d", __func__,
1196 toString(*resultAttr).c_str(), toString(*stream).c_str(), session, requestedPortId);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001197
Oscar Azucena873d10f2023-01-12 18:34:42 -08001198 bool usePrimaryOutputFromPolicyMixes = false;
1199
Kevin Rocard153f92d2018-12-18 18:33:28 -08001200 // The primary output is the explicit routing (eg. setPreferredDevice) if specified,
1201 // otherwise, fallback to the dynamic policies, if none match, query the engine.
1202 // Secondary outputs are always found by dynamic policies as the engine do not support them
Eric Laurentc529cf62020-04-17 18:19:10 -07001203 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11001204 const audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
1205 .channel_mask = config->channel_mask,
1206 .format = config->format,
1207 };
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02001208 status = mPolicyMixes.getOutputForAttr(*resultAttr, clientConfig, uid, session, *flags,
Oscar Azucena873d10f2023-01-12 18:34:42 -08001209 mAvailableOutputDevices, requestedDevice, primaryMix,
1210 secondaryMixes, usePrimaryOutputFromPolicyMixes);
Kevin Rocard94114a22019-04-01 19:38:23 -07001211 if (status != OK) {
1212 return status;
Kevin Rocard153f92d2018-12-18 18:33:28 -08001213 }
Kevin Rocard94114a22019-04-01 19:38:23 -07001214
Kevin Rocard153f92d2018-12-18 18:33:28 -08001215 // FIXME: in case of RENDER policy, the output capabilities should be checked
Dean Wheatleyd082f472022-02-04 11:10:48 +11001216 if ((secondaryMixes != nullptr && !secondaryMixes->empty())
1217 && !audio_is_linear_pcm(config->format)) {
1218 ALOGD("%s: rejecting request as secondary mixes only support pcm", __func__);
Kevin Rocard153f92d2018-12-18 18:33:28 -08001219 return BAD_VALUE;
1220 }
1221 if (usePrimaryOutputFromPolicyMixes) {
jiabin24ff57a2023-11-27 21:06:51 +00001222 sp<DeviceDescriptor> policyMixDevice =
Eric Laurentc529cf62020-04-17 18:19:10 -07001223 mAvailableOutputDevices.getDevice(primaryMix->mDeviceType,
1224 primaryMix->mDeviceAddress,
1225 AUDIO_FORMAT_DEFAULT);
1226 sp<SwAudioOutputDescriptor> policyDesc = primaryMix->getOutput();
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001227 bool tryDirectForFlags = policyDesc == nullptr ||
jiabin24ff57a2023-11-27 21:06:51 +00001228 (policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) ||
1229 (*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ));
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001230 // if a direct output can be opened to deliver the track's multi-channel content to the
1231 // output rather than being downmixed by the primary output, then use this direct
1232 // output by by-passing the primary mix if possible, otherwise fall-through to primary
1233 // mix.
1234 bool tryDirectForChannelMask = policyDesc != nullptr
1235 && (audio_channel_count_from_out_mask(policyDesc->getConfig().channel_mask) <
1236 audio_channel_count_from_out_mask(config->channel_mask));
jiabin24ff57a2023-11-27 21:06:51 +00001237 if (policyMixDevice != nullptr && (tryDirectForFlags || tryDirectForChannelMask)) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001238 audio_io_handle_t newOutput;
1239 status = openDirectOutput(
1240 *stream, session, config,
1241 (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT),
jiabin24ff57a2023-11-27 21:06:51 +00001242 DeviceVector(policyMixDevice), &newOutput);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001243 if (status == NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001244 policyDesc = mOutputs.valueFor(newOutput);
1245 primaryMix->setOutput(policyDesc);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001246 } else if (tryDirectForFlags) {
jiabin24ff57a2023-11-27 21:06:51 +00001247 ALOGW("%s, failed open direct, status: %d", __func__, status);
Dean Wheatleyecbf2ee2022-03-04 10:51:36 +11001248 policyDesc = nullptr;
1249 } // otherwise use primary if available.
Eric Laurentc529cf62020-04-17 18:19:10 -07001250 }
1251 if (policyDesc != nullptr) {
1252 policyDesc->mPolicyMix = primaryMix;
1253 *output = policyDesc->mIoHandle;
jiabin24ff57a2023-11-27 21:06:51 +00001254 *selectedDeviceId = policyMixDevice != nullptr ? policyMixDevice->getId()
1255 : AUDIO_PORT_HANDLE_NONE;
1256 if ((policyDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) != AUDIO_OUTPUT_FLAG_DIRECT) {
1257 // Remove direct flag as it is not on a direct output.
1258 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1259 }
Eric Laurent8a1095a2019-11-08 14:44:16 -08001260
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08001261 ALOGV("getOutputForAttr() returns output %d", *output);
1262 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1263 *outputType = API_OUT_MIX_PLAYBACK;
1264 } else {
1265 *outputType = API_OUTPUT_LEGACY;
1266 }
1267 return NO_ERROR;
jiabin24ff57a2023-11-27 21:06:51 +00001268 } else {
1269 if (policyMixDevice != nullptr) {
1270 ALOGE("%s, try to use primary mix but no output found", __func__);
1271 return INVALID_OPERATION;
1272 }
1273 // Fallback to default engine selection as the selected primary mix device is not
1274 // available.
Eric Laurent8a1095a2019-11-08 14:44:16 -08001275 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07001276 }
François Gaffiec005e562018-11-06 15:04:49 +01001277 // Virtual sources must always be dynamicaly or explicitly routed
1278 if (resultAttr->usage == AUDIO_USAGE_VIRTUAL_SOURCE) {
1279 ALOGW("getOutputForAttr() no policy mix found for usage AUDIO_USAGE_VIRTUAL_SOURCE");
1280 return BAD_VALUE;
1281 }
1282 // explicit routing managed by getDeviceForStrategy in APM is now handled by engine
1283 // in order to let the choice of the order to future vendor engine
1284 outputDevices = mEngine->getOutputDevicesForAttributes(*resultAttr, requestedDevice, false);
Scott Randolph7b1fd232018-06-18 15:33:03 -07001285
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001286 if ((resultAttr->flags & AUDIO_FLAG_HW_AV_SYNC) != 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001287 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
Eric Laurent93c3d412014-08-01 14:48:35 -07001288 }
1289
Nadav Barb2f18162018-07-18 13:01:53 +03001290 // Set incall music only if device was explicitly set, and fallback to the device which is
1291 // chosen by the engine if not.
1292 // FIXME: provide a more generic approach which is not device specific and move this back
1293 // to getOutputForDevice.
Nadav Bar20919492018-11-20 10:20:51 +02001294 // TODO: Remove check of AUDIO_STREAM_MUSIC once migration is completed on the app side.
jiabin9a3361e2019-10-01 09:38:30 -07001295 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX) &&
François Gaffiec005e562018-11-06 15:04:49 +01001296 (*stream == AUDIO_STREAM_MUSIC || resultAttr->usage == AUDIO_USAGE_VOICE_COMMUNICATION) &&
Nadav Barb2f18162018-07-18 13:01:53 +03001297 audio_is_linear_pcm(config->format) &&
Eric Laurent74b71512019-11-06 17:21:57 -08001298 isCallAudioAccessible()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01001299 if (requestedPortId != AUDIO_PORT_HANDLE_NONE) {
Nadav Barb2f18162018-07-18 13:01:53 +03001300 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_INCALL_MUSIC;
François Gaffief579db52018-11-13 11:25:16 +01001301 *isRequestedDeviceForExclusiveUse = true;
Nadav Barb2f18162018-07-18 13:01:53 +03001302 }
1303 }
1304
François Gaffiec005e562018-11-06 15:04:49 +01001305 ALOGV("%s() device %s, sampling rate %d, format %#x, channel mask %#x, flags %#x stream %s",
1306 __func__, outputDevices.toString().c_str(), config->sample_rate, config->format,
1307 config->channel_mask, *flags, toString(*stream).c_str());
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001308
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001309 *output = AUDIO_IO_HANDLE_NONE;
François Gaffie11d30102018-11-02 16:09:09 +01001310 if (!msdDevices.isEmpty()) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001311 *output = getOutputForDevices(msdDevices, session, resultAttr, config, flags, isSpatialized);
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001312 if (*output != AUDIO_IO_HANDLE_NONE && setMsdOutputPatches(&outputDevices) == NO_ERROR) {
François Gaffiec005e562018-11-06 15:04:49 +01001313 ALOGV("%s() Using MSD devices %s instead of devices %s",
1314 __func__, msdDevices.toString().c_str(), outputDevices.toString().c_str());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001315 } else {
1316 *output = AUDIO_IO_HANDLE_NONE;
1317 }
1318 }
1319 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabina84c3d32022-12-02 18:59:55 +00001320 sp<PreferredMixerAttributesInfo> info = nullptr;
1321 if (outputDevices.size() == 1) {
1322 info = getPreferredMixerAttributesInfo(
1323 outputDevices.itemAt(0)->getId(),
jiabind9a58d32023-06-01 17:57:30 +00001324 mEngine->getProductStrategyForAttributes(*resultAttr),
1325 true /*activeBitPerfectPreferred*/);
jiabin5eaf0962022-12-20 20:11:38 +00001326 // Only use preferred mixer if the uid matches or the preferred mixer is bit-perfect
1327 // and it is currently active.
1328 if (info != nullptr && info->getUid() != uid &&
1329 ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_NONE ||
1330 info->getActiveClientCount() == 0)) {
jiabina84c3d32022-12-02 18:59:55 +00001331 info = nullptr;
1332 }
1333 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001334 *output = getOutputForDevices(outputDevices, session, resultAttr, config,
jiabina84c3d32022-12-02 18:59:55 +00001335 flags, isSpatialized, info, resultAttr->flags & AUDIO_FLAG_MUTE_HAPTIC);
jiabin5eaf0962022-12-20 20:11:38 +00001336 // The client will be active if the client is currently preferred mixer owner and the
1337 // requested configuration matches the preferred mixer configuration.
jiabinc658e452022-10-21 20:52:21 +00001338 *isBitPerfect = (info != nullptr
1339 && (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
jiabin5eaf0962022-12-20 20:11:38 +00001340 && info->getUid() == uid
1341 && *output != AUDIO_IO_HANDLE_NONE
1342 // When bit-perfect output is selected for the preferred mixer attributes owner,
1343 // only need to consider the config matches.
1344 && mOutputs.valueFor(*output)->isConfigurationMatched(
1345 clientConfig, AUDIO_OUTPUT_FLAG_NONE));
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001346 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001347 if (*output == AUDIO_IO_HANDLE_NONE) {
jiabinf1c73972022-04-14 16:28:52 -07001348 AudioProfileVector profiles;
1349 status_t ret = getProfilesForDevices(outputDevices, profiles, *flags, false /*isInput*/);
1350 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00001351 const auto channels = profiles[0]->getChannels();
1352 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
1353 config->channel_mask = *channels.begin();
1354 }
1355 const auto sampleRates = profiles[0]->getSampleRates();
1356 if (!sampleRates.empty() &&
1357 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
1358 config->sample_rate = *sampleRates.begin();
1359 }
jiabinf1c73972022-04-14 16:28:52 -07001360 config->format = profiles[0]->getFormat();
1361 }
Eric Laurente83b55d2014-11-14 10:06:21 -08001362 return INVALID_OPERATION;
1363 }
Paul McLeanaa981192015-03-21 09:55:15 -07001364
François Gaffiec005e562018-11-06 15:04:49 +01001365 *selectedDeviceId = getFirstDeviceId(outputDevices);
Michael Chan6fb34492020-12-08 15:44:49 +11001366 for (auto &outputDevice : outputDevices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001367 if (outputDevice->getId() == mConfig->getDefaultOutputDevice()->getId()) {
Michael Chan6fb34492020-12-08 15:44:49 +11001368 *selectedDeviceId = outputDevice->getId();
1369 break;
1370 }
1371 }
Eric Laurent2ac76942017-06-22 17:17:09 -07001372
Eric Laurent8a1095a2019-11-08 14:44:16 -08001373 if (outputDevices.onlyContainsDevicesWithType(AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
1374 *outputType = API_OUTPUT_TELEPHONY_TX;
1375 } else {
1376 *outputType = API_OUTPUT_LEGACY;
1377 }
1378
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001379 ALOGV("%s returns output %d selectedDeviceId %d", __func__, *output, *selectedDeviceId);
1380
1381 return NO_ERROR;
1382}
1383
1384status_t AudioPolicyManager::getOutputForAttr(const audio_attributes_t *attr,
1385 audio_io_handle_t *output,
1386 audio_session_t session,
1387 audio_stream_type_t *stream,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001388 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07001389 audio_config_t *config,
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001390 audio_output_flags_t *flags,
1391 audio_port_handle_t *selectedDeviceId,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001392 audio_port_handle_t *portId,
Eric Laurent8a1095a2019-11-08 14:44:16 -08001393 std::vector<audio_io_handle_t> *secondaryOutputs,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001394 output_type_t *outputType,
jiabinc658e452022-10-21 20:52:21 +00001395 bool *isSpatialized,
1396 bool *isBitPerfect)
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001397{
1398 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
1399 if (*portId != AUDIO_PORT_HANDLE_NONE) {
1400 return INVALID_OPERATION;
1401 }
Philip P. Moltmannbda45752020-07-17 16:41:18 -07001402 const uid_t uid = VALUE_OR_RETURN_STATUS(
Svet Ganov3e5f14f2021-05-13 22:51:08 +00001403 aidl2legacy_int32_t_uid_t(attributionSource.uid));
Francois Gaffie716e1432019-01-14 16:58:59 +01001404 const audio_port_handle_t requestedPortId = *selectedDeviceId;
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001405 audio_attributes_t resultAttr;
François Gaffief579db52018-11-13 11:25:16 +01001406 bool isRequestedDeviceForExclusiveUse = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07001407 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001408 const sp<DeviceDescriptor> requestedDevice =
1409 mAvailableOutputDevices.getDeviceFromId(requestedPortId);
1410
1411 // Prevent from storing invalid requested device id in clients
1412 const audio_port_handle_t sanitizedRequestedPortId =
1413 requestedDevice != nullptr ? requestedPortId : AUDIO_PORT_HANDLE_NONE;
1414 *selectedDeviceId = sanitizedRequestedPortId;
1415
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001416 status_t status = getOutputForAttrInt(&resultAttr, output, session, attr, stream, uid,
Kevin Rocard153f92d2018-12-18 18:33:28 -08001417 config, flags, selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00001418 secondaryOutputs != nullptr ? &secondaryMixes : nullptr, outputType, isSpatialized,
1419 isBitPerfect);
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001420 if (status != NO_ERROR) {
1421 return status;
1422 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001423 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryOutputDescs;
Eric Laurentc529cf62020-04-17 18:19:10 -07001424 if (secondaryOutputs != nullptr) {
1425 for (auto &secondaryMix : secondaryMixes) {
1426 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
1427 if (outputDesc != nullptr &&
1428 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
1429 secondaryOutputs->push_back(outputDesc->mIoHandle);
1430 weakSecondaryOutputDescs.push_back(outputDesc);
1431 }
1432 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08001433 }
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001434
Eric Laurent8fc147b2018-07-22 19:13:55 -07001435 audio_config_base_t clientConfig = {.sample_rate = config->sample_rate,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001436 .channel_mask = config->channel_mask,
Eric Laurent8fc147b2018-07-22 19:13:55 -07001437 .format = config->format,
Nick Desaulniersa30e3202019-10-18 13:38:23 -07001438 };
jiabin4ef93452019-09-10 14:29:54 -07001439 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07001440
Eric Laurentc209fe42020-06-05 18:11:23 -07001441 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(*output);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001442 sp<TrackClientDescriptor> clientDesc =
Hongwei Wangbb93dfb2018-10-23 13:54:22 -07001443 new TrackClientDescriptor(*portId, uid, session, resultAttr, clientConfig,
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001444 sanitizedRequestedPortId, *stream,
François Gaffiec005e562018-11-06 15:04:49 +01001445 mEngine->getProductStrategyForAttributes(resultAttr),
François Gaffieaaac0fd2018-11-22 17:56:39 +01001446 toVolumeSource(resultAttr),
Kevin Rocard153f92d2018-12-18 18:33:28 -08001447 *flags, isRequestedDeviceForExclusiveUse,
Eric Laurentc209fe42020-06-05 18:11:23 -07001448 std::move(weakSecondaryOutputDescs),
1449 outputDesc->mPolicyMix);
Andy Hung39efb7a2018-09-26 15:39:28 -07001450 outputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07001451
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01001452 ALOGV("%s() returns output %d requestedPortId %d selectedDeviceId %d for port ID %d", __func__,
1453 *output, requestedPortId, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07001454
Eric Laurente83b55d2014-11-14 10:06:21 -08001455 return NO_ERROR;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001456}
1457
Eric Laurentc529cf62020-04-17 18:19:10 -07001458status_t AudioPolicyManager::openDirectOutput(audio_stream_type_t stream,
1459 audio_session_t session,
1460 const audio_config_t *config,
1461 audio_output_flags_t flags,
1462 const DeviceVector &devices,
1463 audio_io_handle_t *output) {
1464
1465 *output = AUDIO_IO_HANDLE_NONE;
1466
1467 // skip direct output selection if the request can obviously be attached to a mixed output
1468 // and not explicitly requested
1469 if (((flags & AUDIO_OUTPUT_FLAG_DIRECT) == 0) &&
1470 audio_is_linear_pcm(config->format) && config->sample_rate <= SAMPLE_RATE_HZ_MAX &&
1471 audio_channel_count_from_out_mask(config->channel_mask) <= 2) {
1472 return NAME_NOT_FOUND;
1473 }
1474
1475 // Do not allow offloading if one non offloadable effect is enabled or MasterMono is enabled.
1476 // This prevents creating an offloaded track and tearing it down immediately after start
1477 // when audioflinger detects there is an active non offloadable effect.
1478 // FIXME: We should check the audio session here but we do not have it in this context.
1479 // This may prevent offloading in rare situations where effects are left active by apps
1480 // in the background.
1481 sp<IOProfile> profile;
1482 if (((flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) == 0) ||
1483 !(mEffects.isNonOffloadableEffectEnabled() || mMasterMono)) {
1484 profile = getProfileForOutput(
1485 devices, config->sample_rate, config->format, config->channel_mask,
1486 flags, true /* directOnly */);
1487 }
1488
1489 if (profile == nullptr) {
1490 return NAME_NOT_FOUND;
1491 }
1492
1493 // exclusive outputs for MMAP and Offload are enforced by different session ids.
1494 for (size_t i = 0; i < mOutputs.size(); i++) {
1495 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
1496 if (!desc->isDuplicated() && (profile == desc->mProfile)) {
1497 // reuse direct output if currently open by the same client
1498 // and configured with same parameters
1499 if ((config->sample_rate == desc->getSamplingRate()) &&
1500 (config->format == desc->getFormat()) &&
1501 (config->channel_mask == desc->getChannelMask()) &&
1502 (session == desc->mDirectClientSession)) {
1503 desc->mDirectOpenCount++;
Eric Laurentfecbceb2021-02-09 14:46:43 +01001504 ALOGV("%s reusing direct output %d for session %d", __func__,
Eric Laurentc529cf62020-04-17 18:19:10 -07001505 mOutputs.keyAt(i), session);
1506 *output = mOutputs.keyAt(i);
1507 return NO_ERROR;
1508 }
1509 }
1510 }
1511
1512 if (!profile->canOpenNewIo()) {
Atneya Nairb16666a2023-12-11 20:18:33 -08001513 if (!com::android::media::audioserver::direct_track_reprioritization()) {
1514 return NAME_NOT_FOUND;
1515 } else if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) != 0) {
1516 // MMAP gracefully handles lack of an exclusive track resource by mixing
1517 // above the audio framework. For AAudio to know that the limit is reached,
1518 // return an error.
1519 return NAME_NOT_FOUND;
1520 } else {
1521 // Close outputs on this profile, if available, to free resources for this request
1522 for (int i = 0; i < mOutputs.size() && !profile->canOpenNewIo(); i++) {
1523 const auto desc = mOutputs.valueAt(i);
1524 if (desc->mProfile == profile) {
1525 closeOutput(desc->mIoHandle);
1526 }
1527 }
1528 }
1529 }
1530
1531 // Unable to close streams to find free resources for this request
1532 if (!profile->canOpenNewIo()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07001533 return NAME_NOT_FOUND;
1534 }
1535
Atneya Nairb16666a2023-12-11 20:18:33 -08001536 auto outputDesc = sp<SwAudioOutputDescriptor>::make(profile, mpClientInterface);
Eric Laurentc529cf62020-04-17 18:19:10 -07001537
Michael Chan6fb34492020-12-08 15:44:49 +11001538 // An MSD patch may be using the only output stream that can service this request. Release
1539 // all MSD patches to prioritize this request over any active output on MSD.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001540 releaseMsdOutputPatches(devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07001541
Eric Laurentf1f22e72021-07-13 14:04:14 +02001542 status_t status =
1543 outputDesc->open(config, nullptr /* mixerConfig */, devices, stream, flags, output);
Eric Laurentc529cf62020-04-17 18:19:10 -07001544
1545 // only accept an output with the requested parameters
1546 if (status != NO_ERROR ||
1547 (config->sample_rate != 0 && config->sample_rate != outputDesc->getSamplingRate()) ||
1548 (config->format != AUDIO_FORMAT_DEFAULT && config->format != outputDesc->getFormat()) ||
1549 (config->channel_mask != 0 && config->channel_mask != outputDesc->getChannelMask())) {
1550 ALOGV("%s failed opening direct output: output %d sample rate %d %d,"
1551 "format %d %d, channel mask %04x %04x", __func__, *output, config->sample_rate,
1552 outputDesc->getSamplingRate(), config->format, outputDesc->getFormat(),
1553 config->channel_mask, outputDesc->getChannelMask());
1554 if (*output != AUDIO_IO_HANDLE_NONE) {
1555 outputDesc->close();
1556 }
1557 // fall back to mixer output if possible when the direct output could not be open
1558 if (audio_is_linear_pcm(config->format) &&
1559 config->sample_rate <= SAMPLE_RATE_HZ_MAX) {
1560 return NAME_NOT_FOUND;
1561 }
1562 *output = AUDIO_IO_HANDLE_NONE;
1563 return BAD_VALUE;
1564 }
1565 outputDesc->mDirectOpenCount = 1;
1566 outputDesc->mDirectClientSession = session;
1567
1568 addOutput(*output, outputDesc);
1569 mPreviousOutputs = mOutputs;
1570 ALOGV("%s returns new direct output %d", __func__, *output);
1571 mpClientInterface->onAudioPortListUpdate();
1572 return NO_ERROR;
1573}
1574
François Gaffie11d30102018-11-02 16:09:09 +01001575audio_io_handle_t AudioPolicyManager::getOutputForDevices(
1576 const DeviceVector &devices,
Kevin Rocard169753c2017-03-06 14:18:23 -08001577 audio_session_t session,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001578 const audio_attributes_t *attr,
Eric Laurentfe231122017-11-17 17:48:06 -08001579 const audio_config_t *config,
jiabine375d412019-02-26 12:54:53 -08001580 audio_output_flags_t *flags,
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001581 bool *isSpatialized,
jiabina84c3d32022-12-02 18:59:55 +00001582 sp<PreferredMixerAttributesInfo> prefMixerConfigInfo,
jiabine375d412019-02-26 12:54:53 -08001583 bool forceMutingHaptic)
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001584{
Andy Hungc88b0642018-04-27 15:42:35 -07001585 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Jean-Michel Trivi5bd3f382014-06-13 16:06:54 -07001586
jiabine375d412019-02-26 12:54:53 -08001587 // Discard haptic channel mask when forcing muting haptic channels.
1588 audio_channel_mask_t channelMask = forceMutingHaptic
Mikhail Naganov55773032020-10-01 15:08:13 -07001589 ? static_cast<audio_channel_mask_t>(config->channel_mask & ~AUDIO_CHANNEL_HAPTIC_ALL)
1590 : config->channel_mask;
jiabine375d412019-02-26 12:54:53 -08001591
Eric Laurente552edb2014-03-10 17:42:56 -07001592 // open a direct output if required by specified parameters
1593 //force direct flag if offload flag is set: offloading implies a direct output stream
1594 // and all common behaviors are driven by checking only the direct flag
1595 // this should normally be set appropriately in the policy configuration file
Nadav Bar766fb022018-01-07 12:18:03 +02001596 if ((*flags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
1597 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurente552edb2014-03-10 17:42:56 -07001598 }
Nadav Bar766fb022018-01-07 12:18:03 +02001599 if ((*flags & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) {
1600 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_DIRECT);
Eric Laurent93c3d412014-08-01 14:48:35 -07001601 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001602
1603 audio_stream_type_t stream = mEngine->getStreamTypeForAttributes(*attr);
1604
Eric Laurente83b55d2014-11-14 10:06:21 -08001605 // only allow deep buffering for music stream type
1606 if (stream != AUDIO_STREAM_MUSIC) {
Nadav Bar766fb022018-01-07 12:18:03 +02001607 *flags = (audio_output_flags_t)(*flags &~AUDIO_OUTPUT_FLAG_DEEP_BUFFER);
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001608 } else if (/* stream == AUDIO_STREAM_MUSIC && */
Nadav Bar766fb022018-01-07 12:18:03 +02001609 *flags == AUDIO_OUTPUT_FLAG_NONE &&
Ravi Kumar Alamanda439e4ed2015-04-03 12:13:21 -07001610 property_get_bool("audio.deep_buffer.media", false /* default_value */)) {
1611 // use DEEP_BUFFER as default output for music stream type
Nadav Bar766fb022018-01-07 12:18:03 +02001612 *flags = (audio_output_flags_t)AUDIO_OUTPUT_FLAG_DEEP_BUFFER;
Eric Laurente83b55d2014-11-14 10:06:21 -08001613 }
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001614 if (stream == AUDIO_STREAM_TTS) {
Nadav Bar766fb022018-01-07 12:18:03 +02001615 *flags = AUDIO_OUTPUT_FLAG_TTS;
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001616 } else if (stream == AUDIO_STREAM_VOICE_CALL &&
Nadav Bar20919492018-11-20 10:20:51 +02001617 audio_is_linear_pcm(config->format) &&
1618 (*flags & AUDIO_OUTPUT_FLAG_INCALL_MUSIC) == 0) {
Nadav Bar766fb022018-01-07 12:18:03 +02001619 *flags = (audio_output_flags_t)(AUDIO_OUTPUT_FLAG_VOIP_RX |
Haynes Mathew George84c621e2017-04-25 11:41:50 -07001620 AUDIO_OUTPUT_FLAG_DIRECT);
1621 ALOGV("Set VoIP and Direct output flags for PCM format");
Ravi Kumar Alamandac36a8892015-04-24 16:35:49 -07001622 }
Eric Laurente552edb2014-03-10 17:42:56 -07001623
Carter Hsua3abb402021-10-26 11:11:20 +08001624 // Attach the Ultrasound flag for the AUDIO_CONTENT_TYPE_ULTRASOUND
1625 if (attr->content_type == AUDIO_CONTENT_TYPE_ULTRASOUND) {
1626 *flags = (audio_output_flags_t)(*flags | AUDIO_OUTPUT_FLAG_ULTRASOUND);
1627 }
1628
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001629 *isSpatialized = false;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001630 if (mSpatializerOutput != nullptr
jiabin2462ce82024-01-12 20:37:59 +00001631 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())
1632 && prefMixerConfigInfo == nullptr) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001633 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001634 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001635 }
1636
Eric Laurentc529cf62020-04-17 18:19:10 -07001637 audio_config_t directConfig = *config;
1638 directConfig.channel_mask = channelMask;
1639 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1640 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001641 return output;
1642 }
1643
Eric Laurent14cbfca2016-03-17 09:42:16 -07001644 // A request for HW A/V sync cannot fallback to a mixed output because time
1645 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001646 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001647 return AUDIO_IO_HANDLE_NONE;
1648 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001649 // A request for Tuner cannot fallback to a mixed output
1650 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1651 return AUDIO_IO_HANDLE_NONE;
1652 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001653
Eric Laurente552edb2014-03-10 17:42:56 -07001654 // ignoring channel mask due to downmix capability in mixer
1655
1656 // open a non direct output
1657
1658 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001659 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001660 // get which output is suitable for the specified stream. The actual
1661 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001662 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001663 if (prefMixerConfigInfo != nullptr) {
1664 for (audio_io_handle_t outputHandle : outputs) {
1665 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1666 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1667 output = outputHandle;
1668 break;
1669 }
1670 }
1671 if (output == AUDIO_IO_HANDLE_NONE) {
1672 // No output open with the preferred profile. Open a new one.
1673 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1674 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1675 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1676 config.format = prefMixerConfigInfo->getConfigBase().format;
1677 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1678 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1679 &config, prefMixerConfigInfo->getFlags());
1680 if (preferredOutput == nullptr) {
1681 ALOGE("%s failed to open output with preferred mixer config", __func__);
1682 } else {
1683 output = preferredOutput->mIoHandle;
1684 }
1685 }
1686 } else {
1687 // at this stage we should ignore the DIRECT flag as no direct output could be
1688 // found earlier
1689 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1690 output = selectOutput(
1691 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1692 }
Eric Laurente552edb2014-03-10 17:42:56 -07001693 }
François Gaffie11d30102018-11-02 16:09:09 +01001694 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001695 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001696 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001697
Eric Laurente552edb2014-03-10 17:42:56 -07001698 return output;
1699}
1700
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001701sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001702 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1703 mAvailableInputDevices);
1704 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1705}
1706
1707DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1708 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1709 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001710}
1711
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001712const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001713 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001714 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1715 if (msdModule != 0) {
1716 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1717 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1718 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1719 const struct audio_port_config *source = &patch->mPatch.sources[j];
1720 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1721 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001722 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001723 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001724 }
1725 }
1726 }
1727 return msdPatches;
1728}
1729
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001730bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1731 ssize_t index = mAudioPatches.indexOfKey(handle);
1732 if (index < 0) {
1733 return false;
1734 }
1735 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1736 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1737 if (msdModule == nullptr) {
1738 return false;
1739 }
1740 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1741 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1742 return true;
1743 }
1744 index = getMsdOutputPatches().indexOfKey(handle);
1745 if (index < 0) {
1746 return false;
1747 }
1748 return true;
1749}
1750
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001751status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1752 const InputProfileCollection &inputProfiles,
1753 const OutputProfileCollection &outputProfiles,
1754 const sp<DeviceDescriptor> &sourceDevice,
1755 const sp<DeviceDescriptor> &sinkDevice,
1756 AudioProfileVector& sourceProfiles,
1757 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001758 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001759 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001760 return NO_INIT;
1761 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001762 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001763 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001764 return NO_INIT;
1765 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001766 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001767 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1768 inProfile->supportsDevice(sourceDevice)) {
1769 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001770 }
1771 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001772 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001773 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001774 outProfile->supportsDevice(sinkDevice)) {
1775 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001776 }
1777 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001778 return NO_ERROR;
1779}
1780
1781status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1782 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1783 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1784{
Dean Wheatley16809da2022-12-09 14:55:46 +11001785 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1786 static const std::vector<audio_format_t> formatsOrder = {{
1787 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001788 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1789 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001790 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1791 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1792 // preferred).
1793 std::vector<audio_channel_mask_t> masks = {{
1794 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1795 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1796 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1797 // insert index masks (higher counts most preferred) as preferred over position masks
1798 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1799 masks.insert(
1800 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1801 }
1802 return masks;
1803 }();
1804
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001805 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001806 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1807 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001808 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001809 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1810 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001811 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001812 }
1813 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1814 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1815 sinkConfig->format = bestSinkConfig.format;
1816 // For encoded streams force direct flag to prevent downstream mixing.
1817 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1818 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001819 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1820 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001821 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001822 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1823 // raw and IEC61937 framed streams.
1824 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1825 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1826 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001827 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1828 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001829 sourceConfig->channel_mask =
1830 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1831 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1832 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001833 sourceConfig->format = bestSinkConfig.format;
1834 // Copy input stream directly without any processing (e.g. resampling).
1835 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1836 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1837 if (hwAvSync) {
1838 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1839 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1840 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1841 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1842 }
1843 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1844 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1845 sinkConfig->config_mask |= config_mask;
1846 sourceConfig->config_mask |= config_mask;
1847 return NO_ERROR;
1848}
1849
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001850PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1851 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001852{
1853 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001854 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1855 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1856 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1857 if (deviceModule == nullptr) {
1858 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1859 return patchBuilder;
1860 }
1861 const InputProfileCollection inputProfiles = msdIsSource ?
1862 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1863 const OutputProfileCollection outputProfiles = msdIsSource ?
1864 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1865
1866 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1867 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1868 device : getMsdAudioOutDevices().itemAt(0);
1869 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1870
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001871 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1872 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001873 AudioProfileVector sourceProfiles;
1874 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001875 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1876 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001877 for (auto hwAvSync : { true, false }) {
1878 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1879 sourceProfiles, sinkProfiles) != NO_ERROR) {
1880 continue;
1881 }
1882 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1883 &sinkConfig) == NO_ERROR) {
1884 // Found a matching config. Re-create PatchBuilder with this config.
1885 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1886 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001887 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001888 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001889 " supporting PCM format conversion.", __func__);
1890 return patchBuilder;
1891}
1892
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001893status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001894 DeviceVector devices;
1895 if (outputDevices != nullptr && outputDevices->size() > 0) {
1896 devices.add(*outputDevices);
1897 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001898 // Use media strategy for unspecified output device. This should only
1899 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1900 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001901 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001902 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001903 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001904 }
Michael Chan6fb34492020-12-08 15:44:49 +11001905 std::vector<PatchBuilder> patchesToCreate;
1906 for (auto i = 0u; i < devices.size(); ++i) {
1907 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001908 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001909 }
1910 // Retain only the MSD patches associated with outputDevices request.
1911 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001912 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001913 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1914 auto retainedPatch = false;
1915 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1916 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1917 patchesToRemove.removeItemsAt(i);
1918 retainedPatch = true;
1919 break;
1920 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001921 }
Michael Chan6fb34492020-12-08 15:44:49 +11001922 if (retainedPatch) {
1923 it = patchesToCreate.erase(it);
1924 continue;
1925 }
1926 ++it;
1927 }
1928 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1929 return NO_ERROR;
1930 }
1931 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1932 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001933 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001934 }
Michael Chan6fb34492020-12-08 15:44:49 +11001935 status_t status = NO_ERROR;
1936 for (const auto &p : patchesToCreate) {
1937 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1938 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1939 char message[256];
1940 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1941 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1942 currStatus == NO_ERROR ? "Success" : "Error",
1943 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1944 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1945 if (currStatus == NO_ERROR) {
1946 ALOGD("%s", message);
1947 } else {
1948 ALOGE("%s", message);
1949 if (status == NO_ERROR) {
1950 status = currStatus;
1951 }
1952 }
1953 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001954 return status;
1955}
1956
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001957void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1958 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001959 for (size_t i = 0; i < msdPatches.size(); i++) {
1960 const auto& patch = msdPatches[i];
1961 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1962 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1963 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1964 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1965 releaseAudioPatch(patch->getHandle(), mUidCached);
1966 break;
1967 }
1968 }
1969 }
1970}
1971
Dorin Drimus94d94412022-02-02 09:05:02 +01001972bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001973 DeviceVector devicesToCheck =
1974 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001975 AudioPatchCollection msdPatches = getMsdOutputPatches();
1976 for (size_t i = 0; i < msdPatches.size(); i++) {
1977 const auto& patch = msdPatches[i];
1978 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1979 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1980 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1981 const auto& foundDevice = devicesToCheck.getDevice(
1982 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1983 if (foundDevice != nullptr) {
1984 devicesToCheck.remove(foundDevice);
1985 if (devicesToCheck.isEmpty()) {
1986 return true;
1987 }
1988 }
1989 }
1990 }
1991 }
1992 return false;
1993}
1994
Eric Laurente0720872014-03-11 09:30:41 -07001995audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001996 audio_output_flags_t flags,
1997 audio_format_t format,
1998 audio_channel_mask_t channelMask,
1999 uint32_t samplingRate,
2000 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002001{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002002 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2003 "%s called with format %#x", __func__, format);
2004
jiabinebb6af42020-06-09 17:31:17 -07002005 // Return the output that haptic-generating attached to when 1) session id is specified,
2006 // 2) haptic-generating effect exists for given session id and 3) the output that
2007 // haptic-generating effect attached to is in given outputs.
2008 if (sessionId != AUDIO_SESSION_NONE) {
2009 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2010 sessionId, FX_IID_HAPTICGENERATOR);
2011 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2012 return hapticGeneratingOutput;
2013 }
2014 }
2015
Eric Laurent16c66dd2019-05-01 17:54:10 -07002016 // Flags disqualifying an output: the match must happen before calling selectOutput()
2017 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2018 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2019
2020 // Flags expressing a functional request: must be honored in priority over
2021 // other criteria
2022 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2023 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002024 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2025 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002026 // Flags expressing a performance request: have lower priority than serving
2027 // requested sampling rate or channel mask
2028 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2029 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2030 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2031
2032 const audio_output_flags_t functionalFlags =
2033 (audio_output_flags_t)(flags & kFunctionalFlags);
2034 const audio_output_flags_t performanceFlags =
2035 (audio_output_flags_t)(flags & kPerformanceFlags);
2036
2037 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2038
Eric Laurente552edb2014-03-10 17:42:56 -07002039 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002040 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002041 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002042 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002043 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002044 // with tiebreak preferring the minimum number of extra functional flags
2045 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002046 // 3: the output supporting the exact channel mask
2047 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002048 // 5: the output with the highest sampling rate if the requested sample rate is
2049 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002050 // 6: the output with the highest number of requested performance flags
2051 // 7: the output with the bit depth the closest to the requested one
2052 // 8: the primary output
2053 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002054
Eric Laurent16c66dd2019-05-01 17:54:10 -07002055 // matching criteria values in priority order for best matching output so far
2056 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002057
Eric Laurent16c66dd2019-05-01 17:54:10 -07002058 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2059 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2060 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002061
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002062 for (audio_io_handle_t output : outputs) {
2063 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002064 // matching criteria values in priority order for current output
2065 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002066
Eric Laurent16c66dd2019-05-01 17:54:10 -07002067 if (outputDesc->isDuplicated()) {
2068 continue;
2069 }
2070 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2071 continue;
2072 }
Eric Laurent8838a382014-09-08 16:44:28 -07002073
Eric Laurent16c66dd2019-05-01 17:54:10 -07002074 // If haptic channel is specified, use the haptic output if present.
2075 // When using haptic output, same audio format and sample rate are required.
2076 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002077 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002078 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2079 continue;
2080 }
2081 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002082 && format == outputDesc->getFormat()
2083 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002084 currentMatchCriteria[0] = outputHapticChannelCount;
2085 }
2086
2087 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002088 const int matchingFunctionalFlags =
2089 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2090 const int totalFunctionalFlags =
2091 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2092 // Prefer matching functional flags, but subtract unnecessary functional flags.
2093 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002094
2095 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002096 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2097 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002098 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2099 channelCount <= outputChannelCount) {
2100 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002101 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2102 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002103 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002104 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002105 currentMatchCriteria[3] = outputChannelCount;
2106 }
2107
2108 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002109 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002110 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002111 }
2112
2113 // performance flags match
2114 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2115
2116 // format match
2117 if (format != AUDIO_FORMAT_INVALID) {
2118 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002119 PolicyAudioPort::kFormatDistanceMax -
2120 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002121 }
2122
2123 // primary output match
2124 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2125
2126 // compare match criteria by priority then value
2127 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2128 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2129 bestMatchCriteria = currentMatchCriteria;
2130 bestOutput = output;
2131
2132 std::stringstream result;
2133 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2134 std::ostream_iterator<int>(result, " "));
2135 ALOGV("%s new bestOutput %d criteria %s",
2136 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002137 }
2138 }
2139
Eric Laurent16c66dd2019-05-01 17:54:10 -07002140 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002141}
2142
Eric Laurent8fc147b2018-07-22 19:13:55 -07002143status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002144{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002145 ALOGV("%s portId %d", __FUNCTION__, portId);
2146
2147 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2148 if (outputDesc == 0) {
2149 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002150 return BAD_VALUE;
2151 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002152 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002153
Eric Laurent8fc147b2018-07-22 19:13:55 -07002154 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002155 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002156
Eric Laurent733ce942017-12-07 12:18:25 -08002157 status_t status = outputDesc->start();
2158 if (status != NO_ERROR) {
2159 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002160 }
2161
Eric Laurent97ac8712018-07-27 18:59:02 -07002162 uint32_t delayMs;
2163 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002164
2165 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002166 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002167 if (status == DEAD_OBJECT) {
2168 sp<SwAudioOutputDescriptor> desc =
2169 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2170 if (desc == nullptr) {
2171 // This is not common, it may indicate something wrong with the HAL.
2172 ALOGE("%s unable to open output with default config", __func__);
2173 return status;
2174 }
2175 desc->mUsePreferredMixerAttributes = true;
2176 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002177 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002178 }
jiabina84c3d32022-12-02 18:59:55 +00002179
2180 // If the client is the first one active on preferred mixer parameters, reopen the output
2181 // if the current mixer parameters doesn't match the preferred one.
2182 if (outputDesc->devices().size() == 1) {
2183 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2184 outputDesc->devices()[0]->getId(), client->strategy());
2185 if (info != nullptr && info->getUid() == client->uid()) {
2186 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2187 info->getConfigBase(), info->getFlags())) {
2188 stopSource(outputDesc, client);
2189 outputDesc->stop();
2190 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2191 config.channel_mask = info->getConfigBase().channel_mask;
2192 config.sample_rate = info->getConfigBase().sample_rate;
2193 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002194 sp<SwAudioOutputDescriptor> desc =
2195 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2196 if (desc == nullptr) {
2197 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002198 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002199 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002200 // Intentionally return error to let the client side resending request for
2201 // creating and starting.
2202 return DEAD_OBJECT;
2203 }
2204 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002205 if (info->getActiveClientCount() == 1 &&
2206 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2207 // If it is first bit-perfect client, reroute all clients that will be routed to
2208 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2209 PortHandleVector clientsToInvalidate;
2210 for (size_t i = 0; i < mOutputs.size(); i++) {
2211 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002212 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002213 continue;
2214 }
2215 for (const auto& c : mOutputs[i]->getClientIterable()) {
2216 clientsToInvalidate.push_back(c->portId());
2217 }
2218 }
2219 if (!clientsToInvalidate.empty()) {
2220 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2221 __func__);
2222 mpClientInterface->invalidateTracks(clientsToInvalidate);
2223 }
2224 }
jiabina84c3d32022-12-02 18:59:55 +00002225 }
2226 }
2227
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002228 if (client->hasPreferredDevice()) {
2229 // playback activity with preferred device impacts routing occurred, inform upper layers
2230 mpClientInterface->onRoutingUpdated();
2231 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002232 if (delayMs != 0) {
2233 usleep(delayMs * 1000);
2234 }
2235
2236 return status;
2237}
2238
Eric Laurent96d1dda2022-03-14 17:14:19 +01002239bool AudioPolicyManager::isLeUnicastActive() const {
2240 if (isInCall()) {
2241 return true;
2242 }
2243 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2244}
2245
2246bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2247 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2248 return false;
2249 }
2250 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2251 ALOGV("%s active %d", __func__, active);
2252 return active;
2253}
2254
Eric Laurent97ac8712018-07-27 18:59:02 -07002255status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2256 const sp<TrackClientDescriptor>& client,
2257 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002258{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002259 // cannot start playback of STREAM_TTS if any other output is being used
2260 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002261
2262 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002263 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002264 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002265 auto clientStrategy = client->strategy();
2266 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002267 if (stream == AUDIO_STREAM_TTS) {
2268 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002269 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002270 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002271 return INVALID_OPERATION;
2272 } else {
2273 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2274 }
2275 } else {
2276 // some playback other than beacon starts
2277 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2278 }
2279
Eric Laurent77305a62016-07-25 16:39:22 -07002280 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002281 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002282 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002283
François Gaffie11d30102018-11-02 16:09:09 +01002284 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002285 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002286 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002287 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002288 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002289 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002290 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002291 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002292 } else {
2293 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002294 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002295 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2296 AUDIO_FORMAT_DEFAULT);
2297 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2298 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002299 }
2300
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002301 // requiresMuteCheck is false when we can bypass mute strategy.
2302 // It covers a common case when there is no materially active audio
2303 // and muting would result in unnecessary delay and dropped audio.
2304 const uint32_t outputLatencyMs = outputDesc->latency();
2305 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002306 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002307
Eric Laurente552edb2014-03-10 17:42:56 -07002308 // increment usage count for this stream on the requested output:
2309 // NOTE that the usage count is the same for duplicated output and hardware output which is
2310 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002311 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002312
2313 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002314 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002315 // Preferred device may be exclusive, use only if no other active clients on this output
2316 devices = DeviceVector(
2317 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2318 } else {
2319 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2320 }
François Gaffie11d30102018-11-02 16:09:09 +01002321 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002322 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002323 }
2324 }
Eric Laurente552edb2014-03-10 17:42:56 -07002325
François Gaffiec005e562018-11-06 15:04:49 +01002326 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002327 selectOutputForMusicEffects();
2328 }
2329
François Gaffie1c878552018-11-22 16:53:21 +01002330 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002331 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002332 if (devices.isEmpty()) {
2333 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002334 }
François Gaffiec005e562018-11-06 15:04:49 +01002335 bool shouldWait =
2336 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2337 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2338 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002339 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002340 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002341 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002342 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002343 // An output has a shared device if
2344 // - managed by the same hw module
2345 // - supports the currently selected device
2346 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002347 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002348
Eric Laurent77305a62016-07-25 16:39:22 -07002349 // force a device change if any other output is:
2350 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002351 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002352 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002353 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002354 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002355 // change the device currently selected by the other output.
2356 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002357 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002358 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002359 force = true;
2360 }
2361 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002362 // a notification so that audio focus effect can propagate, or that a mute/unmute
2363 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002364 const uint32_t latencyMs = desc->latency();
2365 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2366
2367 if (shouldWait && isActive && (waitMs < latencyMs)) {
2368 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002369 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002370
2371 // Require mute check if another output is on a shared device
2372 // and currently active to have proper drain and avoid pops.
2373 // Note restoring AudioTracks onto this output needs to invoke
2374 // a volume ramp if there is no mute.
2375 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002376 }
2377 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002378
jiabin3ff8d7d2022-12-13 06:27:44 +00002379 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2380 // If the output is open with preferred mixer attributes, but the routed device is
2381 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2382 // changed.
2383 return DEAD_OBJECT;
2384 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002385 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302386 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2387 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002388
Eric Laurente552edb2014-03-10 17:42:56 -07002389 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002390 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002391 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002392 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002393 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002394 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002395 outputDesc->useHwGain() /*force*/)) {
2396 // request AudioService to reinitialize the volume curves asynchronously
2397 ALOGE("checkAndSetVolume failed, requesting volume range init");
2398 mpClientInterface->onVolumeRangeInitRequest();
2399 };
Eric Laurente552edb2014-03-10 17:42:56 -07002400
2401 // update the outputs if starting an output with a stream that can affect notification
2402 // routing
2403 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002404
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002405 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002406 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002407 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002408 }
Eric Laurentdc462862016-07-19 12:29:53 -07002409
2410 if (waitMs > muteWaitMs) {
2411 *delayMs = waitMs - muteWaitMs;
2412 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002413
2414 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2415 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2416 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2417 // change occurs after the MixerThread starts and causes a stream volume
2418 // glitch.
2419 //
2420 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002421 }
Eric Laurentdc462862016-07-19 12:29:53 -07002422
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002423 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002424 mEngine->getForceUse(
2425 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002426 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002427 }
2428
Eric Laurent97ac8712018-07-27 18:59:02 -07002429 // Automatically enable the remote submix input when output is started on a re routing mix
2430 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002431 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2432 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002433 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2434 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2435 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002436 "remote-submix",
2437 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002438 }
2439
Eric Laurent96d1dda2022-03-14 17:14:19 +01002440 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2441
Eric Laurente552edb2014-03-10 17:42:56 -07002442 return NO_ERROR;
2443}
2444
Eric Laurent96d1dda2022-03-14 17:14:19 +01002445void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2446 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2447 bool isUnicastActive = isLeUnicastActive();
2448
2449 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002450 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002451 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2452 for (size_t i = 0; i < mOutputs.size(); i++) {
2453 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2454 if (desc != ignoredOutput && desc->isActive()
2455 && ((isUnicastActive &&
2456 !desc->devices().
2457 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2458 || (wasUnicastActive &&
2459 !desc->devices().getDevicesFromTypes(
2460 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2461 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2462 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002463 if (desc->mUsePreferredMixerAttributes && force) {
2464 // If the device is using preferred mixer attributes, the output need to reopen
2465 // with default configuration when the new selected devices are different from
2466 // current routing devices.
2467 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2468 continue;
2469 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302470 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002471 // re-apply device specific volume if not done by setOutputDevice()
2472 if (!force) {
2473 applyStreamVolumes(desc, newDevices.types(), delayMs);
2474 }
2475 }
2476 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002477 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002478 }
2479}
2480
Eric Laurent8fc147b2018-07-22 19:13:55 -07002481status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002482{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002483 ALOGV("%s portId %d", __FUNCTION__, portId);
2484
2485 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2486 if (outputDesc == 0) {
2487 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002488 return BAD_VALUE;
2489 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002490 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002491
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002492 if (client->hasPreferredDevice(true)) {
2493 // playback activity with preferred device impacts routing occurred, inform upper layers
2494 mpClientInterface->onRoutingUpdated();
2495 }
2496
Eric Laurent97ac8712018-07-27 18:59:02 -07002497 ALOGV("stopOutput() output %d, stream %d, session %d",
2498 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002499
Eric Laurent97ac8712018-07-27 18:59:02 -07002500 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002501
Eric Laurent733ce942017-12-07 12:18:25 -08002502 if (status == NO_ERROR ) {
2503 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002504 } else {
2505 return status;
2506 }
2507
2508 if (outputDesc->devices().size() == 1) {
2509 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2510 outputDesc->devices()[0]->getId(), client->strategy());
2511 if (info != nullptr && info->getUid() == client->uid()) {
2512 info->decreaseActiveClient();
2513 if (info->getActiveClientCount() == 0) {
2514 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2515 }
2516 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002517 }
2518 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002519}
2520
Eric Laurent97ac8712018-07-27 18:59:02 -07002521status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2522 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002523{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002524 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002525 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002526 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002527 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002528
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002529 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2530
François Gaffie1c878552018-11-22 16:53:21 +01002531 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2532 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002533 // Automatically disable the remote submix input when output is stopped on a
2534 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002535 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002536 if (isSingleDeviceType(
2537 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002538 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002539 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002540 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2541 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002542 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002543 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002544 }
2545 }
2546 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002547 if (client->hasPreferredDevice(true) &&
2548 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002549 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002550 forceDeviceUpdate = true;
2551 }
2552
Eric Laurente552edb2014-03-10 17:42:56 -07002553 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002554 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002555
Eric Laurente552edb2014-03-10 17:42:56 -07002556 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002557 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002558 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002559 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002560
2561 // If the routing does not change, if an output is routed on a device using HwGain
2562 // (aka setAudioPortConfig) and there are still active clients following different
2563 // volume group(s), force reapply volume
2564 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2565 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2566
Eric Laurente552edb2014-03-10 17:42:56 -07002567 // delay the device switch by twice the latency because stopOutput() is executed when
2568 // the track stop() command is received and at that time the audio track buffer can
2569 // still contain data that needs to be drained. The latency only covers the audio HAL
2570 // and kernel buffers. Also the latency does not always include additional delay in the
2571 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302572 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002573 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002574
2575 // force restoring the device selection on other active outputs if it differs from the
2576 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002577 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002578 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002579 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002580 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002581 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002582 desc->isActive() &&
2583 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002584 (newDevices != desc->devices())) {
2585 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2586 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002587
jiabin3ff8d7d2022-12-13 06:27:44 +00002588 if (desc->mUsePreferredMixerAttributes && force) {
2589 // If the device is using preferred mixer attributes, the output need to
2590 // reopen with default configuration when the new selected devices are
2591 // different from current routing devices.
2592 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2593 continue;
2594 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302595 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002596
Eric Laurent57de36c2016-09-28 16:59:11 -07002597 // re-apply device specific volume if not done by setOutputDevice()
2598 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002599 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002600 }
Eric Laurente552edb2014-03-10 17:42:56 -07002601 }
2602 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002603 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002604 // update the outputs if stopping one with a stream that can affect notification routing
2605 handleNotificationRoutingForStream(stream);
2606 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002607
2608 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2609 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002610 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002611 }
2612
François Gaffiec005e562018-11-06 15:04:49 +01002613 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002614 selectOutputForMusicEffects();
2615 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002616
2617 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2618
Eric Laurente552edb2014-03-10 17:42:56 -07002619 return NO_ERROR;
2620 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002621 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002622 return INVALID_OPERATION;
2623 }
2624}
2625
jiabinbce0c1d2020-10-05 11:20:18 -07002626bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002627{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002628 ALOGV("%s portId %d", __FUNCTION__, portId);
2629
2630 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2631 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002632 // If an output descriptor is closed due to a device routing change,
2633 // then there are race conditions with releaseOutput from tracks
2634 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2635 // destroyed shortly thereafter.
2636 //
2637 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002638 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002639 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002640 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002641
2642 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002643
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302644 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2645 if (outputDesc->isClientActive(client)) {
2646 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2647 stopOutput(portId);
2648 }
2649
Eric Laurent8fc147b2018-07-22 19:13:55 -07002650 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2651 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002652 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002653 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002654 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002655 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002656 if (--outputDesc->mDirectOpenCount == 0) {
2657 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002658 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002659 }
2660 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302661
Andy Hung39efb7a2018-09-26 15:39:28 -07002662 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002663 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2664 // The output is pending reopened to query dynamic profiles and
2665 // there is no active clients
2666 closeOutput(outputDesc->mIoHandle);
2667 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2668 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2669 if (newOutputDesc == nullptr) {
2670 ALOGE("%s failed to open output", __func__);
2671 }
2672 return true;
2673 }
2674 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002675}
2676
Eric Laurentcaf7f482014-11-25 17:50:47 -08002677status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2678 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002679 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002680 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002681 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002682 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002683 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002684 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002685 input_type_t *inputType,
2686 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002687{
François Gaffiec005e562018-11-06 15:04:49 +01002688 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002689 "flags %#x attributes=%s requested device ID %d",
2690 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2691 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002692
Eric Laurentad2e7b92017-09-14 20:06:42 -07002693 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002694 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002695 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002696 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002697 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002698 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002699 sp<RecordClientDescriptor> clientDesc;
2700 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002701 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002702 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002703
2704 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2705 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2706 return INVALID_OPERATION;
2707 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002708
Francois Gaffie716e1432019-01-14 16:58:59 +01002709 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2710 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002711 }
2712
Paul McLean466dc8e2015-04-17 13:15:36 -06002713 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002714 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002715 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002716
Eric Laurentad2e7b92017-09-14 20:06:42 -07002717 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2718 // possible
2719 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2720 *input != AUDIO_IO_HANDLE_NONE) {
2721 ssize_t index = mInputs.indexOfKey(*input);
2722 if (index < 0) {
2723 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2724 status = BAD_VALUE;
2725 goto error;
2726 }
2727 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002728 RecordClientVector clients = inputDesc->getClientsForSession(session);
2729 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002730 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2731 status = BAD_VALUE;
2732 goto error;
2733 }
2734 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2735 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002736 // corresponds to a new client and is only permitted from the same UID.
2737 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002738 if (clients.size() > 1) {
2739 for (const auto& client : clients) {
2740 // The client map is ordered by key values (portId) and portIds are allocated
2741 // incrementaly. So the first client in this list is the one opened by audio flinger
2742 // when the mmap stream is created and should be ignored as it does not correspond
2743 // to an actual client
2744 if (client == *clients.cbegin()) {
2745 continue;
2746 }
2747 if (uid != client->uid() && !client->isSilenced()) {
2748 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2749 uid, client->portId(), client->uid());
2750 status = INVALID_OPERATION;
2751 goto error;
2752 }
Eric Laurent331679c2018-04-16 17:03:16 -07002753 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002754 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002755 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002756 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002757
Eric Laurentfecbceb2021-02-09 14:46:43 +01002758 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002759 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002760 }
2761
2762 *input = AUDIO_IO_HANDLE_NONE;
2763 *inputType = API_INPUT_INVALID;
2764
Francois Gaffie716e1432019-01-14 16:58:59 +01002765 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002766 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002767 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002768 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002769 ALOGW("%s could not find input mix for attr %s",
2770 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002771 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002772 }
jiabinc1de2df2019-05-07 14:26:40 -07002773 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2774 String8(attr->tags + strlen("addr=")),
2775 AUDIO_FORMAT_DEFAULT);
2776 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002777 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002778 __func__, attributes.source, attributes.tags);
2779 status = BAD_VALUE;
2780 goto error;
2781 }
2782
Kevin Rocard25f9b052019-02-27 15:08:54 -08002783 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2784 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2785 } else {
2786 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2787 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002788 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002789 if (explicitRoutingDevice != nullptr) {
2790 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002791 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002792 // Prevent from storing invalid requested device id in clients
2793 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002794 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002795 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2796 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002797 }
François Gaffie11d30102018-11-02 16:09:09 +01002798 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002799 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002800 status = BAD_VALUE;
2801 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002802 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002803 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2804 *inputType = API_INPUT_MIX_CAPTURE;
2805 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002806 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2807 // there is an external policy, but this input is attached to a mix of recorders,
2808 // meaning it receives audio injected into the framework, so the recorder doesn't
2809 // know about it and is therefore considered "legacy"
2810 *inputType = API_INPUT_LEGACY;
2811 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002812 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002813 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002814 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002815 } else {
2816 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002817 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002818
Eric Laurent599c7582015-12-07 18:05:55 -08002819 }
2820
François Gaffiec005e562018-11-06 15:04:49 +01002821 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002822 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002823 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002824 AudioProfileVector profiles;
2825 status_t ret = getProfilesForDevices(
2826 DeviceVector(device), profiles, flags, true /*isInput*/);
2827 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002828 const auto channels = profiles[0]->getChannels();
2829 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2830 config->channel_mask = *channels.begin();
2831 }
2832 const auto sampleRates = profiles[0]->getSampleRates();
2833 if (!sampleRates.empty() &&
2834 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2835 config->sample_rate = *sampleRates.begin();
2836 }
jiabinf1c73972022-04-14 16:28:52 -07002837 config->format = profiles[0]->getFormat();
2838 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002839 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002840 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002841
Eric Laurent8f42ea12018-08-08 09:08:25 -07002842exit:
2843
François Gaffiec005e562018-11-06 15:04:49 +01002844 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2845 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002846
Francois Gaffie716e1432019-01-14 16:58:59 +01002847 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002848 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002849 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002850
Mikhail Naganov2996f672019-04-18 12:29:59 -07002851 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002852 requestedDeviceId, attributes.source, flags,
2853 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002854 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002855 // Move (if found) effect for the client session to its input
2856 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002857 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002858
2859 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2860 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002861
Eric Laurent599c7582015-12-07 18:05:55 -08002862 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002863
2864error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002865 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002866}
2867
2868
François Gaffie11d30102018-11-02 16:09:09 +01002869audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002870 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002871 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002872 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002873 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002874 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002875{
2876 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002877 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002878 bool isSoundTrigger = false;
2879
François Gaffiec005e562018-11-06 15:04:49 +01002880 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002881 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2882 if (index >= 0) {
2883 input = mSoundTriggerSessions.valueFor(session);
2884 isSoundTrigger = true;
2885 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2886 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2887 } else {
2888 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002889 }
François Gaffiec005e562018-11-06 15:04:49 +01002890 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002891 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002892 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002893 }
2894
Carter Hsua3abb402021-10-26 11:11:20 +08002895 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2896 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2897 }
2898
Eric Laurentfe231122017-11-17 17:48:06 -08002899 // sampling rate and flags may be updated by getInputProfile
2900 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2901 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002902 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002903 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002904 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002905 // find a compatible input profile (not necessarily identical in parameters)
2906 sp<IOProfile> profile = getInputProfile(
2907 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2908 if (profile == nullptr) {
2909 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002910 }
jiabin2fd710d2022-05-02 23:20:22 +00002911
Glenn Kasten05ddca52016-02-11 08:17:12 -08002912 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002913 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002914 if (samplingRate == 0) {
2915 samplingRate = profileSamplingRate;
2916 }
Eric Laurente552edb2014-03-10 17:42:56 -07002917
Eric Laurent322b4d22015-04-03 15:57:54 -07002918 if (profile->getModuleHandle() == 0) {
2919 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002920 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002921 }
2922
Eric Laurentec376dc2021-04-08 20:41:22 +02002923 // Reuse an already opened input if a client with the same session ID already exists
2924 // on that input
2925 for (size_t i = 0; i < mInputs.size(); i++) {
2926 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2927 if (desc->mProfile != profile) {
2928 continue;
2929 }
2930 RecordClientVector clients = desc->clientsList();
2931 for (const auto &client : clients) {
2932 if (session == client->session()) {
2933 return desc->mIoHandle;
2934 }
2935 }
2936 }
2937
Eric Laurent3974e3b2017-12-07 17:58:43 -08002938 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002939 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002940 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002941 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002942 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002943 continue;
2944 }
2945 // if sound trigger, reuse input if used by other sound trigger on same session
2946 // else
2947 // reuse input if active client app is not in IDLE state
2948 //
2949 RecordClientVector clients = desc->clientsList();
2950 bool doClose = false;
2951 for (const auto& client : clients) {
2952 if (isSoundTrigger != client->isSoundTrigger()) {
2953 continue;
2954 }
2955 if (client->isSoundTrigger()) {
2956 if (session == client->session()) {
2957 return desc->mIoHandle;
2958 }
2959 continue;
2960 }
2961 if (client->active() && client->appState() != APP_STATE_IDLE) {
2962 return desc->mIoHandle;
2963 }
2964 doClose = true;
2965 }
2966 if (doClose) {
2967 closeInput(desc->mIoHandle);
2968 } else {
2969 i++;
2970 }
2971 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002972 }
2973
Eric Laurentfe231122017-11-17 17:48:06 -08002974 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002975
Eric Laurentfe231122017-11-17 17:48:06 -08002976 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2977 lConfig.sample_rate = profileSamplingRate;
2978 lConfig.channel_mask = profileChannelMask;
2979 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002980
François Gaffie11d30102018-11-02 16:09:09 +01002981 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002982
2983 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002984 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002985 (profileSamplingRate != lConfig.sample_rate) ||
2986 !audio_formats_match(profileFormat, lConfig.format) ||
2987 (profileChannelMask != lConfig.channel_mask)) {
2988 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002989 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002990 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002991 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002992 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002993 }
Eric Laurent599c7582015-12-07 18:05:55 -08002994 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002995 }
2996
Eric Laurentc722f302014-12-10 11:21:49 -08002997 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002998
Eric Laurent599c7582015-12-07 18:05:55 -08002999 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07003000 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003001
Eric Laurent599c7582015-12-07 18:05:55 -08003002 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003003}
3004
Eric Laurent4eb58f12018-12-07 16:41:02 -08003005status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003006{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003007 ALOGV("%s portId %d", __FUNCTION__, portId);
3008
3009 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3010 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003011 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003012 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003013 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003014 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003015 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003016 if (client->active()) {
3017 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3018 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003019 }
3020
Eric Laurent8f42ea12018-08-08 09:08:25 -07003021 audio_session_t session = client->session();
3022
Eric Laurent4eb58f12018-12-07 16:41:02 -08003023 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003024
Eric Laurent4eb58f12018-12-07 16:41:02 -08003025 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003026
Eric Laurent4eb58f12018-12-07 16:41:02 -08003027 status_t status = inputDesc->start();
3028 if (status != NO_ERROR) {
3029 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003030 }
Eric Laurente552edb2014-03-10 17:42:56 -07003031
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003032 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003033 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003034 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003035
Eric Laurent8f42ea12018-08-08 09:08:25 -07003036 // indicate active capture to sound trigger service if starting capture from a mic on
3037 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003038 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003039 if (device != nullptr) {
3040 status = setInputDevice(input, device, true /* force */);
3041 } else {
3042 ALOGW("%s no new input device can be found for descriptor %d",
3043 __FUNCTION__, inputDesc->getId());
3044 status = BAD_VALUE;
3045 }
Eric Laurente552edb2014-03-10 17:42:56 -07003046
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003047 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003048 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003049 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003050 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003051 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3052 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003053 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003054 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003055
François Gaffie11d30102018-11-02 16:09:09 +01003056 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3057 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003058 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003059 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003060 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003061
Eric Laurent8f42ea12018-08-08 09:08:25 -07003062 // automatically enable the remote submix output when input is started if not
3063 // used by a policy mix of type MIX_TYPE_RECORDERS
3064 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003065 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003066 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003067 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003068 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003069 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3070 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003071 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003072 if (address != "") {
3073 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3074 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003075 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003076 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003077 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003078 } else if (status != NO_ERROR) {
3079 // Restore client activity state.
3080 inputDesc->setClientActive(client, false);
3081 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003082 }
3083
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003084 ALOGV("%s input %d source = %d status = %d exit",
3085 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003086
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003087 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003088}
3089
Eric Laurent8fc147b2018-07-22 19:13:55 -07003090status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003091{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003092 ALOGV("%s portId %d", __FUNCTION__, portId);
3093
3094 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3095 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003096 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003097 return BAD_VALUE;
3098 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003099 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003100 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003101 if (!client->active()) {
3102 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003103 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003104 }
Carter Hsue6139d52021-07-08 10:30:20 +08003105 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003106 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003107
Eric Laurent8f42ea12018-08-08 09:08:25 -07003108 inputDesc->stop();
3109 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003110 auto current_source = inputDesc->source();
3111 setInputDevice(input, getNewInputDevice(inputDesc),
3112 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003113 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003114 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003115 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003116 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003117 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3118 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003119 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003120 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003121
3122 // automatically disable the remote submix output when input is stopped if not
3123 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003124 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003125 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003126 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003127 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003128 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3129 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003130 }
3131 if (address != "") {
3132 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3133 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003134 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003135 }
3136 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003137 resetInputDevice(input);
3138
3139 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3140 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003141 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3142 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003143 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003144 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003145 }
3146 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003147 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003148 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003149}
3150
Eric Laurent8fc147b2018-07-22 19:13:55 -07003151void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003152{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003153 ALOGV("%s portId %d", __FUNCTION__, portId);
3154
3155 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3156 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003157 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003158 return;
3159 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003160 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003161 audio_io_handle_t input = inputDesc->mIoHandle;
3162
Eric Laurent8f42ea12018-08-08 09:08:25 -07003163 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003164
Andy Hung39efb7a2018-09-26 15:39:28 -07003165 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003166 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003167 if (inputDesc->getClientCount() > 0) {
3168 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003169 return;
3170 }
3171
Eric Laurent05b90f82014-08-27 15:32:29 -07003172 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003173 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003174 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003175}
3176
Eric Laurent8f42ea12018-08-08 09:08:25 -07003177void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003178{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003179 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003180
3181 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003182 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003183 }
3184}
3185
Eric Laurent8f42ea12018-08-08 09:08:25 -07003186void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3187{
3188 stopInput(portId);
3189 releaseInput(portId);
3190}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003191
Eric Laurent0dd51852019-04-19 18:18:58 -07003192void AudioPolicyManager::checkCloseInputs() {
3193 // After connecting or disconnecting an input device, close input if:
3194 // - it has no client (was just opened to check profile) OR
3195 // - none of its supported devices are connected anymore OR
3196 // - one of its clients cannot be routed to one of its supported
3197 // devices anymore. Otherwise update device selection
3198 std::vector<audio_io_handle_t> inputsToClose;
3199 for (size_t i = 0; i < mInputs.size(); i++) {
3200 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3201 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003202 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003203 inputsToClose.push_back(mInputs.keyAt(i));
3204 } else {
3205 bool close = false;
3206 for (const auto& client : input->clientsList()) {
3207 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003208 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3209 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003210 if (!input->supportedDevices().contains(device)) {
3211 close = true;
3212 break;
3213 }
3214 }
3215 if (close) {
3216 inputsToClose.push_back(mInputs.keyAt(i));
3217 } else {
3218 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3219 }
3220 }
3221 }
3222
3223 for (const audio_io_handle_t handle : inputsToClose) {
3224 ALOGV("%s closing input %d", __func__, handle);
3225 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003226 }
Eric Laurentd4692962014-05-05 18:13:44 -07003227}
3228
François Gaffie251c7f02018-11-07 10:41:08 +01003229void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003230{
3231 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003232 if (indexMin < 0 || indexMax < 0) {
3233 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3234 return;
3235 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003236 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003237
3238 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003239 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3240 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003241 continue;
3242 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003243 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003244 }
Eric Laurente552edb2014-03-10 17:42:56 -07003245}
3246
Eric Laurente0720872014-03-11 09:30:41 -07003247status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003248 int index,
3249 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003250{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003251 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003252 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3253 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3254 return NO_ERROR;
3255 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003256 ALOGV("%s: stream %s attributes=%s", __func__,
3257 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003258 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003259}
3260
Eric Laurente0720872014-03-11 09:30:41 -07003261status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003262 int *index,
3263 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003264{
François Gaffiec005e562018-11-06 15:04:49 +01003265 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3266 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003267 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003268 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003269 deviceTypes = mEngine->getOutputDevicesForStream(
3270 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003271 }
jiabin9a3361e2019-10-01 09:38:30 -07003272 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003273}
3274
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003275status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003276 int index,
3277 audio_devices_t device)
3278{
3279 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003280 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3281 if (group == VOLUME_GROUP_NONE) {
3282 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003283 return BAD_VALUE;
3284 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003285 ALOGV("%s: group %d matching with %s index %d",
3286 __FUNCTION__, group, toString(attributes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003287 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003288 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003289 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003290 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3291 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3292 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3293 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003294 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3295
3296 status = setVolumeCurveIndex(index, device, curves);
3297 if (status != NO_ERROR) {
3298 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3299 return status;
3300 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003301
jiabin9a3361e2019-10-01 09:38:30 -07003302 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003303 auto curCurvAttrs = curves.getAttributes();
3304 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3305 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003306 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003307 } else if (!curves.getStreamTypes().empty()) {
3308 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003309 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003310 } else {
3311 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3312 return BAD_VALUE;
3313 }
jiabin9a3361e2019-10-01 09:38:30 -07003314 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3315 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003316
François Gaffiecfe17322018-11-07 13:41:29 +01003317 // update volume on all outputs and streams matching the following:
3318 // - The requested stream (or a stream matching for volume control) is active on the output
3319 // - The device (or devices) selected by the engine for this stream includes
3320 // the requested device
3321 // - For non default requested device, currently selected device on the output is either the
3322 // requested device or one of the devices selected by the engine for this stream
3323 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3324 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003325 for (size_t i = 0; i < mOutputs.size(); i++) {
3326 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003327 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003328
jiabin9a3361e2019-10-01 09:38:30 -07003329 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3330 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003331 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003332
3333 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003334 continue;
3335 }
3336 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3337 curDevices.find(device) == curDevices.end()) {
3338 continue;
3339 }
3340 bool applyVolume = false;
3341 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3342 curSrcDevices.insert(device);
3343 applyVolume = (curSrcDevices.find(
3344 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3345 } else {
3346 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3347 }
3348 if (!applyVolume) {
3349 continue; // next output
3350 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003351 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3352 // If a higher priority strategy is active, and the output is routed to a device with a
3353 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003354 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003355 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003356 // If the volume source is active with higher priority source, ensure at least Sw Muted
3357 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003358 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3359 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3360 false /*preferredDevice*/);
3361 if (activeClients.empty()) {
3362 continue;
3363 }
3364 bool isPreempted = false;
3365 bool isHigherPriority = productStrategy < strategy;
3366 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003367 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003368 ALOGV("%s: Strategy=%d (\nrequester:\n"
3369 " group %d, volumeGroup=%d attributes=%s)\n"
3370 " higher priority source active:\n"
3371 " volumeGroup=%d attributes=%s) \n"
3372 " on output %zu, bailing out", __func__, productStrategy,
3373 group, group, toString(attributes).c_str(),
3374 client->volumeSource(), toString(client->attributes()).c_str(), i);
3375 applyVolume = false;
3376 isPreempted = true;
3377 break;
3378 }
3379 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003380 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003381 applyVolume = true;
3382 }
3383 }
3384 if (isPreempted || applyVolume) {
3385 break;
3386 }
3387 }
3388 if (!applyVolume) {
3389 continue; // next output
3390 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003391 }
François Gaffieed91f582020-01-31 10:35:37 +01003392 //FIXME: workaround for truncated touch sounds
3393 // delayed volume change for system stream to be removed when the problem is
3394 // handled by system UI
3395 status_t volStatus = checkAndSetVolume(
3396 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003397 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003398 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3399 if (volStatus != NO_ERROR) {
3400 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003401 }
3402 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01003403
3404 // update voice volume if the an active call route exists
3405 if (mCallRxSourceClient != nullptr && mCallRxSourceClient->isConnected()
3406 && (curSrcDevices.find(
3407 Volume::getDeviceForVolume({mCallRxSourceClient->sinkDevice()->type()}))
3408 != curSrcDevices.end())) {
3409 bool isVoiceVolSrc;
3410 bool isBtScoVolSrc;
3411 if (isVolumeConsistentForCalls(vs, {mCallRxSourceClient->sinkDevice()->type()},
3412 isVoiceVolSrc, isBtScoVolSrc, __func__)
3413 && (isVoiceVolSrc || isBtScoVolSrc)) {
3414 setVoiceVolume(index, curves, isVoiceVolSrc, 0);
3415 }
3416 }
3417
François Gaffiecfe17322018-11-07 13:41:29 +01003418 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3419 return status;
3420}
3421
François Gaffieaaac0fd2018-11-22 17:56:39 +01003422status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003423 audio_devices_t device,
3424 IVolumeCurves &volumeCurves)
3425{
3426 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3427 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003428 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3429 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003430 (index > volumeCurves.getVolumeIndexMax())) {
3431 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3432 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3433 return BAD_VALUE;
3434 }
3435 if (!audio_is_output_device(device)) {
3436 return BAD_VALUE;
3437 }
3438
3439 // Force max volume if stream cannot be muted
3440 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3441
François Gaffieaaac0fd2018-11-22 17:56:39 +01003442 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003443 volumeCurves.addCurrentVolumeIndex(device, index);
3444 return NO_ERROR;
3445}
3446
3447status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3448 int &index,
3449 audio_devices_t device)
3450{
3451 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3452 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003453 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003454 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003455 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003456 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003457 }
jiabin9a3361e2019-10-01 09:38:30 -07003458 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003459}
3460
3461status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3462 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003463 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003464{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003465 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003466 return BAD_VALUE;
3467 }
jiabin9a3361e2019-10-01 09:38:30 -07003468 index = curves.getVolumeIndex(deviceTypes);
3469 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003470 return NO_ERROR;
3471}
3472
3473status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3474 int &index)
3475{
3476 index = getVolumeCurves(attr).getVolumeIndexMin();
3477 return NO_ERROR;
3478}
3479
3480status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3481 int &index)
3482{
3483 index = getVolumeCurves(attr).getVolumeIndexMax();
3484 return NO_ERROR;
3485}
3486
Eric Laurent36829f92017-04-07 19:04:42 -07003487audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003488{
3489 // select one output among several suitable for global effects.
3490 // The priority is as follows:
3491 // 1: An offloaded output. If the effect ends up not being offloadable,
3492 // AudioFlinger will invalidate the track and the offloaded output
3493 // will be closed causing the effect to be moved to a PCM output.
3494 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003495 // 3: The primary output
3496 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003497
François Gaffiec005e562018-11-06 15:04:49 +01003498 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3499 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003500 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003501
Eric Laurent36829f92017-04-07 19:04:42 -07003502 if (outputs.size() == 0) {
3503 return AUDIO_IO_HANDLE_NONE;
3504 }
Eric Laurente552edb2014-03-10 17:42:56 -07003505
Eric Laurent36829f92017-04-07 19:04:42 -07003506 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3507 bool activeOnly = true;
3508
3509 while (output == AUDIO_IO_HANDLE_NONE) {
3510 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3511 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3512 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3513
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003514 for (audio_io_handle_t output : outputs) {
3515 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003516 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003517 continue;
3518 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003519 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3520 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003521 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003522 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003523 }
3524 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003525 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003526 }
3527 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003528 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003529 }
3530 }
3531 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3532 output = outputOffloaded;
3533 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3534 output = outputDeepBuffer;
3535 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3536 output = outputPrimary;
3537 } else {
3538 output = outputs[0];
3539 }
3540 activeOnly = false;
3541 }
3542
3543 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003544 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3545 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003546 mMusicEffectOutput = output;
3547 }
3548
3549 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003550 return output;
3551}
3552
Eric Laurent36829f92017-04-07 19:04:42 -07003553audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3554{
3555 return selectOutputForMusicEffects();
3556}
3557
Eric Laurente0720872014-03-11 09:30:41 -07003558status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003559 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003560 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003561 int session,
3562 int id)
3563{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003564 if (session != AUDIO_SESSION_DEVICE) {
3565 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003566 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003567 index = mInputs.indexOfKey(io);
3568 if (index < 0) {
3569 ALOGW("registerEffect() unknown io %d", io);
3570 return INVALID_OPERATION;
3571 }
Eric Laurente552edb2014-03-10 17:42:56 -07003572 }
3573 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003574 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3575 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3576 || strategy == PRODUCT_STRATEGY_NONE));
3577 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003578}
3579
Eric Laurentc241b0d2018-11-28 09:08:49 -08003580status_t AudioPolicyManager::unregisterEffect(int id)
3581{
3582 if (mEffects.getEffect(id) == nullptr) {
3583 return INVALID_OPERATION;
3584 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003585 if (mEffects.isEffectEnabled(id)) {
3586 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3587 setEffectEnabled(id, false);
3588 }
3589 return mEffects.unregisterEffect(id);
3590}
3591
3592status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3593{
3594 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3595 if (effect == nullptr) {
3596 return INVALID_OPERATION;
3597 }
3598
3599 status_t status = mEffects.setEffectEnabled(id, enabled);
3600 if (status == NO_ERROR) {
3601 mInputs.trackEffectEnabled(effect, enabled);
3602 }
3603 return status;
3604}
3605
Eric Laurent6c796322019-04-09 14:13:17 -07003606
3607status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3608{
3609 mEffects.moveEffects(ids, io);
3610 return NO_ERROR;
3611}
3612
Eric Laurentc75307b2015-03-17 15:29:32 -07003613bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3614{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003615 auto vs = toVolumeSource(stream, false);
3616 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003617}
3618
3619bool AudioPolicyManager::isStreamActiveRemotely(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.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003623}
3624
Eric Laurente0720872014-03-11 09:30:41 -07003625bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003626{
3627 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003628 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003629 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003630 return true;
3631 }
3632 }
3633 return false;
3634}
3635
Eric Laurent275e8e92014-11-30 15:14:47 -08003636// Register a list of custom mixes with their attributes and format.
3637// When a mix is registered, corresponding input and output profiles are
3638// added to the remote submix hw module. The profile contains only the
3639// parameters (sampling rate, format...) specified by the mix.
3640// The corresponding input remote submix device is also connected.
3641//
3642// When a remote submix device is connected, the address is checked to select the
3643// appropriate profile and the corresponding input or output stream is opened.
3644//
3645// When capture starts, getInputForAttr() will:
3646// - 1 look for a mix matching the address passed in attribtutes tags if any
3647// - 2 if none found, getDeviceForInputSource() will:
3648// - 2.1 look for a mix matching the attributes source
3649// - 2.2 if none found, default to device selection by policy rules
3650// At this time, the corresponding output remote submix device is also connected
3651// and active playback use cases can be transferred to this mix if needed when reconnecting
3652// after AudioTracks are invalidated
3653//
3654// When playback starts, getOutputForAttr() will:
3655// - 1 look for a mix matching the address passed in attribtutes tags if any
3656// - 2 if none found, look for a mix matching the attributes usage
3657// - 3 if none found, default to device and output selection by policy rules.
3658
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003659status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003660{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003661 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3662 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003663 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003664 sp<HwModule> rSubmixModule;
3665 // examine each mix's route type
3666 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003667 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003668 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3669 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3670 ALOGE("Unsupported Policy Mix %zu of %zu: "
3671 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3672 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003673 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003674 break;
3675 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003676 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3677 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003678 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003679 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3680 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003681 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003682 rSubmixModule = mHwModules.getModuleFromName(
3683 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3684 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003685 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003686 i);
3687 res = INVALID_OPERATION;
3688 break;
3689 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003690 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003691
Eric Laurent97ac8712018-07-27 18:59:02 -07003692 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003693 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003694 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003695 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003696 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3697 } else {
3698 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3699 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003700 }
François Gaffie036e1e92015-03-19 10:16:24 +01003701
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003702 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003703 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003704 res = INVALID_OPERATION;
3705 break;
3706 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003707 audio_config_t outputConfig = mix.mFormat;
3708 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003709 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3710 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003711 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3712 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003713 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003714 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3715 audio_is_linear_pcm(outputConfig.format)
3716 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003717 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003718 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3719 audio_is_linear_pcm(inputConfig.format)
3720 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003721
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003722 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003723 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003724 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003725 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003726 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003727 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003728 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003729 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3730 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003731 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003732 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003733 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003734
3735 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3736 mix.mDeviceType, mix.mDeviceAddress,
3737 String8(), AUDIO_FORMAT_DEFAULT);
3738 if (device == nullptr) {
3739 res = INVALID_OPERATION;
3740 break;
3741 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003742
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003743 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003744 // First try to find an already opened output supporting the device
3745 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003746 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003747
Eric Laurentc529cf62020-04-17 18:19:10 -07003748 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003749 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003750 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003751 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003752 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003753 } else {
3754 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003755 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003756 }
3757 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003758 // If no output found, try to find a direct output profile supporting the device
3759 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3760 sp<HwModule> module = mHwModules[i];
3761 for (size_t j = 0;
3762 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3763 j++) {
3764 sp<IOProfile> profile = module->getOutputProfiles()[j];
3765 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3766 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3767 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003768 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003769 res = INVALID_OPERATION;
3770 } else {
3771 foundOutput = true;
3772 }
3773 }
3774 }
3775 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003776 if (res != NO_ERROR) {
3777 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003778 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003779 res = INVALID_OPERATION;
3780 break;
3781 } else if (!foundOutput) {
3782 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003783 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003784 res = INVALID_OPERATION;
3785 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003786 } else {
3787 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003788 }
Eric Laurentc722f302014-12-10 11:21:49 -08003789 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003790 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003791 if (res != NO_ERROR) {
3792 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003793 } else if (checkOutputs) {
3794 checkForDeviceAndOutputChanges();
3795 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003796 }
3797 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003798}
3799
3800status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3801{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003802 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003803 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003804 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003805 sp<HwModule> rSubmixModule;
3806 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003807 for (const auto& mix : mixes) {
3808 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003809
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003810 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003811 rSubmixModule = mHwModules.getModuleFromName(
3812 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3813 if (rSubmixModule == 0) {
3814 res = INVALID_OPERATION;
3815 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003816 }
3817 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003818
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003819 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003820
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003821 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003822 res = INVALID_OPERATION;
3823 continue;
3824 }
3825
Kevin Rocard04ed0462019-05-02 17:53:24 -07003826 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003827 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003828 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3829 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003830 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003831 AUDIO_FORMAT_DEFAULT);
3832 if (res != OK) {
3833 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003834 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003835 }
3836 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003837 }
jiabin5740f082019-08-19 15:08:30 -07003838 rSubmixModule->removeOutputProfile(address.c_str());
3839 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003840
Kevin Rocard153f92d2018-12-18 18:33:28 -08003841 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003842 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003843 res = INVALID_OPERATION;
3844 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003845 } else {
3846 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003847 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003848 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003849 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003850 if (res == NO_ERROR && checkOutputs) {
3851 checkForDeviceAndOutputChanges();
3852 updateCallAndOutputRouting();
3853 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003854 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003855}
3856
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003857status_t AudioPolicyManager::updatePolicyMix(
3858 const AudioMix& mix,
3859 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3860 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3861 if (res == NO_ERROR) {
3862 checkForDeviceAndOutputChanges();
3863 updateCallAndOutputRouting();
3864 }
3865 return res;
3866}
3867
Mikhail Naganov100f0122018-11-29 11:22:16 -08003868void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3869{
3870 size_t i = 0;
3871 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3872 for (const auto& fmt : mManualSurroundFormats) {
3873 if (i++ != 0) dst->append(", ");
3874 std::string sfmt;
3875 FormatConverter::toString(fmt, sfmt);
3876 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3877 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3878 }
3879}
3880
Eric Laurentc529cf62020-04-17 18:19:10 -07003881// Returns true if all devices types match the predicate and are supported by one HW module
3882bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003883 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003884 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003885 const char *context,
3886 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003887 for (size_t i = 0; i < devices.size(); i++) {
3888 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003889 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003890 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003891 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003892 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003893 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003894 return false;
3895 }
3896 }
3897 return true;
3898}
3899
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003900void AudioPolicyManager::changeOutputDevicesMuteState(
3901 const AudioDeviceTypeAddrVector& devices) {
3902 ALOGVV("%s() num devices %zu", __func__, devices.size());
3903
3904 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3905 getSoftwareOutputsForDevices(devices);
3906
3907 for (size_t i = 0; i < outputs.size(); i++) {
3908 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3909 DeviceVector prevDevices = outputDesc->devices();
3910 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3911 }
3912}
3913
3914std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3915 const AudioDeviceTypeAddrVector& devices) const
3916{
3917 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3918 DeviceVector deviceDescriptors;
3919 for (size_t j = 0; j < devices.size(); j++) {
3920 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3921 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3922 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3923 ALOGE("%s: device type %#x address %s not supported or not an output device",
3924 __func__, devices[j].mType, devices[j].getAddress());
3925 continue;
3926 }
3927 deviceDescriptors.add(desc);
3928 }
3929 for (size_t i = 0; i < mOutputs.size(); i++) {
3930 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3931 continue;
3932 }
3933 outputs.push_back(mOutputs.valueAt(i));
3934 }
3935 return outputs;
3936}
3937
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003938status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003939 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003940 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003941 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3942 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003943 }
3944 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003945 if (res != NO_ERROR) {
3946 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3947 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003948 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003949
3950 checkForDeviceAndOutputChanges();
3951 updateCallAndOutputRouting();
3952
3953 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003954}
3955
3956status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3957 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003958 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3959 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003960 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003961 __FUNCTION__, uid);
3962 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003963 }
3964
Eric Laurentc529cf62020-04-17 18:19:10 -07003965 checkForDeviceAndOutputChanges();
3966 updateCallAndOutputRouting();
3967
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003968 return res;
3969}
3970
Eric Laurent2517af32020-11-25 15:31:27 +01003971
jiabin0a488932020-08-07 17:32:40 -07003972status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3973 device_role_t role,
3974 const AudioDeviceTypeAddrVector &devices) {
3975 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3976 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003977
Eric Laurentc529cf62020-04-17 18:19:10 -07003978 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003979 return BAD_VALUE;
3980 }
jiabin0a488932020-08-07 17:32:40 -07003981 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003982 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003983 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3984 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003985 return status;
3986 }
3987
3988 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003989
3990 bool forceVolumeReeval = false;
3991 // FIXME: workaround for truncated touch sounds
3992 // to be removed when the problem is handled by system UI
3993 uint32_t delayMs = 0;
3994 if (strategy == mCommunnicationStrategy) {
3995 forceVolumeReeval = true;
3996 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3997 updateInputRouting();
3998 }
3999 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004000
4001 return NO_ERROR;
4002}
4003
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004004void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
4005 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004006{
4007 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01004008 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01004009 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004010 // Only apply special touch sound delay once
4011 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004012 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004013 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004014 for (size_t i = 0; i < mOutputs.size(); i++) {
4015 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
4016 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004017 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4018 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004019 // As done in setDeviceConnectionState, we could also fix default device issue by
4020 // preventing the force re-routing in case of default dev that distinguishes on address.
4021 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004022 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004023 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4024 // If the device is using preferred mixer attributes, the output need to reopen
4025 // with default configuration when the new selected devices are different from
4026 // current routing devices.
4027 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4028 continue;
4029 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304030
4031 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4032 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004033 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004034 // Only apply special touch sound delay once
4035 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004036 }
4037 if (forceVolumeReeval && !newDevices.isEmpty()) {
4038 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4039 }
4040 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004041 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004042 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004043}
4044
Eric Laurent2517af32020-11-25 15:31:27 +01004045void AudioPolicyManager::updateInputRouting() {
4046 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304047 // Skip for hotword recording as the input device switch
4048 // is handled within sound trigger HAL
4049 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4050 continue;
4051 }
Eric Laurent2517af32020-11-25 15:31:27 +01004052 auto newDevice = getNewInputDevice(activeDesc);
4053 // Force new input selection if the new device can not be reached via current input
4054 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4055 setInputDevice(activeDesc->mIoHandle, newDevice);
4056 } else {
4057 closeInput(activeDesc->mIoHandle);
4058 }
4059 }
4060}
4061
Paul Wang5d7cdb52022-11-22 09:45:06 +00004062status_t
4063AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4064 device_role_t role,
4065 const AudioDeviceTypeAddrVector &devices) {
4066 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4067 dumpAudioDeviceTypeAddrVector(devices).c_str());
4068
Eric Laurent78fedbf2023-03-09 14:40:44 +01004069 if (!areAllDevicesSupported(
4070 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004071 return BAD_VALUE;
4072 }
4073 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4074 if (status != NO_ERROR) {
4075 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4076 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4077 return status;
4078 }
4079
4080 checkForDeviceAndOutputChanges();
4081
4082 bool forceVolumeReeval = false;
4083 // TODO(b/263479999): workaround for truncated touch sounds
4084 // to be removed when the problem is handled by system UI
4085 uint32_t delayMs = 0;
4086 if (strategy == mCommunnicationStrategy) {
4087 forceVolumeReeval = true;
4088 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4089 updateInputRouting();
4090 }
4091 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4092
4093 return NO_ERROR;
4094}
4095
4096status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4097 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004098{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004099 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004100
Paul Wang5d7cdb52022-11-22 09:45:06 +00004101 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004102 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004103 ALOGW_IF(status != NAME_NOT_FOUND,
4104 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004105 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004106 return status;
4107 }
4108
4109 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004110
4111 bool forceVolumeReeval = false;
4112 // FIXME: workaround for truncated touch sounds
4113 // to be removed when the problem is handled by system UI
4114 uint32_t delayMs = 0;
4115 if (strategy == mCommunnicationStrategy) {
4116 forceVolumeReeval = true;
4117 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4118 updateInputRouting();
4119 }
4120 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004121
4122 return NO_ERROR;
4123}
4124
jiabin0a488932020-08-07 17:32:40 -07004125status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4126 device_role_t role,
4127 AudioDeviceTypeAddrVector &devices) {
4128 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004129}
4130
Jiabin Huang3b98d322020-09-03 17:54:16 +00004131status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4132 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4133 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4134 dumpAudioDeviceTypeAddrVector(devices).c_str());
4135
Mikhail Naganov55773032020-10-01 15:08:13 -07004136 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004137 return BAD_VALUE;
4138 }
4139 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4140 ALOGW_IF(status != NO_ERROR,
4141 "Engine could not set preferred devices %s for audio source %d role %d",
4142 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4143
4144 return status;
4145}
4146
4147status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4148 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4149 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4150 dumpAudioDeviceTypeAddrVector(devices).c_str());
4151
Mikhail Naganov55773032020-10-01 15:08:13 -07004152 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004153 return BAD_VALUE;
4154 }
4155 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4156 ALOGW_IF(status != NO_ERROR,
4157 "Engine could not add preferred devices %s for audio source %d role %d",
4158 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4159
Eric Laurent2517af32020-11-25 15:31:27 +01004160 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004161 return status;
4162}
4163
4164status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4165 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4166{
4167 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4168 dumpAudioDeviceTypeAddrVector(devices).c_str());
4169
Eric Laurent78fedbf2023-03-09 14:40:44 +01004170 if (!areAllDevicesSupported(
4171 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004172 return BAD_VALUE;
4173 }
4174
4175 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4176 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004177 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004178 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004179 if (status == NO_ERROR) {
4180 updateInputRouting();
4181 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004182 return status;
4183}
4184
4185status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4186 device_role_t role) {
4187 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4188
4189 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004190 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004191 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004192 if (status == NO_ERROR) {
4193 updateInputRouting();
4194 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004195 return status;
4196}
4197
4198status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4199 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4200 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4201}
4202
Oscar Azucena90e77632019-11-27 17:12:28 -08004203status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004204 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004205 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004206 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4207 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004208 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004209 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4210 if (status != NO_ERROR) {
4211 ALOGE("%s() could not set device affinity for userId %d",
4212 __FUNCTION__, userId);
4213 return status;
4214 }
4215
4216 // reevaluate outputs for all devices
4217 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004218 changeOutputDevicesMuteState(devices);
4219 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4220 true /* skipDelays */);
4221 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004222
4223 return NO_ERROR;
4224}
4225
4226status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004227 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004228 AudioDeviceTypeAddrVector devices;
4229 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004230 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4231 if (status != NO_ERROR) {
4232 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4233 __FUNCTION__, userId);
4234 return status;
4235 }
4236
4237 // reevaluate outputs for all devices
4238 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004239 changeOutputDevicesMuteState(devices);
4240 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4241 true /* skipDelays */);
4242 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004243
4244 return NO_ERROR;
4245}
4246
Andy Hungc29d82b2018-10-05 12:23:17 -07004247void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004248{
Andy Hungc29d82b2018-10-05 12:23:17 -07004249 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004250 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004251 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004252 std::string stateLiteral;
4253 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004254 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004255 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4256 "communications", "media", "record", "dock", "system",
4257 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4258 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4259 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004260 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4261 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4262 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4263 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4264 dst->append(" (MANUAL: ");
4265 dumpManualSurroundFormats(dst);
4266 dst->append(")");
4267 }
4268 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004269 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004270 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4271 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004272 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004273 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004274
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004275 dst->append("\n");
4276 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4277 dst->append("\n");
4278 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004279 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004280 mOutputs.dump(dst);
4281 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004282 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004283 mAudioPatches.dump(dst);
4284 mPolicyMixes.dump(dst);
4285 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004286
Kevin Rocardb99cc752019-03-21 20:52:24 -07004287 dst->appendFormat(" AllowedCapturePolicies:\n");
4288 for (auto& policy : mAllowedCapturePolicies) {
4289 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4290 }
4291
jiabina84c3d32022-12-02 18:59:55 +00004292 dst->appendFormat(" Preferred mixer audio configuration:\n");
4293 for (const auto it : mPreferredMixerAttrInfos) {
4294 dst->appendFormat(" - device port id: %d\n", it.first);
4295 for (const auto preferredMixerInfoIt : it.second) {
4296 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4297 preferredMixerInfoIt.second->dump(dst);
4298 }
4299 }
4300
François Gaffiec005e562018-11-06 15:04:49 +01004301 dst->appendFormat("\nPolicy Engine dump:\n");
4302 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004303}
4304
4305status_t AudioPolicyManager::dump(int fd)
4306{
4307 String8 result;
4308 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004309 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004310 return NO_ERROR;
4311}
4312
Kevin Rocardb99cc752019-03-21 20:52:24 -07004313status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4314{
4315 mAllowedCapturePolicies[uid] = capturePolicy;
4316 return NO_ERROR;
4317}
4318
Eric Laurente552edb2014-03-10 17:42:56 -07004319// This function checks for the parameters which can be offloaded.
4320// This can be enhanced depending on the capability of the DSP and policy
4321// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004322audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004323{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004324 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004325 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004326 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004327 offloadInfo.format,
4328 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4329 offloadInfo.has_video);
4330
jiabin2b9d5a12021-12-10 01:06:29 +00004331 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004332 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004333 }
4334
4335 // See if there is a profile to support this.
4336 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004337 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004338 offloadInfo.sample_rate,
4339 offloadInfo.format,
4340 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004341 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4342 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004343 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4344 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4345 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004346 if (profile == nullptr) {
4347 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4348 }
4349 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4350 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4351 }
4352 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004353}
4354
Michael Chana94fbb22018-04-24 14:31:19 +10004355bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4356 const audio_attributes_t& attributes) {
4357 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004358 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004359 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4360 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004361 config.sample_rate,
4362 config.format,
4363 config.channel_mask,
4364 output_flags,
4365 true /* directOnly */);
4366 ALOGV("%s() profile %sfound with name: %s, "
4367 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4368 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004369 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004370 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004371
4372 // also try the MSD module if compatible profile not found
4373 if (profile == nullptr) {
4374 profile = getMsdProfileForOutput(outputDevices,
4375 config.sample_rate,
4376 config.format,
4377 config.channel_mask,
4378 output_flags,
4379 true /* directOnly */);
4380 ALOGV("%s() MSD profile %sfound with name: %s, "
4381 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4382 __FUNCTION__, profile != 0 ? "" : "NOT ",
4383 (profile != 0 ? profile->getTagName().c_str() : "null"),
4384 config.sample_rate, config.format, config.channel_mask, output_flags);
4385 }
4386 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004387}
4388
jiabin2b9d5a12021-12-10 01:06:29 +00004389bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4390 bool durationIgnored) {
4391 if (mMasterMono) {
4392 return false; // no offloading if mono is set.
4393 }
4394
4395 // Check if offload has been disabled
4396 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4397 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4398 return false;
4399 }
4400
4401 // Check if stream type is music, then only allow offload as of now.
4402 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4403 {
4404 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4405 return false;
4406 }
4407
4408 //TODO: enable audio offloading with video when ready
4409 const bool allowOffloadWithVideo =
4410 property_get_bool("audio.offload.video", false /* default_value */);
4411 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4412 ALOGV("%s: has_video == true, returning false", __func__);
4413 return false;
4414 }
4415
4416 //If duration is less than minimum value defined in property, return false
4417 const int min_duration_secs = property_get_int32(
4418 "audio.offload.min.duration.secs", -1 /* default_value */);
4419 if (!durationIgnored) {
4420 if (min_duration_secs >= 0) {
4421 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4422 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4423 __func__, min_duration_secs);
4424 return false;
4425 }
4426 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4427 ALOGV("%s: Offload denied by duration < default min(=%u)",
4428 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4429 return false;
4430 }
4431 }
4432
4433 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4434 // creating an offloaded track and tearing it down immediately after start when audioflinger
4435 // detects there is an active non offloadable effect.
4436 // FIXME: We should check the audio session here but we do not have it in this context.
4437 // This may prevent offloading in rare situations where effects are left active by apps
4438 // in the background.
4439 if (mEffects.isNonOffloadableEffectEnabled()) {
4440 return false;
4441 }
4442
4443 return true;
4444}
4445
4446audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4447 const audio_config_t *config) {
4448 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4449 offloadInfo.format = config->format;
4450 offloadInfo.sample_rate = config->sample_rate;
4451 offloadInfo.channel_mask = config->channel_mask;
4452 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4453 offloadInfo.has_video = false;
4454 offloadInfo.is_streaming = false;
4455 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4456
4457 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4458 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4459 audio_flags_to_audio_output_flags(attr->flags, &flags);
4460 // only retain flags that will drive compressed offload or passthrough
4461 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4462 if (offloadPossible) {
4463 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4464 }
4465 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4466
Dorin Drimusfae3c642022-03-17 18:36:30 +01004467 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004468 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004469 DeviceVector outputDevices = engineOutputDevices;
4470 // the MSD module checks for different conditions and output devices
4471 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4472 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4473 continue;
4474 }
4475 outputDevices = getMsdAudioOutDevices();
4476 }
jiabin2b9d5a12021-12-10 01:06:29 +00004477 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004478 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004479 config->sample_rate, nullptr /*updatedSamplingRate*/,
4480 config->format, nullptr /*updatedFormat*/,
4481 config->channel_mask, nullptr /*updatedChannelMask*/,
4482 flags)) {
4483 continue;
4484 }
4485 // reject profiles not corresponding to a device currently available
4486 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4487 continue;
4488 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004489 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4490 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004491 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004492 != AUDIO_DIRECT_NOT_SUPPORTED) {
4493 // Already reports offload gapless supported. No need to report offload support.
4494 continue;
4495 }
4496 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4497 != AUDIO_OUTPUT_FLAG_NONE) {
4498 // If offload gapless is reported, no need to report offload support.
4499 directMode = (audio_direct_mode_t) ((directMode &
4500 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4501 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4502 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004503 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004504 }
4505 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004506 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004507 }
4508 }
4509 }
4510 return directMode;
4511}
4512
Dorin Drimusf2196d82022-01-03 12:11:18 +01004513status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4514 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004515 if (mEffects.isNonOffloadableEffectEnabled()) {
4516 return OK;
4517 }
jiabinf1c73972022-04-14 16:28:52 -07004518 DeviceVector devices;
4519 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004520 if (status != OK) {
4521 return status;
4522 }
4523 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4524 if (devices.empty()) {
4525 return OK; // no output devices for the attributes
4526 }
jiabinf1c73972022-04-14 16:28:52 -07004527 return getProfilesForDevices(devices, audioProfilesVector,
4528 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004529}
4530
jiabina84c3d32022-12-02 18:59:55 +00004531status_t AudioPolicyManager::getSupportedMixerAttributes(
4532 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4533 ALOGV("%s, portId=%d", __func__, portId);
4534 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4535 if (deviceDescriptor == nullptr) {
4536 ALOGE("%s the requested device is currently unavailable", __func__);
4537 return BAD_VALUE;
4538 }
jiabin96daffc2023-05-11 17:51:55 +00004539 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4540 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4541 deviceDescriptor->type());
4542 return BAD_VALUE;
4543 }
jiabina84c3d32022-12-02 18:59:55 +00004544 for (const auto& hwModule : mHwModules) {
4545 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4546 if (curProfile->supportsDevice(deviceDescriptor)) {
4547 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4548 }
4549 }
4550 }
4551 return NO_ERROR;
4552}
4553
4554status_t AudioPolicyManager::setPreferredMixerAttributes(
4555 const audio_attributes_t *attr,
4556 audio_port_handle_t portId,
4557 uid_t uid,
4558 const audio_mixer_attributes_t *mixerAttributes) {
4559 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4560 "mixerBehavior=%d}, uid=%d, portId=%u",
4561 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4562 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4563 mixerAttributes->mixer_behavior, uid, portId);
4564 if (attr->usage != AUDIO_USAGE_MEDIA) {
4565 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4566 return BAD_VALUE;
4567 }
4568 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4569 if (deviceDescriptor == nullptr) {
4570 ALOGE("%s the requested device is currently unavailable", __func__);
4571 return BAD_VALUE;
4572 }
4573 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4574 ALOGE("%s(%d), type=%d, is not a usb output device",
4575 __func__, portId, deviceDescriptor->type());
4576 return BAD_VALUE;
4577 }
4578
4579 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4580 audio_flags_to_audio_output_flags(attr->flags, &flags);
4581 flags = (audio_output_flags_t) (flags |
4582 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4583 sp<IOProfile> profile = nullptr;
4584 DeviceVector devices(deviceDescriptor);
4585 for (const auto& hwModule : mHwModules) {
4586 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4587 if (curProfile->hasDynamicAudioProfile()
4588 && curProfile->isCompatibleProfile(devices,
4589 mixerAttributes->config.sample_rate,
4590 nullptr /*updatedSamplingRate*/,
4591 mixerAttributes->config.format,
4592 nullptr /*updatedFormat*/,
4593 mixerAttributes->config.channel_mask,
4594 nullptr /*updatedChannelMask*/,
4595 flags,
4596 false /*exactMatchRequiredForInputFlags*/)) {
4597 profile = curProfile;
4598 break;
4599 }
4600 }
4601 }
4602 if (profile == nullptr) {
4603 ALOGE("%s, there is no compatible profile found", __func__);
4604 return BAD_VALUE;
4605 }
4606
4607 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4608 sp<PreferredMixerAttributesInfo>::make(
4609 uid, portId, profile, flags, *mixerAttributes);
4610 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4611 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4612
4613 // If 1) there is any client from the preferred mixer configuration owner that is currently
4614 // active and matches the strategy and 2) current output is on the preferred device and the
4615 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4616 // configuration.
4617 std::vector<audio_io_handle_t> outputsToReopen;
4618 for (size_t i = 0; i < mOutputs.size(); i++) {
4619 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004620 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4621 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4622 output->mUsePreferredMixerAttributes = true;
4623 } else {
4624 for (const auto &client: output->getActiveClients()) {
4625 if (client->uid() == uid && client->strategy() == strategy) {
4626 client->setIsInvalid();
4627 outputsToReopen.push_back(output->mIoHandle);
4628 }
jiabina84c3d32022-12-02 18:59:55 +00004629 }
4630 }
4631 }
4632 }
4633 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4634 config.sample_rate = mixerAttributes->config.sample_rate;
4635 config.channel_mask = mixerAttributes->config.channel_mask;
4636 config.format = mixerAttributes->config.format;
4637 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004638 sp<SwAudioOutputDescriptor> desc =
4639 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4640 if (desc == nullptr) {
4641 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4642 continue;
4643 }
4644 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004645 }
4646
4647 return NO_ERROR;
4648}
4649
4650sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004651 audio_port_handle_t devicePortId,
4652 product_strategy_t strategy,
4653 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004654 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4655 if (it == mPreferredMixerAttrInfos.end()) {
4656 return nullptr;
4657 }
jiabind9a58d32023-06-01 17:57:30 +00004658 if (activeBitPerfectPreferred) {
4659 for (auto [strategy, info] : it->second) {
4660 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4661 && info->getActiveClientCount() != 0) {
4662 return info;
4663 }
4664 }
jiabina84c3d32022-12-02 18:59:55 +00004665 }
jiabind9a58d32023-06-01 17:57:30 +00004666 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4667 return strategyMatchedMixerAttrInfoIt == it->second.end()
4668 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004669}
4670
4671status_t AudioPolicyManager::getPreferredMixerAttributes(
4672 const audio_attributes_t *attr,
4673 audio_port_handle_t portId,
4674 audio_mixer_attributes_t* mixerAttributes) {
4675 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4676 portId, mEngine->getProductStrategyForAttributes(*attr));
4677 if (info == nullptr) {
4678 return NAME_NOT_FOUND;
4679 }
4680 *mixerAttributes = info->getMixerAttributes();
4681 return NO_ERROR;
4682}
4683
4684status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4685 audio_port_handle_t portId,
4686 uid_t uid) {
4687 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4688 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4689 if (preferredMixerAttrInfo == nullptr) {
4690 return NAME_NOT_FOUND;
4691 }
4692 if (preferredMixerAttrInfo->getUid() != uid) {
4693 ALOGE("%s, requested uid=%d, owned uid=%d",
4694 __func__, uid, preferredMixerAttrInfo->getUid());
4695 return PERMISSION_DENIED;
4696 }
4697 mPreferredMixerAttrInfos[portId].erase(strategy);
4698 if (mPreferredMixerAttrInfos[portId].empty()) {
4699 mPreferredMixerAttrInfos.erase(portId);
4700 }
4701
4702 // Reconfig existing output
4703 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4704 for (size_t i = 0; i < mOutputs.size(); i++) {
4705 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4706 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4707 }
4708 }
4709 for (const auto output : potentialOutputsToReopen) {
4710 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4711 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4712 preferredMixerAttrInfo->getFlags())) {
4713 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4714 }
4715 }
4716 return NO_ERROR;
4717}
4718
Eric Laurent6a94d692014-05-20 11:18:06 -07004719status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4720 audio_port_type_t type,
4721 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004722 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004723 unsigned int *generation)
4724{
jiabin19cdba52020-11-24 11:28:58 -08004725 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4726 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004727 return BAD_VALUE;
4728 }
4729 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004730 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004731 *num_ports = 0;
4732 }
4733
4734 size_t portsWritten = 0;
4735 size_t portsMax = *num_ports;
4736 *num_ports = 0;
4737 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004738 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4739 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004740 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004741 for (const auto& dev : mAvailableOutputDevices) {
4742 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004743 continue;
4744 }
4745 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004746 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004747 }
4748 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004749 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004750 }
4751 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004752 for (const auto& dev : mAvailableInputDevices) {
4753 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004754 continue;
4755 }
4756 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004757 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004758 }
4759 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004760 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004761 }
4762 }
4763 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4764 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4765 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4766 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4767 }
4768 *num_ports += mInputs.size();
4769 }
4770 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004771 size_t numOutputs = 0;
4772 for (size_t i = 0; i < mOutputs.size(); i++) {
4773 if (!mOutputs[i]->isDuplicated()) {
4774 numOutputs++;
4775 if (portsWritten < portsMax) {
4776 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4777 }
4778 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004779 }
Eric Laurent84c70242014-06-23 08:46:27 -07004780 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004781 }
4782 }
jiabina84c3d32022-12-02 18:59:55 +00004783
Eric Laurent6a94d692014-05-20 11:18:06 -07004784 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004785 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004786 return NO_ERROR;
4787}
4788
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004789status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4790 std::vector<media::AudioPortFw>* _aidl_return) {
4791 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4792 audio_port_v7 port;
4793 dev->toAudioPort(&port);
4794 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4795 _aidl_return->push_back(std::move(aidlPort));
4796 return OK;
4797 };
4798
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004799 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004800 for (const auto& dev : module->getDeclaredDevices()) {
4801 if (role == media::AudioPortRole::NONE ||
4802 ((role == media::AudioPortRole::SOURCE)
4803 == audio_is_input_device(dev->type()))) {
4804 RETURN_STATUS_IF_ERROR(pushPort(dev));
4805 }
4806 }
4807 }
4808 return OK;
4809}
4810
jiabin19cdba52020-11-24 11:28:58 -08004811status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004812{
Eric Laurent99fcae42018-05-17 16:59:18 -07004813 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4814 return BAD_VALUE;
4815 }
4816 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4817 if (dev != 0) {
4818 dev->toAudioPort(port);
4819 return NO_ERROR;
4820 }
4821 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4822 if (dev != 0) {
4823 dev->toAudioPort(port);
4824 return NO_ERROR;
4825 }
4826 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4827 if (out != 0) {
4828 out->toAudioPort(port);
4829 return NO_ERROR;
4830 }
4831 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4832 if (in != 0) {
4833 in->toAudioPort(port);
4834 return NO_ERROR;
4835 }
4836 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004837}
4838
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004839status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4840 audio_patch_handle_t *handle,
4841 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004842{
François Gaffieafd4cea2019-11-18 15:50:22 +01004843 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004844 if (handle == NULL || patch == NULL) {
4845 return BAD_VALUE;
4846 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004847 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004848 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004849 return BAD_VALUE;
4850 }
4851 // only one source per audio patch supported for now
4852 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004853 return INVALID_OPERATION;
4854 }
Eric Laurent874c42872014-08-08 15:13:39 -07004855 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004856 return INVALID_OPERATION;
4857 }
Eric Laurent874c42872014-08-08 15:13:39 -07004858 for (size_t i = 0; i < patch->num_sinks; i++) {
4859 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4860 return INVALID_OPERATION;
4861 }
4862 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004863
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004864 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4865 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4866 if (srcDevice == nullptr || sinkDevice == nullptr) {
4867 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4868 return BAD_VALUE;
4869 }
4870 ALOGV("%s between source %s and sink %s", __func__,
4871 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4872 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4873 // Default attributes, default volume priority, not to infer with non raw audio patches.
4874 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4875 const struct audio_port_config *source = &patch->sources[0];
4876 sp<SourceClientDescriptor> sourceDesc =
4877 new InternalSourceClientDescriptor(
4878 portId, uid, attributes, *source, srcDevice, sinkDevice,
4879 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4880
4881 status_t status =
4882 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4883
4884 if (status != NO_ERROR) {
4885 return INVALID_OPERATION;
4886 }
4887 mAudioSources.add(portId, sourceDesc);
4888 return NO_ERROR;
4889}
4890
4891status_t AudioPolicyManager::connectAudioSourceToSink(
4892 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4893 const struct audio_patch *patch,
4894 audio_patch_handle_t &handle,
4895 uid_t uid, uint32_t delayMs)
4896{
4897 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4898 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4899 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4900 return INVALID_OPERATION;
4901 }
4902 sourceDesc->connect(handle, sinkDevice);
4903 if (isMsdPatch(handle)) {
4904 return NO_ERROR;
4905 }
4906 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4907 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4908 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4909 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4910 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4911 goto FailurePatchAdded;
4912 }
4913 status = swOutput->start();
4914 if (status != NO_ERROR) {
4915 goto FailureSourceAdded;
4916 }
4917 swOutput->addClient(sourceDesc);
4918 status = startSource(swOutput, sourceDesc, &delayMs);
4919 if (status != NO_ERROR) {
4920 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4921 goto FailureSourceActive;
4922 }
4923 if (delayMs != 0) {
4924 usleep(delayMs * 1000);
4925 }
4926 return NO_ERROR;
4927
4928FailureSourceActive:
4929 swOutput->stop();
4930 releaseOutput(sourceDesc->portId());
4931FailureSourceAdded:
4932 sourceDesc->setSwOutput(nullptr);
4933FailurePatchAdded:
4934 releaseAudioPatchInternal(handle);
4935 return INVALID_OPERATION;
4936}
4937
4938status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4939 audio_patch_handle_t *handle,
4940 uid_t uid, uint32_t delayMs,
4941 const sp<SourceClientDescriptor>& sourceDesc)
4942{
4943 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004944 sp<AudioPatch> patchDesc;
4945 ssize_t index = mAudioPatches.indexOfKey(*handle);
4946
François Gaffieafd4cea2019-11-18 15:50:22 +01004947 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4948 patch->sources[0].role,
4949 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004950#if LOG_NDEBUG == 0
4951 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004952 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4953 patch->sinks[i].role,
4954 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004955 }
4956#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004957
4958 if (index >= 0) {
4959 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004960 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4961 __func__, mUidCached, patchDesc->getUid(), uid);
4962 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004963 return INVALID_OPERATION;
4964 }
4965 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004966 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004967 }
4968
4969 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004970 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004971 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004972 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004973 return BAD_VALUE;
4974 }
Eric Laurent84c70242014-06-23 08:46:27 -07004975 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4976 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004977 if (patchDesc != 0) {
4978 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004979 ALOGV("%s source id differs for patch current id %d new id %d",
4980 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004981 return BAD_VALUE;
4982 }
4983 }
Eric Laurent874c42872014-08-08 15:13:39 -07004984 DeviceVector devices;
4985 for (size_t i = 0; i < patch->num_sinks; i++) {
4986 // Only support mix to devices connection
4987 // TODO add support for mix to mix connection
4988 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004989 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004990 return INVALID_OPERATION;
4991 }
4992 sp<DeviceDescriptor> devDesc =
4993 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4994 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004995 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004996 return BAD_VALUE;
4997 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004998
François Gaffie11d30102018-11-02 16:09:09 +01004999 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07005000 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01005001 NULL, // updatedSamplingRate
5002 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005003 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01005004 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005005 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01005006 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005007 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07005008 return INVALID_OPERATION;
5009 }
5010 devices.add(devDesc);
5011 }
5012 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005013 return INVALID_OPERATION;
5014 }
Eric Laurent874c42872014-08-08 15:13:39 -07005015
Eric Laurent6a94d692014-05-20 11:18:06 -07005016 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005017 ALOGV("%s setting device %s on output %d",
5018 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305019 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005020 index = mAudioPatches.indexOfKey(*handle);
5021 if (index >= 0) {
5022 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005023 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005024 }
5025 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005026 patchDesc->setUid(uid);
5027 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005028 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005029 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005030 return INVALID_OPERATION;
5031 }
5032 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5033 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5034 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005035 // only one sink supported when connecting an input device to a mix
5036 if (patch->num_sinks > 1) {
5037 return INVALID_OPERATION;
5038 }
François Gaffie53615e22015-03-19 09:24:12 +01005039 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005040 if (inputDesc == NULL) {
5041 return BAD_VALUE;
5042 }
5043 if (patchDesc != 0) {
5044 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5045 return BAD_VALUE;
5046 }
5047 }
François Gaffie11d30102018-11-02 16:09:09 +01005048 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005049 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005050 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005051 return BAD_VALUE;
5052 }
5053
François Gaffie11d30102018-11-02 16:09:09 +01005054 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005055 patch->sinks[0].sample_rate,
5056 NULL, /*updatedSampleRate*/
5057 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005058 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005059 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005060 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005061 // FIXME for the parameter type,
5062 // and the NONE
5063 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005064 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005065 return INVALID_OPERATION;
5066 }
5067 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005068 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005069 device->toString().c_str(), inputDesc->mIoHandle);
5070 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005071 index = mAudioPatches.indexOfKey(*handle);
5072 if (index >= 0) {
5073 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005074 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005075 }
5076 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005077 patchDesc->setUid(uid);
5078 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005079 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005080 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005081 return INVALID_OPERATION;
5082 }
5083 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5084 // device to device connection
5085 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005086 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005087 return BAD_VALUE;
5088 }
5089 }
François Gaffie11d30102018-11-02 16:09:09 +01005090 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005091 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005092 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005093 return BAD_VALUE;
5094 }
Eric Laurent874c42872014-08-08 15:13:39 -07005095
Eric Laurent6a94d692014-05-20 11:18:06 -07005096 //update source and sink with our own data as the data passed in the patch may
5097 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005098 PatchBuilder patchBuilder;
5099 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005100
5101 // if first sink is to MSD, establish single MSD patch
5102 if (getMsdAudioOutDevices().contains(
5103 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5104 ALOGV("%s patching to MSD", __FUNCTION__);
5105 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5106 goto installPatch;
5107 }
5108
François Gaffieafd4cea2019-11-18 15:50:22 +01005109 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5110 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005111
Eric Laurent874c42872014-08-08 15:13:39 -07005112 for (size_t i = 0; i < patch->num_sinks; i++) {
5113 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005114 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005115 return INVALID_OPERATION;
5116 }
François Gaffie11d30102018-11-02 16:09:09 +01005117 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005118 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005119 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005120 return BAD_VALUE;
5121 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005122 audio_port_config sinkPortConfig = {};
5123 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5124 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005125
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005126 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5127 // volume management purpose (tracking activity)
5128 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5129 // in config XML to reach the sink so that is can be declared as available.
5130 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005131 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005132 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005133 // take care of dynamic routing for SwOutput selection,
5134 audio_attributes_t attributes = sourceDesc->attributes();
5135 audio_stream_type_t stream = sourceDesc->stream();
5136 audio_attributes_t resultAttr;
5137 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5138 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005139 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5140 config.channel_mask =
5141 (audio_channel_mask_get_representation(sourceMask)
5142 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5143 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005144 config.format = sourceDesc->config().format;
5145 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5146 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5147 bool isRequestedDeviceForExclusiveUse = false;
5148 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005149 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005150 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005151 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5152 &stream, sourceDesc->uid(), &config, &flags,
5153 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005154 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005155 if (output == AUDIO_IO_HANDLE_NONE) {
5156 ALOGV("%s no output for device %s",
5157 __FUNCTION__, sinkDevice->toString().c_str());
5158 return INVALID_OPERATION;
5159 }
5160 outputDesc = mOutputs.valueFor(output);
5161 if (outputDesc->isDuplicated()) {
5162 ALOGE("%s output is duplicated", __func__);
5163 return INVALID_OPERATION;
5164 }
François Gaffie7e39df22022-04-26 12:48:49 +02005165 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5166 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005167 } else {
5168 // Same for "raw patches" aka created from createAudioPatch API
5169 SortedVector<audio_io_handle_t> outputs =
5170 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5171 // if the sink device is reachable via an opened output stream, request to
5172 // go via this output stream by adding a second source to the patch
5173 // description
5174 output = selectOutput(outputs);
5175 if (output == AUDIO_IO_HANDLE_NONE) {
5176 ALOGE("%s no output available for internal patch sink", __func__);
5177 return INVALID_OPERATION;
5178 }
5179 outputDesc = mOutputs.valueFor(output);
5180 if (outputDesc->isDuplicated()) {
5181 ALOGV("%s output for device %s is duplicated",
5182 __func__, sinkDevice->toString().c_str());
5183 return INVALID_OPERATION;
5184 }
François Gaffie7e39df22022-04-26 12:48:49 +02005185 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005186 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005187 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005188 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005189 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005190 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005191 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5192 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005193 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5194 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005195 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005196 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005197 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005198 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005199 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005200 return INVALID_OPERATION;
5201 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005202 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005203 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005204 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005205 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005206 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005207 srcMixPortConfig.ext.mix.usecase.stream =
5208 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005209 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5210 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005211 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005212 }
Eric Laurent83b88082014-06-20 18:31:16 -07005213 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005214 }
5215 // TODO: check from routing capabilities in config file and other conflicting patches
5216
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005217installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005218 status_t status = installPatch(
5219 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005220 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005221 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005222 return INVALID_OPERATION;
5223 }
5224 } else {
5225 return BAD_VALUE;
5226 }
5227 } else {
5228 return BAD_VALUE;
5229 }
5230 return NO_ERROR;
5231}
5232
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005233status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005234{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005235 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005236 ssize_t index = mAudioPatches.indexOfKey(handle);
5237
5238 if (index < 0) {
5239 return BAD_VALUE;
5240 }
5241 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005242 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5243 __func__, mUidCached, patchDesc->getUid(), uid);
5244 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005245 return INVALID_OPERATION;
5246 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005247 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5248 for (size_t i = 0; i < mAudioSources.size(); i++) {
5249 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5250 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5251 portId = sourceDesc->portId();
5252 break;
5253 }
5254 }
5255 return portId != AUDIO_PORT_HANDLE_NONE ?
5256 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005257}
Eric Laurent6a94d692014-05-20 11:18:06 -07005258
François Gaffieafd4cea2019-11-18 15:50:22 +01005259status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005260 uint32_t delayMs,
5261 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005262{
5263 ALOGV("%s patch %d", __func__, handle);
5264 if (mAudioPatches.indexOfKey(handle) < 0) {
5265 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5266 return BAD_VALUE;
5267 }
5268 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005270 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005271 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005272 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005273 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005274 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 return BAD_VALUE;
5276 }
5277
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305278 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005279 getNewOutputDevices(outputDesc, true /*fromCache*/),
5280 true,
5281 0,
5282 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5284 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005285 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005286 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005287 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005288 return BAD_VALUE;
5289 }
5290 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005291 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005292 true,
5293 NULL);
5294 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005295 status_t status =
5296 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5297 ALOGV("%s patch panel returned %d patchHandle %d",
5298 __func__, status, patchDesc->getAfHandle());
5299 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005300 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005301 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005302 // SW or HW Bridge
5303 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5304 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005305 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005306 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5307 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5308 outputDesc = sourceDesc->swOutput().promote();
5309 }
5310 if (outputDesc == nullptr) {
5311 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5312 // releaseOutput has already called closeOutput in case of direct output
5313 return NO_ERROR;
5314 }
François Gaffie7e39df22022-04-26 12:48:49 +02005315 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005316 // While using a HwBridge, force reconsidering device only if not reusing an existing
5317 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005318 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005319 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5320 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5321 // Reconsider device only for cases:
5322 // 1 / Active Output
5323 // 2 / Inactive Output previously hosting HwBridge
5324 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5325 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5326 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305327 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005328 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5329 outputDesc->devices(),
5330 force,
5331 0,
5332 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005333 } else {
5334 return BAD_VALUE;
5335 }
5336 } else {
5337 return BAD_VALUE;
5338 }
5339 return NO_ERROR;
5340}
5341
5342status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5343 struct audio_patch *patches,
5344 unsigned int *generation)
5345{
François Gaffie53615e22015-03-19 09:24:12 +01005346 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005347 return BAD_VALUE;
5348 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005349 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005350 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005351}
5352
Eric Laurente1715a42014-05-20 11:30:42 -07005353status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005354{
Eric Laurente1715a42014-05-20 11:30:42 -07005355 ALOGV("setAudioPortConfig()");
5356
5357 if (config == NULL) {
5358 return BAD_VALUE;
5359 }
5360 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5361 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005362 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5363 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005364 }
5365
Eric Laurenta121f902014-06-03 13:32:54 -07005366 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005367 if (config->type == AUDIO_PORT_TYPE_MIX) {
5368 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005369 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005370 if (outputDesc == NULL) {
5371 return BAD_VALUE;
5372 }
Eric Laurent84c70242014-06-23 08:46:27 -07005373 ALOG_ASSERT(!outputDesc->isDuplicated(),
5374 "setAudioPortConfig() called on duplicated output %d",
5375 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005376 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005377 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005378 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005379 if (inputDesc == NULL) {
5380 return BAD_VALUE;
5381 }
Eric Laurenta121f902014-06-03 13:32:54 -07005382 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005383 } else {
5384 return BAD_VALUE;
5385 }
5386 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5387 sp<DeviceDescriptor> deviceDesc;
5388 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5389 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5390 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5391 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5392 } else {
5393 return BAD_VALUE;
5394 }
5395 if (deviceDesc == NULL) {
5396 return BAD_VALUE;
5397 }
Eric Laurenta121f902014-06-03 13:32:54 -07005398 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005399 } else {
5400 return BAD_VALUE;
5401 }
5402
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005403 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005404 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5405 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005406 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005407 audioPortConfig->toAudioPortConfig(&newConfig, config);
5408 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005409 }
Eric Laurenta121f902014-06-03 13:32:54 -07005410 if (status != NO_ERROR) {
5411 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005412 }
Eric Laurente1715a42014-05-20 11:30:42 -07005413
5414 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005415}
5416
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005417void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5418{
Eric Laurentd60560a2015-04-10 11:31:20 -07005419 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005420 clearAudioPatches(uid);
5421 clearSessionRoutes(uid);
5422}
5423
Eric Laurent6a94d692014-05-20 11:18:06 -07005424void AudioPolicyManager::clearAudioPatches(uid_t uid)
5425{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005426 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005427 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005428 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005429 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005430 }
5431 }
5432}
5433
François Gaffiec005e562018-11-06 15:04:49 +01005434void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005435{
François Gaffiec005e562018-11-06 15:04:49 +01005436 // Take the first attributes following the product strategy as it is used to retrieve the routed
5437 // device. All attributes wihin a strategy follows the same "routing strategy"
5438 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5439 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005440 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005441 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005442 for (size_t j = 0; j < mOutputs.size(); j++) {
5443 if (mOutputs.keyAt(j) == ouptutToSkip) {
5444 continue;
5445 }
5446 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005447 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005448 continue;
5449 }
5450 // If the default device for this strategy is on another output mix,
5451 // invalidate all tracks in this strategy to force re connection.
5452 // Otherwise select new device on the output mix.
5453 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005454 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005455 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005456 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5457 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5458 // If the device is using preferred mixer attributes, the output need to reopen
5459 // with default configuration when the new selected devices are different from
5460 // current routing devices.
5461 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5462 continue;
5463 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305464 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005465 }
5466 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005467 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005468}
5469
5470void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5471{
5472 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005473 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005474 for (size_t i = 0; i < mOutputs.size(); i++) {
5475 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005476 for (const auto& client : outputDesc->getClientIterable()) {
5477 if (client->hasPreferredDevice() && client->uid() == uid) {
5478 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005479 auto clientStrategy = client->strategy();
5480 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5481 end(affectedStrategies)) {
5482 continue;
5483 }
5484 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005485 }
5486 }
5487 }
5488 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005489 for (const auto& strategy : affectedStrategies) {
5490 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005491 }
5492
5493 // remove input routes associated with this uid
5494 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005495 for (size_t i = 0; i < mInputs.size(); i++) {
5496 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005497 for (const auto& client : inputDesc->getClientIterable()) {
5498 if (client->hasPreferredDevice() && client->uid() == uid) {
5499 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5500 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005501 }
5502 }
5503 }
5504 // reroute inputs if necessary
5505 SortedVector<audio_io_handle_t> inputsToClose;
5506 for (size_t i = 0; i < mInputs.size(); i++) {
5507 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005508 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005509 inputsToClose.add(inputDesc->mIoHandle);
5510 }
5511 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005512 for (const auto& input : inputsToClose) {
5513 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005514 }
5515}
5516
Eric Laurentd60560a2015-04-10 11:31:20 -07005517void AudioPolicyManager::clearAudioSources(uid_t uid)
5518{
5519 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005520 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5521 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005522 stopAudioSource(mAudioSources.keyAt(i));
5523 }
5524 }
5525}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005526
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005527status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5528 audio_io_handle_t *ioHandle,
5529 audio_devices_t *device)
5530{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005531 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5532 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005533 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005534 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5535 if (deviceDesc == nullptr) {
5536 return INVALID_OPERATION;
5537 }
5538 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005539
François Gaffiedf372692015-03-19 10:43:27 +01005540 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005541}
5542
Eric Laurentd60560a2015-04-10 11:31:20 -07005543status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005544 const audio_attributes_t *attributes,
5545 audio_port_handle_t *portId,
5546 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005547{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005548 ALOGV("%s", __FUNCTION__);
5549 *portId = AUDIO_PORT_HANDLE_NONE;
5550
5551 if (source == NULL || attributes == NULL || portId == NULL) {
5552 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5553 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005554 return BAD_VALUE;
5555 }
5556
Eric Laurentd60560a2015-04-10 11:31:20 -07005557 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5558 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005559 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5560 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005561 return INVALID_OPERATION;
5562 }
5563
François Gaffie11d30102018-11-02 16:09:09 +01005564 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005565 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005566 String8(source->ext.device.address),
5567 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005568 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005569 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005570 return BAD_VALUE;
5571 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005572
jiabin4ef93452019-09-10 14:29:54 -07005573 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005574
François Gaffieaaac0fd2018-11-22 17:56:39 +01005575 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005576 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005577 mEngine->getStreamTypeForAttributes(*attributes),
5578 mEngine->getProductStrategyForAttributes(*attributes),
5579 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005580
5581 status_t status = connectAudioSource(sourceDesc);
5582 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005583 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005584 }
5585 return status;
5586}
5587
Francois Gaffie601801d2021-06-22 13:27:39 +02005588sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5589 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5590{
5591 ALOGV("%s", __FUNCTION__);
5592 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5593
5594 status_t status = startAudioSource(source, attributes, &portId, uid);
5595 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5596 return mAudioSources.valueFor(portId);
5597}
5598
5599
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005600status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005601{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005602 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005603
5604 // make sure we only have one patch per source.
5605 disconnectAudioSource(sourceDesc);
5606
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005607 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005608 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5609 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5610 sourceDesc->srcDevice()->type(),
5611 String8(sourceDesc->srcDevice()->address().c_str()),
5612 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005613 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005614 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005615 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005616 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005617 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5618 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5619 return INVALID_OPERATION;
5620 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005621 PatchBuilder patchBuilder;
5622 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5623 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005624
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005625 return connectAudioSourceToSink(
5626 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005627}
5628
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005629status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005630{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005631 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5632 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005633 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005634 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005635 return BAD_VALUE;
5636 }
5637 status_t status = disconnectAudioSource(sourceDesc);
5638
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005639 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005640 return status;
5641}
5642
Andy Hung2ddee192015-12-18 17:34:44 -08005643status_t AudioPolicyManager::setMasterMono(bool mono)
5644{
5645 if (mMasterMono == mono) {
5646 return NO_ERROR;
5647 }
5648 mMasterMono = mono;
5649 // if enabling mono we close all offloaded devices, which will invalidate the
5650 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5651 // for recreating the new AudioTrack as non-offloaded PCM.
5652 //
5653 // If disabling mono, we leave all tracks as is: we don't know which clients
5654 // and tracks are able to be recreated as offloaded. The next "song" should
5655 // play back offloaded.
5656 if (mMasterMono) {
5657 Vector<audio_io_handle_t> offloaded;
5658 for (size_t i = 0; i < mOutputs.size(); ++i) {
5659 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5660 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5661 offloaded.push(desc->mIoHandle);
5662 }
5663 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005664 for (const auto& handle : offloaded) {
5665 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005666 }
5667 }
5668 // update master mono for all remaining outputs
5669 for (size_t i = 0; i < mOutputs.size(); ++i) {
5670 updateMono(mOutputs.keyAt(i));
5671 }
5672 return NO_ERROR;
5673}
5674
5675status_t AudioPolicyManager::getMasterMono(bool *mono)
5676{
5677 *mono = mMasterMono;
5678 return NO_ERROR;
5679}
5680
Eric Laurentac9cef52017-06-09 15:46:26 -07005681float AudioPolicyManager::getStreamVolumeDB(
5682 audio_stream_type_t stream, int index, audio_devices_t device)
5683{
jiabin9a3361e2019-10-01 09:38:30 -07005684 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005685}
5686
jiabin81772902018-04-02 17:52:27 -07005687status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5688 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005689 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005690{
Kriti Dang6537def2021-03-02 13:46:59 +01005691 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5692 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005693 return BAD_VALUE;
5694 }
Kriti Dang6537def2021-03-02 13:46:59 +01005695 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5696 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005697
5698 size_t formatsWritten = 0;
5699 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005700
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005701 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005702 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5703 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005704 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005705 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005706 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005707 bool formatEnabled = true;
5708 switch (forceUse) {
5709 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005710 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005711 break;
5712 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5713 formatEnabled = false;
5714 break;
5715 default: // AUTO or ALWAYS => true
5716 break;
jiabin81772902018-04-02 17:52:27 -07005717 }
5718 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5719 }
jiabin81772902018-04-02 17:52:27 -07005720 }
5721 return NO_ERROR;
5722}
5723
Kriti Dang6537def2021-03-02 13:46:59 +01005724status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5725 audio_format_t *surroundFormats) {
5726 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5727 return BAD_VALUE;
5728 }
5729 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5730 __func__, *numSurroundFormats, surroundFormats);
5731
5732 size_t formatsWritten = 0;
5733 size_t formatsMax = *numSurroundFormats;
5734 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5735
5736 // Return formats from all device profiles that have already been resolved by
5737 // checkOutputsForDevice().
5738 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5739 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5740 audio_devices_t deviceType = device->type();
5741 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5742 // returns formats reported by HDMI devices.
5743 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5744 continue;
5745 }
5746 // Formats reported by sink devices
5747 std::unordered_set<audio_format_t> formatset;
5748 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5749 formatset.insert(it->second.begin(), it->second.end());
5750 }
5751
5752 // Formats hard-coded in the in policy configuration file (if any).
5753 FormatVector encodedFormats = device->encodedFormats();
5754 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5755 // Filter the formats which are supported by the vendor hardware.
5756 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005757 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005758 formats.insert(*it);
5759 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005760 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005761 if (pair.second.count(*it) != 0) {
5762 formats.insert(pair.first);
5763 break;
5764 }
5765 }
5766 }
5767 }
5768 }
5769 *numSurroundFormats = formats.size();
5770 for (const auto& format: formats) {
5771 if (formatsWritten < formatsMax) {
5772 surroundFormats[formatsWritten++] = format;
5773 }
5774 }
5775 return NO_ERROR;
5776}
5777
jiabin81772902018-04-02 17:52:27 -07005778status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5779{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005780 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005781 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5782 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005783 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005784 return BAD_VALUE;
5785 }
5786
Mikhail Naganov100f0122018-11-29 11:22:16 -08005787 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5788 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005789 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005790 return INVALID_OPERATION;
5791 }
5792
Mikhail Naganov100f0122018-11-29 11:22:16 -08005793 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005794 return NO_ERROR;
5795 }
5796
Mikhail Naganov100f0122018-11-29 11:22:16 -08005797 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005798 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005799 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005800 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005801 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005802 }
5803 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005804 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005805 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005806 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005807 }
5808 }
5809
5810 sp<SwAudioOutputDescriptor> outputDesc;
5811 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005812 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5813 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005814 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5815 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005816 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005817 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005818 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5819 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5820 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005821 name.c_str(),
5822 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005823 if (status != NO_ERROR) {
5824 continue;
5825 }
5826 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5827 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5828 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005829 name.c_str(),
5830 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005831 profileUpdated |= (status == NO_ERROR);
5832 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005833 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005834 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005835 AUDIO_DEVICE_IN_HDMI);
5836 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5837 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005838 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005839 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005840 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5841 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5842 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005843 name.c_str(),
5844 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005845 if (status != NO_ERROR) {
5846 continue;
5847 }
5848 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5849 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5850 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005851 name.c_str(),
5852 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005853 profileUpdated |= (status == NO_ERROR);
5854 }
5855
jiabin81772902018-04-02 17:52:27 -07005856 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005857 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005858 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005859 }
5860
5861 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5862}
5863
Eric Laurent5ada82e2019-08-29 17:53:54 -07005864void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005865{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005866 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005867 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005868 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005869 }
5870}
5871
jiabin6012f912018-11-02 17:06:30 -07005872bool AudioPolicyManager::isHapticPlaybackSupported()
5873{
5874 for (const auto& hwModule : mHwModules) {
5875 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5876 for (const auto &outProfile : outputProfiles) {
5877 struct audio_port audioPort;
5878 outProfile->toAudioPort(&audioPort);
5879 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5880 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5881 return true;
5882 }
5883 }
5884 }
5885 }
5886 return false;
5887}
5888
Carter Hsu325a8eb2022-01-19 19:56:51 +08005889bool AudioPolicyManager::isUltrasoundSupported()
5890{
5891 bool hasUltrasoundOutput = false;
5892 bool hasUltrasoundInput = false;
5893 for (const auto& hwModule : mHwModules) {
5894 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5895 if (!hasUltrasoundOutput) {
5896 for (const auto &outProfile : outputProfiles) {
5897 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5898 hasUltrasoundOutput = true;
5899 break;
5900 }
5901 }
5902 }
5903
5904 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5905 if (!hasUltrasoundInput) {
5906 for (const auto &inputProfile : inputProfiles) {
5907 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5908 hasUltrasoundInput = true;
5909 break;
5910 }
5911 }
5912 }
5913
5914 if (hasUltrasoundOutput && hasUltrasoundInput)
5915 return true;
5916 }
5917 return false;
5918}
5919
Atneya Nair698f5ef2022-12-15 16:15:09 -08005920bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5921{
5922 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5923 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5924 for (const auto& hwModule : mHwModules) {
5925 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5926 for (const auto &inputProfile : inputProfiles) {
5927 if ((inputProfile->getFlags() & mask) == mask) {
5928 return true;
5929 }
5930 }
5931 }
5932 return false;
5933}
5934
Eric Laurent8340e672019-11-06 11:01:08 -08005935bool AudioPolicyManager::isCallScreenModeSupported()
5936{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005937 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005938}
5939
5940
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005941status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005942{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005943 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005944 if (!sourceDesc->isConnected()) {
5945 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5946 return NO_ERROR;
5947 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005948 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5949 if (swOutput != 0) {
5950 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005951 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005952 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005953 }
jiabinbce0c1d2020-10-05 11:20:18 -07005954 if (releaseOutput(sourceDesc->portId())) {
5955 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5956 // no need to release audio patch here but just return NO_ERROR.
5957 return NO_ERROR;
5958 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005959 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005960 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005961 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005962 // close Hwoutput and remove from mHwOutputs
5963 } else {
5964 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5965 }
5966 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005967 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005968 sourceDesc->disconnect();
5969 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005970}
5971
François Gaffiec005e562018-11-06 15:04:49 +01005972sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5973 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005974{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005975 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005976 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005977 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005978 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005979 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5980 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005981 source = sourceDesc;
5982 break;
5983 }
5984 }
5985 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005986}
5987
Eric Laurentb4f42a92022-01-17 17:37:31 +01005988bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005989 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005990 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005991{
5992 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5993 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005994 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005995 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005996 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5997 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5998 return false;
5999 }
6000 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
6001 return false;
6002 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006003 }
6004
Eric Laurentd332bc82023-08-04 11:45:23 +02006005 // The caller can have the audio config criteria ignored by either passing a null ptr or
6006 // the AUDIO_CONFIG_INITIALIZER value.
6007 // If an audio config is specified, current policy is to only allow spatialization for
6008 // some positional channel masks and PCM format
6009
6010 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08006011 const bool channel_mask_spatialized =
6012 com_android_media_audio_stereo_spatialization()
6013 ? audio_channel_mask_contains_stereo(config->channel_mask)
6014 : audio_is_channel_mask_spatialized(config->channel_mask);
6015 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02006016 return false;
6017 }
6018 if (!audio_is_linear_pcm(config->format)) {
6019 return false;
6020 }
6021 }
6022
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006023 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006024 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006025 if (profile == nullptr) {
6026 return false;
6027 }
6028
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006029 return true;
6030}
6031
6032void AudioPolicyManager::checkVirtualizerClientRoutes() {
6033 std::set<audio_stream_type_t> streamsToInvalidate;
6034 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006035 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6036 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006037 audio_attributes_t attr = client->attributes();
6038 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6039 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6040 audio_config_base_t clientConfig = client->config();
6041 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006042 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006043 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006044 streamsToInvalidate.insert(client->stream());
6045 }
6046 }
6047 }
6048
jiabinc44b3462022-12-08 12:52:31 -08006049 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006050}
6051
Eric Laurente191d1b2022-04-15 11:59:25 +02006052
6053bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6054 const sp<SwAudioOutputDescriptor>& outputDesc) {
6055 if (outputDesc->isDuplicated()) {
6056 return false;
6057 }
6058 DeviceVector devices = outputDesc->supportedDevices();
6059 for (size_t i = 0; i < mOutputs.size(); i++) {
6060 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6061 if (desc == outputDesc || desc->isDuplicated()) {
6062 continue;
6063 }
6064 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6065 if (!sharedDevices.isEmpty()
6066 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6067 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6068 return false;
6069 }
6070 }
6071 return true;
6072}
6073
6074
Eric Laurentfa0f6742021-08-17 18:39:44 +02006075status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006076 const audio_attributes_t *attr,
6077 audio_io_handle_t *output) {
6078 *output = AUDIO_IO_HANDLE_NONE;
6079
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006080 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6081 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6082 audio_config_t *configPtr = nullptr;
6083 audio_config_t config;
6084 if (mixerConfig != nullptr) {
6085 config = audio_config_initializer(mixerConfig);
6086 configPtr = &config;
6087 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006088 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006089 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006090 return BAD_VALUE;
6091 }
6092
6093 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006094 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006095 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006096 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006097 return BAD_VALUE;
6098 }
6099
Eric Laurente191d1b2022-04-15 11:59:25 +02006100 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006101 for (size_t i = 0; i < mOutputs.size(); i++) {
6102 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006103 if (!desc->isDuplicated()
6104 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6105 spatializerOutputs.push_back(desc);
6106 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006107 }
6108 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006109 mSpatializerOutput.clear();
6110 bool outputsChanged = false;
6111 for (const auto& desc : spatializerOutputs) {
6112 if (desc->mProfile == profile
6113 && (configPtr == nullptr
6114 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6115 mSpatializerOutput = desc;
6116 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6117 } else {
6118 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6119 " and devices %s", __func__, desc->mIoHandle,
6120 configPtr != nullptr ? configPtr->channel_mask : 0,
6121 devices.toString().c_str());
6122 closeOutput(desc->mIoHandle);
6123 outputsChanged = true;
6124 }
Eric Laurent39095982021-08-24 18:29:27 +02006125 }
6126
Eric Laurente191d1b2022-04-15 11:59:25 +02006127 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006128 sp<SwAudioOutputDescriptor> desc =
6129 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006130 if (desc != nullptr) {
6131 mSpatializerOutput = desc;
6132 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006133 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006134 }
6135
6136 checkVirtualizerClientRoutes();
6137
Eric Laurente191d1b2022-04-15 11:59:25 +02006138 if (outputsChanged) {
6139 mPreviousOutputs = mOutputs;
6140 mpClientInterface->onAudioPortListUpdate();
6141 }
6142
6143 if (mSpatializerOutput == nullptr) {
6144 ALOGV("%s could not open spatializer output with requested config", __func__);
6145 return BAD_VALUE;
6146 }
Eric Laurent39095982021-08-24 18:29:27 +02006147 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006148 ALOGV("%s returning new spatializer output %d", __func__, *output);
6149 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006150}
6151
Eric Laurentfa0f6742021-08-17 18:39:44 +02006152status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6153 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006154 return INVALID_OPERATION;
6155 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006156 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006157 return BAD_VALUE;
6158 }
Eric Laurent39095982021-08-24 18:29:27 +02006159
Eric Laurente191d1b2022-04-15 11:59:25 +02006160 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6161 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6162 closeOutput(mSpatializerOutput->mIoHandle);
6163 //from now on mSpatializerOutput is null
6164 checkVirtualizerClientRoutes();
6165 }
Eric Laurent39095982021-08-24 18:29:27 +02006166
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006167 return NO_ERROR;
6168}
6169
Eric Laurente552edb2014-03-10 17:42:56 -07006170// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006171// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006172// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006173uint32_t AudioPolicyManager::nextAudioPortGeneration()
6174{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006175 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006176}
6177
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006178AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006179 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006180 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006181 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006182 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006183 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006184 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006185 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006186 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006187 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006188 mAudioPortGeneration(1),
6189 mBeaconMuteRefCount(0),
6190 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006191 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006192 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006193 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006194 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006195{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006196}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006197
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006198status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006199 if (mEngine == nullptr) {
6200 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006201 }
6202 mEngine->setObserver(this);
6203 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006204 if (status != NO_ERROR) {
6205 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6206 return status;
6207 }
François Gaffie2110e042015-03-24 08:41:51 +01006208
jiabin29230182023-04-04 21:02:36 +00006209 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6210 // at the end of this function.
6211 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006212 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6213 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6214
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006215 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006216 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006217 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006218
Eric Laurent3a4311c2014-03-17 12:00:47 -07006219 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006220 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6221 defaultOutputDevice == nullptr ||
6222 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6223 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6224 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006225 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006226 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006227 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006228
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006229 // Silence ALOGV statements
6230 property_set("log.tag." LOG_TAG, "D");
6231
Eric Laurente552edb2014-03-10 17:42:56 -07006232 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006233 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006234}
6235
Eric Laurente0720872014-03-11 09:30:41 -07006236AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006237{
Eric Laurente552edb2014-03-10 17:42:56 -07006238 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006239 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006240 }
6241 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006242 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006243 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006244 mAvailableOutputDevices.clear();
6245 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006246 mOutputs.clear();
6247 mInputs.clear();
6248 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006249 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006250 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006251}
6252
Eric Laurente0720872014-03-11 09:30:41 -07006253status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006254{
Eric Laurent87ffa392015-05-22 10:32:38 -07006255 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006256}
6257
Eric Laurente552edb2014-03-10 17:42:56 -07006258// ---
6259
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006260void AudioPolicyManager::onNewAudioModulesAvailable()
6261{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006262 DeviceVector newDevices;
6263 onNewAudioModulesAvailableInt(&newDevices);
6264 if (!newDevices.empty()) {
6265 nextAudioPortGeneration();
6266 mpClientInterface->onAudioPortListUpdate();
6267 }
6268}
6269
6270void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6271{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006272 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006273 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6274 continue;
6275 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006276 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006277 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6278 handle != AUDIO_MODULE_HANDLE_NONE) {
6279 hwModule->setHandle(handle);
6280 } else {
6281 ALOGW("could not load HW module %s", hwModule->getName());
6282 continue;
6283 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006284 }
6285 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006286 // open all output streams needed to access attached devices.
6287 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006288 // This also validates mAvailableOutputDevices list
6289 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6290 if (!outProfile->canOpenNewIo()) {
6291 ALOGE("Invalid Output profile max open count %u for profile %s",
6292 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6293 continue;
6294 }
6295 if (!outProfile->hasSupportedDevices()) {
6296 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6297 continue;
6298 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006299 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6300 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006301 mTtsOutputAvailable = true;
6302 }
6303
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006304 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006305 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006306 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006307 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6308 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006309 } else {
6310 // choose first device present in profile's SupportedDevices also part of
6311 // mAvailableOutputDevices.
6312 if (availProfileDevices.isEmpty()) {
6313 continue;
6314 }
6315 supportedDevice = availProfileDevices.itemAt(0);
6316 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006317 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006318 continue;
6319 }
6320 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6321 mpClientInterface);
6322 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006323 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6324 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006325 AUDIO_STREAM_DEFAULT,
6326 AUDIO_OUTPUT_FLAG_NONE, &output);
6327 if (status != NO_ERROR) {
6328 ALOGW("Cannot open output stream for devices %s on hw module %s",
6329 supportedDevice->toString().c_str(), hwModule->getName());
6330 continue;
6331 }
6332 for (const auto &device : availProfileDevices) {
6333 // give a valid ID to an attached device once confirmed it is reachable
6334 if (!device->isAttached()) {
6335 device->attach(hwModule);
6336 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006337 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006338 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006339 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6340 }
6341 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006342 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006343 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6344 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006345 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006346 }
Eric Laurent39095982021-08-24 18:29:27 +02006347 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006348 outputDesc->close();
6349 } else {
6350 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306351 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006352 DeviceVector(supportedDevice),
6353 true,
6354 0,
6355 NULL);
6356 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006357 }
6358 // open input streams needed to access attached devices to validate
6359 // mAvailableInputDevices list
6360 for (const auto& inProfile : hwModule->getInputProfiles()) {
6361 if (!inProfile->canOpenNewIo()) {
6362 ALOGE("Invalid Input profile max open count %u for profile %s",
6363 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6364 continue;
6365 }
6366 if (!inProfile->hasSupportedDevices()) {
6367 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6368 continue;
6369 }
6370 // chose first device present in profile's SupportedDevices also part of
6371 // available input devices
6372 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006373 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006374 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006375 ALOGV("%s: Input device list is empty! for profile %s",
6376 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006377 continue;
6378 }
6379 sp<AudioInputDescriptor> inputDesc =
6380 new AudioInputDescriptor(inProfile, mpClientInterface);
6381
6382 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6383 status_t status = inputDesc->open(nullptr,
6384 availProfileDevices.itemAt(0),
6385 AUDIO_SOURCE_MIC,
6386 AUDIO_INPUT_FLAG_NONE,
6387 &input);
6388 if (status != NO_ERROR) {
6389 ALOGW("Cannot open input stream for device %s on hw module %s",
6390 availProfileDevices.toString().c_str(),
6391 hwModule->getName());
6392 continue;
6393 }
6394 for (const auto &device : availProfileDevices) {
6395 // give a valid ID to an attached device once confirmed it is reachable
6396 if (!device->isAttached()) {
6397 device->attach(hwModule);
6398 device->importAudioPortAndPickAudioProfile(inProfile, true);
6399 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006400 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006401 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6402 }
6403 }
6404 inputDesc->close();
6405 }
6406 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006407
6408 // Check if spatializer outputs can be closed until used.
6409 // mOutputs vector never contains duplicated outputs at this point.
6410 std::vector<audio_io_handle_t> outputsClosed;
6411 for (size_t i = 0; i < mOutputs.size(); i++) {
6412 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6413 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6414 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6415 outputsClosed.push_back(desc->mIoHandle);
6416 desc->close();
6417 }
6418 }
6419 for (auto output : outputsClosed) {
6420 removeOutput(output);
6421 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006422}
6423
Eric Laurent98e38192018-02-15 18:31:53 -08006424void AudioPolicyManager::addOutput(audio_io_handle_t output,
6425 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006426{
Eric Laurent1c333e22014-05-20 10:48:17 -07006427 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006428 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006429 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006430 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006431 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006432}
6433
François Gaffie53615e22015-03-19 09:24:12 +01006434void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6435{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006436 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6437 ALOGV("%s: removing primary output", __func__);
6438 mPrimaryOutput = nullptr;
6439 }
François Gaffie53615e22015-03-19 09:24:12 +01006440 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006441 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006442}
6443
Eric Laurent98e38192018-02-15 18:31:53 -08006444void AudioPolicyManager::addInput(audio_io_handle_t input,
6445 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006446{
Eric Laurent1c333e22014-05-20 10:48:17 -07006447 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006448 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006449}
Eric Laurente552edb2014-03-10 17:42:56 -07006450
François Gaffie11d30102018-11-02 16:09:09 +01006451status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006452 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006453 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006454{
François Gaffie11d30102018-11-02 16:09:09 +01006455 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006456 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006457 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006458
François Gaffie11d30102018-11-02 16:09:09 +01006459 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006460 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006461 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006462 }
Eric Laurente552edb2014-03-10 17:42:56 -07006463
Eric Laurent3b73df72014-03-11 09:06:29 -07006464 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006465 // first call getAudioPort to get the supported attributes from the HAL
6466 struct audio_port_v7 port = {};
6467 device->toAudioPort(&port);
6468 status_t status = mpClientInterface->getAudioPort(&port);
6469 if (status == NO_ERROR) {
6470 device->importAudioPort(port);
6471 }
6472
6473 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006474 for (size_t i = 0; i < mOutputs.size(); i++) {
6475 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006476 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006477 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006478 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6479 mOutputs.keyAt(i), device->toString().c_str());
6480 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006481 }
6482 }
6483 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006484 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006485 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006486 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6487 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006488 if (profile->supportsDevice(device)) {
6489 profiles.add(profile);
6490 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6491 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006492 }
6493 }
6494 }
6495
Eric Laurent7b279bb2015-12-14 10:18:23 -08006496 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006497
Eric Laurente552edb2014-03-10 17:42:56 -07006498 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006499 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006500 return BAD_VALUE;
6501 }
6502
6503 // open outputs for matching profiles if needed. Direct outputs are also opened to
6504 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6505 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006506 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006507
6508 // nothing to do if one output is already opened for this profile
6509 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006510 for (j = 0; j < outputs.size(); j++) {
6511 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006512 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006513 // matching profile: save the sample rates, format and channel masks supported
6514 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006515 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006516 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006517 }
Eric Laurente552edb2014-03-10 17:42:56 -07006518 break;
6519 }
6520 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006521 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006522 continue;
6523 }
6524
Eric Laurent3974e3b2017-12-07 17:58:43 -08006525 if (!profile->canOpenNewIo()) {
6526 ALOGW("Max Output number %u already opened for this profile %s",
6527 profile->maxOpenCount, profile->getTagName().c_str());
6528 continue;
6529 }
6530
Eric Laurent83efe1c2017-07-09 16:51:08 -07006531 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006532 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006533 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6534 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006535 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006536 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006537 profiles.removeAt(profile_index);
6538 profile_index--;
6539 } else {
6540 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006541 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006542 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006543 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6544 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006545 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006546 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006547
François Gaffie11d30102018-11-02 16:09:09 +01006548 if (device_distinguishes_on_address(deviceType)) {
6549 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6550 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306551 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6552 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006553 }
Eric Laurente552edb2014-03-10 17:42:56 -07006554 ALOGV("checkOutputsForDevice(): adding output %d", output);
6555 }
6556 }
6557
6558 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006559 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006560 return BAD_VALUE;
6561 }
Eric Laurentd4692962014-05-05 18:13:44 -07006562 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006563 // check if one opened output is not needed any more after disconnecting one device
6564 for (size_t i = 0; i < mOutputs.size(); i++) {
6565 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006566 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006567 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006568 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006569 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006570 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006571 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006572 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6573 mOutputs.keyAt(i));
6574 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006575 }
Eric Laurente552edb2014-03-10 17:42:56 -07006576 }
6577 }
Eric Laurentd4692962014-05-05 18:13:44 -07006578 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006579 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006580 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6581 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006582 if (!profile->supportsDevice(device)) {
6583 continue;
6584 }
6585 ALOGV("checkOutputsForDevice(): "
6586 "clearing direct output profile %zu on module %s",
6587 j, hwModule->getName());
6588 profile->clearAudioProfiles();
6589 if (!profile->hasDynamicAudioProfile()) {
6590 continue;
6591 }
6592 // When a device is disconnected, if there is an IOProfile that contains dynamic
6593 // profiles and supports the disconnected device, call getAudioPort to repopulate
6594 // the capabilities of the devices that is supported by the IOProfile.
6595 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6596 if (supportedDevice == device ||
6597 !mAvailableOutputDevices.contains(supportedDevice)) {
6598 continue;
6599 }
6600 struct audio_port_v7 port;
6601 supportedDevice->toAudioPort(&port);
6602 status_t status = mpClientInterface->getAudioPort(&port);
6603 if (status == NO_ERROR) {
6604 supportedDevice->importAudioPort(port);
6605 }
Eric Laurente552edb2014-03-10 17:42:56 -07006606 }
6607 }
6608 }
6609 }
6610 return NO_ERROR;
6611}
6612
François Gaffie11d30102018-11-02 16:09:09 +01006613status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006614 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006615{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006616 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006617
François Gaffie11d30102018-11-02 16:09:09 +01006618 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006619 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006620 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006621 }
6622
Eric Laurentd4692962014-05-05 18:13:44 -07006623 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006624 // first call getAudioPort to get the supported attributes from the HAL
6625 struct audio_port_v7 port = {};
6626 device->toAudioPort(&port);
6627 status_t status = mpClientInterface->getAudioPort(&port);
6628 if (status == NO_ERROR) {
6629 device->importAudioPort(port);
6630 }
6631
Eric Laurent0dd51852019-04-19 18:18:58 -07006632 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006633 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006634 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006635 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006636 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006637 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006638 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006639
François Gaffie11d30102018-11-02 16:09:09 +01006640 if (profile->supportsDevice(device)) {
6641 profiles.add(profile);
6642 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6643 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006644 }
6645 }
6646 }
6647
Eric Laurent0dd51852019-04-19 18:18:58 -07006648 if (profiles.isEmpty()) {
6649 ALOGW("%s: No input profile available for device %s",
6650 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006651 return BAD_VALUE;
6652 }
6653
6654 // open inputs for matching profiles if needed. Direct inputs are also opened to
6655 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6656 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6657
Eric Laurent1c333e22014-05-20 10:48:17 -07006658 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006659
Eric Laurentd4692962014-05-05 18:13:44 -07006660 // nothing to do if one input is already opened for this profile
6661 size_t input_index;
6662 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6663 desc = mInputs.valueAt(input_index);
6664 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006665 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006666 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006667 }
Eric Laurentd4692962014-05-05 18:13:44 -07006668 break;
6669 }
6670 }
6671 if (input_index != mInputs.size()) {
6672 continue;
6673 }
6674
Eric Laurent3974e3b2017-12-07 17:58:43 -08006675 if (!profile->canOpenNewIo()) {
6676 ALOGW("Max Input number %u already opened for this profile %s",
6677 profile->maxOpenCount, profile->getTagName().c_str());
6678 continue;
6679 }
6680
Eric Laurentfe231122017-11-17 17:48:06 -08006681 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006682 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006683 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006684
Eric Laurentcf2c0212014-07-25 16:20:43 -07006685 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006686 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006687 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006688 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006689 mpClientInterface->setParameters(input, String8(param));
6690 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006691 }
jiabin12537fc2023-10-12 17:56:08 +00006692 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006693 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006694 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006695 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006696 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006697 }
6698
Eric Laurent0dd51852019-04-19 18:18:58 -07006699 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006700 addInput(input, desc);
6701 }
6702 } // endif input != 0
6703
Eric Laurentcf2c0212014-07-25 16:20:43 -07006704 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006705 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006706 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006707 profiles.removeAt(profile_index);
6708 profile_index--;
6709 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006710 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006711 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006712 }
Eric Laurentd4692962014-05-05 18:13:44 -07006713 ALOGV("checkInputsForDevice(): adding input %d", input);
6714 }
6715 } // end scan profiles
6716
6717 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006718 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006719 return BAD_VALUE;
6720 }
6721 } else {
6722 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006723 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006724 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006725 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006726 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006727 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006728 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006729 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006730 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6731 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006732 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006733 }
6734 }
6735 }
6736 } // end disconnect
6737
6738 return NO_ERROR;
6739}
6740
6741
Eric Laurente0720872014-03-11 09:30:41 -07006742void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006743{
6744 ALOGV("closeOutput(%d)", output);
6745
François Gaffie1c878552018-11-22 16:53:21 +01006746 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6747 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006748 ALOGW("closeOutput() unknown output %d", output);
6749 return;
6750 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006751 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006752 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006753
Eric Laurente552edb2014-03-10 17:42:56 -07006754 // look for duplicated outputs connected to the output being removed.
6755 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006756 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6757 if (dupOutput->isDuplicated() &&
6758 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6759 sp<SwAudioOutputDescriptor> remainingOutput =
6760 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006761 // As all active tracks on duplicated output will be deleted,
6762 // and as they were also referenced on the other output, the reference
6763 // count for their stream type must be adjusted accordingly on
6764 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006765 const bool wasActive = remainingOutput->isActive();
6766 // Note: no-op on the closing output where all clients has already been set inactive
6767 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006768 // stop() will be a no op if the output is still active but is needed in case all
6769 // active streams refcounts where cleared above
6770 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006771 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006772 }
Eric Laurente552edb2014-03-10 17:42:56 -07006773 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6774 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6775
6776 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006777 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006778 }
6779 }
6780
Eric Laurent05b90f82014-08-27 15:32:29 -07006781 nextAudioPortGeneration();
6782
François Gaffie1c878552018-11-22 16:53:21 +01006783 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006784 if (index >= 0) {
6785 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006786 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6787 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006788 mAudioPatches.removeItemsAt(index);
6789 mpClientInterface->onAudioPatchListUpdate();
6790 }
6791
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006792 if (closingOutputWasActive) {
6793 closingOutput->stop();
6794 }
François Gaffie1c878552018-11-22 16:53:21 +01006795 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006796 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6797 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6798 for (const auto device : closingOutput->devices()) {
6799 device->setPreferredConfig(nullptr);
6800 }
6801 }
Eric Laurente552edb2014-03-10 17:42:56 -07006802
François Gaffie53615e22015-03-19 09:24:12 +01006803 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006804 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006805 if (closingOutput == mSpatializerOutput) {
6806 mSpatializerOutput.clear();
6807 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006808
6809 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6810 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006811 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006812 bool directOutputOpen = false;
6813 for (size_t i = 0; i < mOutputs.size(); i++) {
6814 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6815 directOutputOpen = true;
6816 break;
6817 }
6818 }
6819 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006820 ALOGV("no direct outputs open, reset MSD patches");
6821 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6822 // how output devices for patching are resolved. Avoid by caching and reusing the
6823 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6824 // devices to patch to. This may be complicated by the fact that devices may become
6825 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006826 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006827 }
6828 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006829}
6830
6831void AudioPolicyManager::closeInput(audio_io_handle_t input)
6832{
6833 ALOGV("closeInput(%d)", input);
6834
6835 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6836 if (inputDesc == NULL) {
6837 ALOGW("closeInput() unknown input %d", input);
6838 return;
6839 }
6840
Eric Laurent6a94d692014-05-20 11:18:06 -07006841 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006842
François Gaffie11d30102018-11-02 16:09:09 +01006843 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006844 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006845 if (index >= 0) {
6846 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006847 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6848 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006849 mAudioPatches.removeItemsAt(index);
6850 mpClientInterface->onAudioPatchListUpdate();
6851 }
6852
François Gaffie6ebbce02023-07-19 13:27:53 +02006853 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006854 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006855 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006856
François Gaffie11d30102018-11-02 16:09:09 +01006857 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6858 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006859 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006860 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006861 }
Eric Laurente552edb2014-03-10 17:42:56 -07006862}
6863
François Gaffie11d30102018-11-02 16:09:09 +01006864SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6865 const DeviceVector &devices,
6866 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006867{
6868 SortedVector<audio_io_handle_t> outputs;
6869
François Gaffie11d30102018-11-02 16:09:09 +01006870 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006871 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006872 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006873 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006874 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006875 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006876 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006877 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006878 outputs.add(openOutputs.keyAt(i));
6879 }
6880 }
6881 return outputs;
6882}
6883
Mikhail Naganov37977152018-07-11 15:54:44 -07006884void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6885{
6886 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6887 // output is suspended before any tracks are moved to it
6888 checkA2dpSuspend();
6889 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006890 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006891 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006892 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006893 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006894 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6895 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6896 // configuration changes will ultimately be rerouted correctly. We can still avoid
6897 // unnecessary rerouting by caching and reusing the arguments to
6898 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6899 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006900 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006901 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006902 // an event that changed routing likely occurred, inform upper layers
6903 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006904}
6905
François Gaffiec005e562018-11-06 15:04:49 +01006906bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6907 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006908{
François Gaffiec005e562018-11-06 15:04:49 +01006909 return mEngine->getProductStrategyForAttributes(lAttr) ==
6910 mEngine->getProductStrategyForAttributes(rAttr);
6911}
6912
Francois Gaffieff1eb522020-05-06 18:37:04 +02006913void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6914{
6915 for (size_t i = 0; i < mAudioSources.size(); i++) {
6916 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6917 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006918 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006919 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006920 connectAudioSource(sourceDesc);
6921 }
6922 }
6923}
6924
6925void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6926{
6927 for (size_t i = 0; i < mAudioSources.size(); i++) {
6928 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6929 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6930 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6931 disconnectAudioSource(sourceDesc);
6932 }
6933 }
6934}
6935
François Gaffiec005e562018-11-06 15:04:49 +01006936void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6937{
6938 auto psId = mEngine->getProductStrategyForAttributes(attr);
6939
6940 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6941 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006942
François Gaffie11d30102018-11-02 16:09:09 +01006943 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6944 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006945
Eric Laurentc209fe42020-06-05 18:11:23 -07006946 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006947 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006948 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006949 // take into account dynamic audio policies related changes: if a client is now associated
6950 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006951 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006952 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6953 if (desc->isDuplicated()) {
6954 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006955 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006956 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6957 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6958 continue;
6959 }
6960 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006961 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006962 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6963 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6964 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006965 if (status != OK) {
6966 continue;
6967 }
yucliuf4de36d2020-09-14 14:57:56 -07006968 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006969 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006970 maxLatency = desc->latency();
6971 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006972 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006973 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006974 }
6975 }
6976
Eric Laurent56ed8842022-11-15 16:04:41 +01006977 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006978 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6979 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006980 for (audio_io_handle_t srcOut : srcOutputs) {
6981 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006982 if (desc == nullptr) continue;
6983
6984 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006985 maxLatency = desc->latency();
6986 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006987
Eric Laurent56ed8842022-11-15 16:04:41 +01006988 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006989 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006990 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006991 // a client on a non direct outputs has necessarily a linear PCM format
6992 // so we can call selectOutput() safely
6993 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6994 client->flags(),
6995 client->config().format,
6996 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006997 client->config().sample_rate,
6998 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006999 if (newOutput != srcOut) {
7000 invalidate = true;
7001 break;
7002 }
7003 } else {
7004 sp<IOProfile> profile = getProfileForOutput(newDevices,
7005 client->config().sample_rate,
7006 client->config().format,
7007 client->config().channel_mask,
7008 client->flags(),
7009 true /* directOnly */);
7010 if (profile != desc->mProfile) {
7011 invalidate = true;
7012 break;
7013 }
7014 }
7015 }
Eric Laurent56ed8842022-11-15 16:04:41 +01007016 // mute strategy while moving tracks from one output to another
7017 if (invalidate) {
7018 invalidatedOutputs.push_back(desc);
7019 if (desc->isStrategyActive(psId)) {
7020 setStrategyMute(psId, true, desc);
7021 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7022 newDevices.types());
7023 }
Eric Laurente552edb2014-03-10 17:42:56 -07007024 }
François Gaffiec005e562018-11-06 15:04:49 +01007025 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007026 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007027 connectAudioSource(source);
7028 }
Eric Laurente552edb2014-03-10 17:42:56 -07007029 }
7030
Eric Laurent56ed8842022-11-15 16:04:41 +01007031 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7032 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7033 std::to_string(srcOutputs[0]).c_str(),
7034 std::to_string(dstOutputs[0]).c_str());
7035
François Gaffiec005e562018-11-06 15:04:49 +01007036 // Move effects associated to this stream from previous output to new output
7037 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007038 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007039 }
François Gaffiec005e562018-11-06 15:04:49 +01007040 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007041 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007042 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007043 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007044 desc->setTracksInvalidatedStatusByStrategy(psId);
7045 }
Eric Laurente552edb2014-03-10 17:42:56 -07007046 }
7047 }
7048}
7049
Eric Laurente0720872014-03-11 09:30:41 -07007050void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007051{
François Gaffiec005e562018-11-06 15:04:49 +01007052 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7053 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7054 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007055 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007056 }
Eric Laurente552edb2014-03-10 17:42:56 -07007057}
7058
Kevin Rocard153f92d2018-12-18 18:33:28 -08007059void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007060 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007061 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007062 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007063 for (size_t i = 0; i < mOutputs.size(); i++) {
7064 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7065 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007066 sp<AudioPolicyMix> primaryMix;
7067 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007068 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007069 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7070 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7071 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007072 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7073 for (auto &secondaryMix : secondaryMixes) {
7074 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7075 if (outputDesc != nullptr &&
7076 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7077 secondaryDescs.push_back(outputDesc);
7078 }
7079 }
7080
jiabinc44b3462022-12-08 12:52:31 -08007081 if (status != OK &&
7082 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7083 // When it failed to query secondary output, only invalidate the client that is not
7084 // MMAP. The reason is that MMAP stream will not support secondary output.
7085 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007086 } else if (!std::equal(
7087 client->getSecondaryOutputs().begin(),
7088 client->getSecondaryOutputs().end(),
7089 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007090 if (!audio_is_linear_pcm(client->config().format)) {
7091 // If the format is not PCM, the tracks should be invalidated to get correct
7092 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007093 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007094 } else {
7095 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7096 std::vector<audio_io_handle_t> secondaryOutputIds;
7097 for (const auto &secondaryDesc: secondaryDescs) {
7098 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7099 weakSecondaryDescs.push_back(secondaryDesc);
7100 }
7101 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7102 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007103 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007104 }
7105 }
7106 }
jiabin10a03f12021-05-07 23:46:28 +00007107 if (!trackSecondaryOutputs.empty()) {
7108 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7109 }
jiabinc44b3462022-12-08 12:52:31 -08007110 if (!clientsToInvalidate.empty()) {
7111 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7112 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007113 }
7114}
7115
Eric Laurent2517af32020-11-25 15:31:27 +01007116bool AudioPolicyManager::isScoRequestedForComm() const {
7117 AudioDeviceTypeAddrVector devices;
7118 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7119 for (const auto &device : devices) {
7120 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7121 return true;
7122 }
7123 }
7124 return false;
7125}
7126
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007127bool AudioPolicyManager::isHearingAidUsedForComm() const {
7128 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7129 true /*fromCache*/);
7130 for (const auto &device : devices) {
7131 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7132 return true;
7133 }
7134 }
7135 return false;
7136}
7137
7138
Eric Laurente0720872014-03-11 09:30:41 -07007139void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007140{
François Gaffie53615e22015-03-19 09:24:12 +01007141 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007142 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007143 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007144 return;
7145 }
7146
Eric Laurent3a4311c2014-03-17 12:00:47 -07007147 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007148 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7149 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007150 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007151
7152 // if suspended, restore A2DP output if:
7153 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007154 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007155 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007156 //
Eric Laurentf732e072016-08-03 19:30:28 -07007157 // if not suspended, suspend A2DP output if:
7158 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007159 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007160 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007161 //
7162 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007163 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007164 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007165 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007166 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007167
7168 mpClientInterface->restoreOutput(a2dpOutput);
7169 mA2dpSuspended = false;
7170 }
7171 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007172 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007173 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007174 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007175 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007176
7177 mpClientInterface->suspendOutput(a2dpOutput);
7178 mA2dpSuspended = true;
7179 }
7180 }
7181}
7182
François Gaffie11d30102018-11-02 16:09:09 +01007183DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7184 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007185{
François Gaffiedb1755b2023-09-01 11:50:35 +02007186 if (outputDesc == nullptr) {
7187 return DeviceVector{};
7188 }
François Gaffie11d30102018-11-02 16:09:09 +01007189
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007190 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007191 if (index >= 0) {
7192 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007193 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007194 ALOGV("%s device %s forced by patch %d", __func__,
7195 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7196 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007197 }
7198 }
7199
Dean Wheatley514b4312020-06-17 21:45:00 +10007200 // Do not retrieve engine device for outputs through MSD
7201 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7202 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7203 return outputDesc->devices();
7204 }
7205
Eric Laurent97ac8712018-07-27 18:59:02 -07007206 // Honor explicit routing requests only if no client using default routing is active on this
7207 // input: a specific app can not force routing for other apps by setting a preferred device.
7208 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007209 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007210 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007211 if (device != nullptr) {
7212 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007213 }
7214
François Gaffiea807ef92018-11-05 10:44:33 +01007215 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7216 // of setForceUse / Default Bus device here
7217 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7218 if (device != nullptr) {
7219 return DeviceVector(device);
7220 }
7221
François Gaffiedb1755b2023-09-01 11:50:35 +02007222 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007223 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7224 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7225 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307226 auto hasStreamActive = [&](auto stream) {
7227 return hasStream(streams, stream) && isStreamActive(stream, 0);
7228 };
Eric Laurent484e9272018-06-07 17:29:23 -07007229
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307230 auto doGetOutputDevicesForVoice = [&]() {
7231 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007232 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307233 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007234 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7235 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307236 };
7237
7238 // With low-latency playing on speaker, music on WFD, when the first low-latency
7239 // output is stopped, getNewOutputDevices checks for a product strategy
7240 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007241 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307242 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7243 // stream is associated to the output descriptor.
7244 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7245 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7246 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7247 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007248 // Retrieval of devices for voice DL is done on primary output profile, cannot
7249 // check the route (would force modifying configuration file for this profile)
7250 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7251 break;
7252 }
Eric Laurente552edb2014-03-10 17:42:56 -07007253 }
François Gaffiec005e562018-11-06 15:04:49 +01007254 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007255 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007256}
7257
François Gaffie11d30102018-11-02 16:09:09 +01007258sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7259 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007260{
François Gaffie11d30102018-11-02 16:09:09 +01007261 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007262
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007263 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007264 if (index >= 0) {
7265 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007266 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007267 ALOGV("getNewInputDevice() device %s forced by patch %d",
7268 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7269 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007270 }
7271 }
7272
Eric Laurent97ac8712018-07-27 18:59:02 -07007273 // Honor explicit routing requests only if no client using default routing is active on this
7274 // input: a specific app can not force routing for other apps by setting a preferred device.
7275 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007276 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7277 if (device != nullptr) {
7278 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007279 }
7280
Eric Laurentdc95a252018-04-12 12:46:56 -07007281 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007282 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007283 audio_attributes_t attributes;
7284 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007285 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007286 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7287 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007288 attributes = topClient->attributes();
7289 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007290 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007291 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007292 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7293 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007294 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007295 }
7296
Francois Gaffie716e1432019-01-14 16:58:59 +01007297 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7298 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007299 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007300 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007301 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007302 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007303
Eric Laurente552edb2014-03-10 17:42:56 -07007304 return device;
7305}
7306
Eric Laurent794fde22016-03-11 09:50:45 -08007307bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7308 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007309 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007310}
7311
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007312status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007313 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007314 if (devices == nullptr) {
7315 return BAD_VALUE;
7316 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007317
Andy Hung6d23c0f2022-02-16 09:37:15 -08007318 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007319 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7320 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007321 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007322 for (const auto& device : curDevices) {
7323 devices->push_back(device->getDeviceTypeAddr());
7324 }
7325 return NO_ERROR;
7326}
7327
Eric Laurente0720872014-03-11 09:30:41 -07007328void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007329 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007330 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007331 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007332 updateDevicesAndOutputs();
7333 break;
7334 default:
7335 break;
7336 }
7337}
7338
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007339uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007340
7341 // skip beacon mute management if a dedicated TTS output is available
7342 if (mTtsOutputAvailable) {
7343 return 0;
7344 }
7345
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007346 switch(event) {
7347 case STARTING_OUTPUT:
7348 mBeaconMuteRefCount++;
7349 break;
7350 case STOPPING_OUTPUT:
7351 if (mBeaconMuteRefCount > 0) {
7352 mBeaconMuteRefCount--;
7353 }
7354 break;
7355 case STARTING_BEACON:
7356 mBeaconPlayingRefCount++;
7357 break;
7358 case STOPPING_BEACON:
7359 if (mBeaconPlayingRefCount > 0) {
7360 mBeaconPlayingRefCount--;
7361 }
7362 break;
7363 }
7364
7365 if (mBeaconMuteRefCount > 0) {
7366 // any playback causes beacon to be muted
7367 return setBeaconMute(true);
7368 } else {
7369 // no other playback: unmute when beacon starts playing, mute when it stops
7370 return setBeaconMute(mBeaconPlayingRefCount == 0);
7371 }
7372}
7373
7374uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7375 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7376 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7377 // keep track of muted state to avoid repeating mute/unmute operations
7378 if (mBeaconMuted != mute) {
7379 // mute/unmute AUDIO_STREAM_TTS on all outputs
7380 ALOGV("\t muting %d", mute);
7381 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007382 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7383 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7384 ALOGV("\t no tts volume source available");
7385 return 0;
7386 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007387 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007388 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007389 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007390 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007391 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007392 maxLatency = latency;
7393 }
7394 }
7395 mBeaconMuted = mute;
7396 return maxLatency;
7397 }
7398 return 0;
7399}
7400
Eric Laurente0720872014-03-11 09:30:41 -07007401void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007402{
François Gaffiec005e562018-11-06 15:04:49 +01007403 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007404 mPreviousOutputs = mOutputs;
7405}
7406
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007407uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007408 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007409 uint32_t delayMs)
7410{
7411 // mute/unmute strategies using an incompatible device combination
7412 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7413 // if unmuting, unmute only after the specified delay
7414 if (outputDesc->isDuplicated()) {
7415 return 0;
7416 }
7417
7418 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007419 DeviceVector devices = outputDesc->devices();
7420 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007421
François Gaffiec005e562018-11-06 15:04:49 +01007422 auto productStrategies = mEngine->getOrderedProductStrategies();
7423 for (const auto &productStrategy : productStrategies) {
7424 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7425 DeviceVector curDevices =
7426 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7427 curDevices = curDevices.filter(outputDesc->supportedDevices());
7428 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007429 bool doMute = false;
7430
François Gaffiec005e562018-11-06 15:04:49 +01007431 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007432 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007433 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7434 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007435 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007436 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007437 }
Eric Laurent99401132014-05-07 19:48:15 -07007438 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007439 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007440 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007441 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007442 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007443 continue;
7444 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307445 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007446 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7447 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7448 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007449 if (mute) {
7450 // FIXME: should not need to double latency if volume could be applied
7451 // immediately by the audioflinger mixer. We must account for the delay
7452 // between now and the next time the audioflinger thread for this output
7453 // will process a buffer (which corresponds to one buffer size,
7454 // usually 1/2 or 1/4 of the latency).
7455 if (muteWaitMs < desc->latency() * 2) {
7456 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007457 }
7458 }
7459 }
7460 }
7461 }
7462 }
7463
Eric Laurent99401132014-05-07 19:48:15 -07007464 // temporary mute output if device selection changes to avoid volume bursts due to
7465 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007466 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007467 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007468
Eric Laurentdc462862016-07-19 12:29:53 -07007469 if (muteWaitMs < tempMuteWaitMs) {
7470 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007471 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007472
7473 // If recommended duration is defined, replace temporary mute duration to avoid
7474 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7475 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7476 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7477 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7478 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7479
François Gaffieaaac0fd2018-11-22 17:56:39 +01007480 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7481 // make sure that we do not start the temporary mute period too early in case of
7482 // delayed device change
7483 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7484 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007485 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007486 }
7487 }
7488
Eric Laurente552edb2014-03-10 17:42:56 -07007489 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7490 if (muteWaitMs > delayMs) {
7491 muteWaitMs -= delayMs;
7492 usleep(muteWaitMs * 1000);
7493 return muteWaitMs;
7494 }
7495 return 0;
7496}
7497
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307498uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7499 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007500 const DeviceVector &devices,
7501 bool force,
7502 int delayMs,
7503 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007504 bool requiresMuteCheck, bool requiresVolumeCheck,
7505 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007506{
jiabin3ff8d7d2022-12-13 06:27:44 +00007507 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307508 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7509 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7510 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007511 uint32_t muteWaitMs;
7512
7513 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307514 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007515 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307516 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007517 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007518 return muteWaitMs;
7519 }
Eric Laurente552edb2014-03-10 17:42:56 -07007520
7521 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007522 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007523 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007524 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007525
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307526 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7527 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007528
7529 if (!filteredDevices.isEmpty()) {
7530 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007531 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007532
7533 // if the outputs are not materially active, there is no need to mute.
7534 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007535 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007536 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307537 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7538 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007539 muteWaitMs = 0;
7540 }
Eric Laurente552edb2014-03-10 17:42:56 -07007541
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007542 bool outputRouted = outputDesc->isRouted();
7543
Eric Laurent79ea9582020-06-11 18:49:24 -07007544 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7545 // output profile or if new device is not supported AND previous device(s) is(are) still
7546 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007547 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307548 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7549 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007550 // restore previous device after evaluating strategy mute state
7551 outputDesc->setDevices(prevDevices);
7552 return muteWaitMs;
7553 }
7554
Eric Laurente552edb2014-03-10 17:42:56 -07007555 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007556 // the requested device is AUDIO_DEVICE_NONE
7557 // OR the requested device is the same as current device
7558 // AND force is not specified
7559 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007560 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007561 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307562 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7563 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7564 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007565 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307566 ALOGV("%s %s setting same device on routed output, force apply volumes",
7567 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007568 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7569 }
Eric Laurente552edb2014-03-10 17:42:56 -07007570 return muteWaitMs;
7571 }
7572
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307573 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7574 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007575
Eric Laurente552edb2014-03-10 17:42:56 -07007576 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007577 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007578 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007579 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007580 PatchBuilder patchBuilder;
7581 patchBuilder.addSource(outputDesc);
7582 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7583 for (const auto &filteredDevice : filteredDevices) {
7584 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007585 }
7586
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007587 // Add half reported latency to delayMs when muteWaitMs is null in order
7588 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007589 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7590 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7591 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007592 }
Eric Laurente552edb2014-03-10 17:42:56 -07007593
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007594 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7595 if (!skipMuteDelay) {
7596 // update stream volumes according to new device
7597 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7598 }
Eric Laurente552edb2014-03-10 17:42:56 -07007599
7600 return muteWaitMs;
7601}
7602
Eric Laurentc75307b2015-03-17 15:29:32 -07007603status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007604 int delayMs,
7605 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007606{
Eric Laurent6a94d692014-05-20 11:18:06 -07007607 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007608 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7609 return INVALID_OPERATION;
7610 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007611 if (patchHandle) {
7612 index = mAudioPatches.indexOfKey(*patchHandle);
7613 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007614 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007615 }
7616 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007617 return INVALID_OPERATION;
7618 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007619 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007620 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007621 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007622 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007623 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007624 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007625 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007626 return status;
7627}
7628
7629status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007630 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007631 bool force,
7632 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007633{
7634 status_t status = NO_ERROR;
7635
Eric Laurent1f2f2232014-06-02 12:01:23 -07007636 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007637 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7638 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007639
François Gaffie11d30102018-11-02 16:09:09 +01007640 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007641 PatchBuilder patchBuilder;
7642 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007643 // AUDIO_SOURCE_HOTWORD is for internal use only:
7644 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007645 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7646 auto result = usecase;
7647 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7648 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7649 }
7650 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007651 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007652 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007653 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007654 }
7655 }
7656 return status;
7657}
7658
Eric Laurent6a94d692014-05-20 11:18:06 -07007659status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7660 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007661{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007662 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007663 ssize_t index;
7664 if (patchHandle) {
7665 index = mAudioPatches.indexOfKey(*patchHandle);
7666 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007667 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007668 }
7669 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007670 return INVALID_OPERATION;
7671 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007672 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007673 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007674 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007675 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007676 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007677 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007678 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007679 return status;
7680}
7681
François Gaffie11d30102018-11-02 16:09:09 +01007682sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007683 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007684 audio_format_t& format,
7685 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007686 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007687{
7688 // Choose an input profile based on the requested capture parameters: select the first available
7689 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007690 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007691 //
7692 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7693 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007694
Atneya Nair0f0a8032022-12-12 16:20:12 -08007695 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7696 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7697 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7698
7699 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007700
jiabin2fd710d2022-05-02 23:20:22 +00007701 for (;;) {
7702 sp<IOProfile> firstInexact = nullptr;
7703 uint32_t updatedSamplingRate = 0;
7704 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7705 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7706 for (const auto& hwModule : mHwModules) {
7707 for (const auto& profile : hwModule->getInputProfiles()) {
7708 // profile->log();
7709 //updatedFormat = format;
7710 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7711 &samplingRate /*updatedSamplingRate*/,
7712 format,
7713 &format, /*updatedFormat*/
7714 channelMask,
7715 &channelMask /*updatedChannelMask*/,
7716 // FIXME ugly cast
7717 (audio_output_flags_t) flags,
7718 true /*exactMatchRequiredForInputFlags*/)) {
7719 return profile;
7720 }
7721 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7722 samplingRate,
7723 &updatedSamplingRate,
7724 format,
7725 &updatedFormat,
7726 channelMask,
7727 &updatedChannelMask,
7728 // FIXME ugly cast
7729 (audio_output_flags_t) flags,
7730 false /*exactMatchRequiredForInputFlags*/)) {
7731 firstInexact = profile;
7732 }
7733 }
7734 }
7735
7736 if (firstInexact != nullptr) {
7737 samplingRate = updatedSamplingRate;
7738 format = updatedFormat;
7739 channelMask = updatedChannelMask;
7740 return firstInexact;
7741 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7742 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7743 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7744 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7745 flags = AUDIO_INPUT_FLAG_NONE;
7746 } else { // fail
7747 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7748 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7749 samplingRate, format, channelMask, oriFlags);
7750 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007751 }
7752 }
jiabin2fd710d2022-05-02 23:20:22 +00007753
7754 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007755}
7756
François Gaffieaaac0fd2018-11-22 17:56:39 +01007757float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7758 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007759 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007760 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007761{
jiabin9a3361e2019-10-01 09:38:30 -07007762 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007763
7764 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7765 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7766 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7767 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007768 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7769 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7770 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7771 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7772 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007773 // Verify that the current volume source is not the ringer volume to prevent recursively
7774 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7775 // to the same volume group.
7776 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007777 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7778 mOutputs.isActive(ringVolumeSrc, 0)) {
7779 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007780 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007781 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007782 }
7783
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007784 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007785 if ((volumeSource != callVolumeSrc && (isInCall() ||
7786 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007787 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007788 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7789 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007790 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7791 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7792 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007793 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007794 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007795 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007796 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007797 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007798 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007799 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7800 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7801 // programmatically muted.
7802 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7803 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7804 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007805 bool exemptFromCapping =
7806 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7807 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007808 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7809 volumeSource, volumeDb);
7810 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007811 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7812 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7813 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007814 }
7815 }
Eric Laurente552edb2014-03-10 17:42:56 -07007816 // if a headset is connected, apply the following rules to ring tones and notifications
7817 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007818 // - always attenuate notifications volume by 6dB
7819 // - attenuate ring tones volume by 6dB unless music is not playing and
7820 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007821 // - if music is playing, always limit the volume to current music volume,
7822 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007823 if (!Intersection(deviceTypes,
7824 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7825 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007826 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7827 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007828 ((volumeSource == alarmVolumeSrc ||
7829 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007830 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7831 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7832 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007833 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7834 curves.canBeMuted()) {
7835
Eric Laurente552edb2014-03-10 17:42:56 -07007836 // when the phone is ringing we must consider that music could have been paused just before
7837 // by the music application and behave as if music was active if the last music track was
7838 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007839 // Verify that the current volume source is not the music volume to prevent recursively
7840 // calling to compute volume. This could happen in cases where music and
7841 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7842 if (volumeSource != musicVolumeSrc &&
7843 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7844 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007845 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007846 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007847 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7848 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007849 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007850 float musicVolDb = computeVolume(musicCurves,
7851 musicVolumeSrc,
7852 musicCurves.getVolumeIndex(musicDevice),
7853 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007854 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7855 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7856 if (volumeDb > minVolDb) {
7857 volumeDb = minVolDb;
7858 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007859 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007860 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7861 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7862 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007863 // on A2DP, also ensure notification volume is not too low compared to media when
7864 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007865 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007866 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007867 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7868 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007869 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7870 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007871 }
7872 }
jiabin9a3361e2019-10-01 09:38:30 -07007873 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007874 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007875 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007876 }
7877 }
7878
François Gaffie43c73442018-11-08 08:21:55 +01007879 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007880}
7881
Eric Laurent3839bc02018-07-10 18:33:34 -07007882int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007883 VolumeSource fromVolumeSource,
7884 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007885{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007886 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007887 return srcIndex;
7888 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007889 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7890 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007891 float minSrc = (float)srcCurves.getVolumeIndexMin();
7892 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7893 float minDst = (float)dstCurves.getVolumeIndexMin();
7894 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007895
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007896 // preserve mute request or correct range
7897 if (srcIndex < minSrc) {
7898 if (srcIndex == 0) {
7899 return 0;
7900 }
7901 srcIndex = minSrc;
7902 } else if (srcIndex > maxSrc) {
7903 srcIndex = maxSrc;
7904 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007905 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7906}
7907
François Gaffieaaac0fd2018-11-22 17:56:39 +01007908status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7909 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007910 int index,
7911 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007912 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007913 int delayMs,
7914 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007915{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007916 // do not change actual attributes volume if the attributes is muted
7917 if (outputDesc->isMuted(volumeSource)) {
7918 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7919 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007920 return NO_ERROR;
7921 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007922
Eric Laurentae6e88c2024-01-10 14:42:57 +01007923 bool isVoiceVolSrc;
7924 bool isBtScoVolSrc;
7925 if (!isVolumeConsistentForCalls(
7926 volumeSource, deviceTypes, isVoiceVolSrc, isBtScoVolSrc, __func__)) {
Eric Laurent571ef962020-07-24 11:43:48 -07007927 // Do not return an error here as AudioService will always set both voice call
Eric Laurentae6e88c2024-01-10 14:42:57 +01007928 // and Bluetooth SCO volumes due to stream aliasing.
Eric Laurent571ef962020-07-24 11:43:48 -07007929 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007930 }
Eric Laurentae6e88c2024-01-10 14:42:57 +01007931
jiabin9a3361e2019-10-01 09:38:30 -07007932 if (deviceTypes.empty()) {
7933 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007934 index = curves.getVolumeIndex(deviceTypes);
7935 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7936 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007937 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007938
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007939 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7940 ALOGE("invalid volume index range");
7941 return BAD_VALUE;
7942 }
7943
jiabin9a3361e2019-10-01 09:38:30 -07007944 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7945 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007946 // Force VoIP volume to max for bluetooth SCO device except if muted
7947 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007948 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007949 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007950 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007951 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007952 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7953 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007954
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007955 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurentae6e88c2024-01-10 14:42:57 +01007956 setVoiceVolume(index, curves, isVoiceVolSrc, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007957 }
Eric Laurente552edb2014-03-10 17:42:56 -07007958 return NO_ERROR;
7959}
7960
Eric Laurentae6e88c2024-01-10 14:42:57 +01007961void AudioPolicyManager::setVoiceVolume(
7962 int index, IVolumeCurves &curves, bool isVoiceVolSrc, int delayMs) {
7963 float voiceVolume;
7964 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed
7965 // by the headset
7966 if (isVoiceVolSrc) {
7967 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
7968 } else {
7969 voiceVolume = index == 0 ? 0.0 : 1.0;
7970 }
7971 if (voiceVolume != mLastVoiceVolume) {
7972 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7973 mLastVoiceVolume = voiceVolume;
7974 }
7975}
7976
7977bool AudioPolicyManager::isVolumeConsistentForCalls(VolumeSource volumeSource,
7978 const DeviceTypeSet& deviceTypes,
7979 bool& isVoiceVolSrc,
7980 bool& isBtScoVolSrc,
7981 const char* caller) {
7982 const VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7983 const VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7984 const bool isScoRequested = isScoRequestedForComm();
7985 const bool isHAUsed = isHearingAidUsedForComm();
7986
7987 isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7988 isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
7989
7990 if ((callVolSrc != btScoVolSrc) &&
7991 ((isVoiceVolSrc && isScoRequested) ||
7992 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7993 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
7994 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", caller,
7995 volumeSource, isScoRequested ? " " : " not ");
7996 return false;
7997 }
7998 return true;
7999}
8000
Eric Laurentc75307b2015-03-17 15:29:32 -07008001void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008002 const DeviceTypeSet& deviceTypes,
8003 int delayMs,
8004 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07008005{
jiabincd510522020-01-22 09:40:55 -08008006 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01008007 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
8008 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
8009 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07008010 curves.getVolumeIndex(deviceTypes),
8011 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07008012 }
8013}
8014
François Gaffiec005e562018-11-06 15:04:49 +01008015void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
8016 bool on,
8017 const sp<AudioOutputDescriptor>& outputDesc,
8018 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008019 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008020{
François Gaffieaaac0fd2018-11-22 17:56:39 +01008021 std::vector<VolumeSource> sourcesToMute;
8022 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
8023 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
8024 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008025 VolumeSource source = toVolumeSource(attributes, false);
8026 if ((source != VOLUME_SOURCE_NONE) &&
8027 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
8028 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008029 sourcesToMute.push_back(source);
8030 }
Eric Laurente552edb2014-03-10 17:42:56 -07008031 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008032 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07008033 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01008034 }
8035
Eric Laurente552edb2014-03-10 17:42:56 -07008036}
8037
François Gaffieaaac0fd2018-11-22 17:56:39 +01008038void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8039 bool on,
8040 const sp<AudioOutputDescriptor>& outputDesc,
8041 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008042 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008043{
jiabin9a3361e2019-10-01 09:38:30 -07008044 if (deviceTypes.empty()) {
8045 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008046 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008047 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008048 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008049 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008050 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008051 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008052 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8053 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008054 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008055 }
8056 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008057 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8058 // ignored
8059 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008060 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008061 if (!outputDesc->isMuted(volumeSource)) {
8062 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008063 return;
8064 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008065 if (outputDesc->decMuteCount(volumeSource) == 0) {
8066 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008067 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008068 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008069 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008070 delayMs);
8071 }
8072 }
8073}
8074
François Gaffie53615e22015-03-19 09:24:12 +01008075bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8076{
François Gaffiec005e562018-11-06 15:04:49 +01008077 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008078 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8079 return true;
8080 }
8081
8082 // has known usage?
8083 switch (paa->usage) {
8084 case AUDIO_USAGE_UNKNOWN:
8085 case AUDIO_USAGE_MEDIA:
8086 case AUDIO_USAGE_VOICE_COMMUNICATION:
8087 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8088 case AUDIO_USAGE_ALARM:
8089 case AUDIO_USAGE_NOTIFICATION:
8090 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8091 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8092 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8093 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8094 case AUDIO_USAGE_NOTIFICATION_EVENT:
8095 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8096 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8097 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8098 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008099 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008100 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008101 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008102 case AUDIO_USAGE_EMERGENCY:
8103 case AUDIO_USAGE_SAFETY:
8104 case AUDIO_USAGE_VEHICLE_STATUS:
8105 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008106 break;
8107 default:
8108 return false;
8109 }
8110 return true;
8111}
8112
François Gaffie2110e042015-03-24 08:41:51 +01008113audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8114{
8115 return mEngine->getForceUse(usage);
8116}
8117
Eric Laurent96d1dda2022-03-14 17:14:19 +01008118bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008119 return isStateInCall(mEngine->getPhoneState());
8120}
8121
Eric Laurent96d1dda2022-03-14 17:14:19 +01008122bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008123 return is_state_in_call(state);
8124}
8125
Eric Laurentf9cccec2022-11-16 19:12:00 +01008126bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008127 audio_mode_t mode = mEngine->getPhoneState();
8128 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008129 || (mode == AUDIO_MODE_CALL_SCREEN)
8130 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008131}
8132
Eric Laurentf9cccec2022-11-16 19:12:00 +01008133bool AudioPolicyManager::isInCallOrScreening() const {
8134 audio_mode_t mode = mEngine->getPhoneState();
8135 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8136}
8137
Eric Laurentd60560a2015-04-10 11:31:20 -07008138void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8139{
8140 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008141 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008142 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008143 sourceDesc->sinkDevice()->equals(deviceDesc))
8144 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008145 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008146 }
8147 }
8148
8149 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8150 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8151 bool release = false;
8152 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8153 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8154 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8155 source->ext.device.type == deviceDesc->type()) {
8156 release = true;
8157 }
8158 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008159 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008160 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8161 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8162 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008163 sink->ext.device.type == deviceDesc->type() &&
8164 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8165 || strncmp(sink->ext.device.address, address,
8166 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008167 release = true;
8168 }
8169 }
8170 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008171 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8172 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008173 }
8174 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008175
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008176 mInputs.clearSessionRoutesForDevice(deviceDesc);
8177
Francois Gaffie716e1432019-01-14 16:58:59 +01008178 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008179}
8180
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008181void AudioPolicyManager::modifySurroundFormats(
8182 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008183 std::unordered_set<audio_format_t> enforcedSurround(
8184 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008185 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008186 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008187 allSurround.insert(pair.first);
8188 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8189 }
Phil Burk09bc4612016-02-24 15:58:15 -08008190
8191 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8192 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008193 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008194 // This is the resulting set of formats depending on the surround mode:
8195 // 'all surround' = allSurround
8196 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8197 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8198 // 'manual surround' = mManualSurroundFormats
8199 // AUTO: formats v 'enforced surround'
8200 // ALWAYS: formats v 'all surround' v 'enforced surround'
8201 // NEVER: formats ^ 'non-surround'
8202 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008203
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008204 std::unordered_set<audio_format_t> formatSet;
8205 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8206 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008207 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008208 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008209 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008210 formatSet.insert(*formatIter);
8211 }
8212 }
8213 } else {
8214 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8215 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008216 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008217
jiabin81772902018-04-02 17:52:27 -07008218 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008219 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008220 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8221 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8222 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008223 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008224 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8225 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8226 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008227 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008228 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008229 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008230 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008231 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008232 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008233}
8234
jiabin06e4bab2019-07-29 10:13:34 -07008235void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8236 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008237 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8238 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8239
8240 // If NEVER, then remove support for channelMasks > stereo.
8241 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008242 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8243 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008244 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008245 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008246 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008247 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008248 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008249 }
8250 }
jiabin81772902018-04-02 17:52:27 -07008251 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8252 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8253 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008254 bool supports5dot1 = false;
8255 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008256 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008257 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8258 supports5dot1 = true;
8259 break;
8260 }
8261 }
8262 // If not then add 5.1 support.
8263 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008264 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008265 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008266 }
Phil Burk09bc4612016-02-24 15:58:15 -08008267 }
8268}
8269
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008270void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008271 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008272 const sp<IOProfile>& profile) {
8273 if (!profile->hasDynamicAudioProfile()) {
8274 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008275 }
François Gaffie112b0af2015-11-19 16:13:25 +01008276
jiabin12537fc2023-10-12 17:56:08 +00008277 audio_port_v7 devicePort;
8278 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008279
jiabin12537fc2023-10-12 17:56:08 +00008280 audio_port_v7 mixPort;
8281 profile->toAudioPort(&mixPort);
8282 mixPort.ext.mix.handle = ioHandle;
8283
8284 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8285 if (status != NO_ERROR) {
8286 ALOGE("%s failed to query the attributes of the mix port", __func__);
8287 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008288 }
jiabin12537fc2023-10-12 17:56:08 +00008289
8290 std::set<audio_format_t> supportedFormats;
8291 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8292 supportedFormats.insert(mixPort.audio_profiles[i].format);
8293 }
8294 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8295 mReportedFormatsMap[devDesc] = formats;
8296
8297 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8298 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8299 modifySurroundFormats(devDesc, &formats);
8300 size_t modifiedNumProfiles = 0;
8301 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8302 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8303 formats.end()) {
8304 // Skip the format that is not present after modifying surround formats.
8305 continue;
8306 }
8307 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8308 sizeof(struct audio_profile));
8309 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8310 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8311 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8312 modifySurroundChannelMasks(&channels);
8313 std::copy(channels.begin(), channels.end(),
8314 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8315 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8316 }
8317 mixPort.num_audio_profiles = modifiedNumProfiles;
8318 }
8319 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008320}
Eric Laurentd60560a2015-04-10 11:31:20 -07008321
Mikhail Naganovdc769682018-05-04 15:34:08 -07008322status_t AudioPolicyManager::installPatch(const char *caller,
8323 audio_patch_handle_t *patchHandle,
8324 AudioIODescriptorInterface *ioDescriptor,
8325 const struct audio_patch *patch,
8326 int delayMs)
8327{
8328 ssize_t index = mAudioPatches.indexOfKey(
8329 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8330 *patchHandle : ioDescriptor->getPatchHandle());
8331 sp<AudioPatch> patchDesc;
8332 status_t status = installPatch(
8333 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8334 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008335 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008336 }
8337 return status;
8338}
8339
8340status_t AudioPolicyManager::installPatch(const char *caller,
8341 ssize_t index,
8342 audio_patch_handle_t *patchHandle,
8343 const struct audio_patch *patch,
8344 int delayMs,
8345 uid_t uid,
8346 sp<AudioPatch> *patchDescPtr)
8347{
8348 sp<AudioPatch> patchDesc;
8349 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8350 if (index >= 0) {
8351 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008352 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008353 }
8354
8355 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8356 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8357 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8358 if (status == NO_ERROR) {
8359 if (index < 0) {
8360 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008361 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008362 } else {
8363 patchDesc->mPatch = *patch;
8364 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008365 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008366 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008367 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008368 }
8369 nextAudioPortGeneration();
8370 mpClientInterface->onAudioPatchListUpdate();
8371 }
8372 if (patchDescPtr) *patchDescPtr = patchDesc;
8373 return status;
8374}
8375
jiabinbce0c1d2020-10-05 11:20:18 -07008376bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8377{
8378 const TrackClientVector activeClients = output->getActiveClients();
8379 if (activeClients.empty()) {
8380 return true;
8381 }
8382 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8383 if (index < 0) {
8384 ALOGE("%s, no audio patch found while there are active clients on output %d",
8385 __func__, output->getId());
8386 return false;
8387 }
8388 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8389 DeviceVector routedDevices;
8390 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8391 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8392 patchDesc->mPatch.sinks[i].id);
8393 if (device == nullptr) {
8394 ALOGE("%s, no audio device found with id(%d)",
8395 __func__, patchDesc->mPatch.sinks[i].id);
8396 return false;
8397 }
8398 routedDevices.add(device);
8399 }
8400 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008401 if (client->isInvalid()) {
8402 // No need to take care about invalidated clients.
8403 continue;
8404 }
jiabinbce0c1d2020-10-05 11:20:18 -07008405 sp<DeviceDescriptor> preferredDevice =
8406 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8407 if (mEngine->getOutputDevicesForAttributes(
8408 client->attributes(), preferredDevice, false) == routedDevices) {
8409 return false;
8410 }
8411 }
8412 return true;
8413}
8414
8415sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008416 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008417 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8418 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008419{
8420 for (const auto& device : devices) {
8421 // TODO: This should be checking if the profile supports the device combo.
8422 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008423 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8424 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008425 return nullptr;
8426 }
8427 }
8428 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8429 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008430 status_t status = desc->open(halConfig, mixerConfig, devices,
8431 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008432 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008433 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008434 return nullptr;
8435 }
jiabin14b50cc2023-12-13 19:01:52 +00008436 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8437 auto portConfig = desc->getConfig();
8438 for (const auto& device : devices) {
8439 device->setPreferredConfig(&portConfig);
8440 }
8441 }
jiabinbce0c1d2020-10-05 11:20:18 -07008442
8443 // Here is where the out_set_parameters() for card & device gets called
8444 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8445 const audio_devices_t deviceType = device->type();
8446 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008447 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008448 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8449 mpClientInterface->setParameters(output, String8(param));
8450 free(param);
8451 }
jiabin12537fc2023-10-12 17:56:08 +00008452 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008453 if (!profile->hasValidAudioProfile()) {
8454 ALOGW("%s() missing param", __func__);
8455 desc->close();
8456 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008457 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8458 // Reopen the output with the best audio profile picked by APM when the profile supports
8459 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008460 desc->close();
8461 output = AUDIO_IO_HANDLE_NONE;
8462 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8463 profile->pickAudioProfile(
8464 config.sample_rate, config.channel_mask, config.format);
8465 config.offload_info.sample_rate = config.sample_rate;
8466 config.offload_info.channel_mask = config.channel_mask;
8467 config.offload_info.format = config.format;
8468
jiabina84c3d32022-12-02 18:59:55 +00008469 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008470 if (status != NO_ERROR) {
8471 return nullptr;
8472 }
8473 }
8474
8475 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008476
baek.kim -61c20122022-07-27 10:05:32 +00008477 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8478 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8479
jiabinbce0c1d2020-10-05 11:20:18 -07008480 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8481 sp<AudioPolicyMix> policyMix;
8482 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8483 policyMix->setOutput(desc);
8484 desc->mPolicyMix = policyMix;
8485 } else {
8486 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008487 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008488 }
8489
baek.kim -61c20122022-07-27 10:05:32 +00008490 } else if (hasPrimaryOutput() && speaker != nullptr
8491 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008492 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8493 // no duplicated output for:
8494 // - direct outputs
8495 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008496 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008497 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8498
8499 //TODO: configure audio effect output stage here
8500
8501 // open a duplicating output thread for the new output and the primary output
8502 sp<SwAudioOutputDescriptor> dupOutputDesc =
8503 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8504 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8505 if (status == NO_ERROR) {
8506 // add duplicated output descriptor
8507 addOutput(duplicatedOutput, dupOutputDesc);
8508 } else {
8509 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8510 mPrimaryOutput->mIoHandle, output);
8511 desc->close();
8512 removeOutput(output);
8513 nextAudioPortGeneration();
8514 return nullptr;
8515 }
8516 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008517 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8518 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8519 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008520 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008521 }
jiabinbce0c1d2020-10-05 11:20:18 -07008522 return desc;
8523}
8524
jiabinf1c73972022-04-14 16:28:52 -07008525status_t AudioPolicyManager::getDevicesForAttributes(
8526 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8527 // Devices are determined in the following precedence:
8528 //
8529 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8530 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8531 //
8532 // If no such dynamic policy then
8533 // 2) Devices containing an active client using setPreferredDevice
8534 // with same strategy as the attributes.
8535 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8536 //
8537 // If no corresponding active client with setPreferredDevice then
8538 // 3) Devices associated with the strategy determined by the attributes
8539 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8540 //
8541 // See related getOutputForAttrInt().
8542
8543 // check dynamic policies but only for primary descriptors (secondary not used for audible
8544 // audio routing, only used for duplication for playback capture)
8545 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008546 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008547 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008548 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8549 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8550 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008551 if (status != OK) {
8552 return status;
8553 }
8554
8555 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8556 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8557 // as they are unaffected by device/stream volume
8558 // (per SwAudioOutputDescriptor::isFixedVolume()).
8559 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8560 ) {
8561 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8562 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8563 devices.add(deviceDesc);
8564 } else {
8565 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8566 // which selects setPreferredDevice if active. This means forVolume call
8567 // will take an active setPreferredDevice, if such exists.
8568
8569 devices = mEngine->getOutputDevicesForAttributes(
8570 attr, nullptr /* preferredDevice */, false /* fromCache */);
8571 }
8572
8573 if (forVolume) {
8574 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8575 // for single volume control in AudioService (such relationship should exist if
8576 // SPEAKER_SAFE is present).
8577 //
8578 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8579 DeviceVector speakerSafeDevices =
8580 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8581 if (!speakerSafeDevices.isEmpty()) {
8582 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8583 devices.remove(speakerSafeDevices);
8584 }
8585 }
8586
8587 return NO_ERROR;
8588}
8589
8590status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8591 AudioProfileVector& audioProfiles,
8592 uint32_t flags,
8593 bool isInput) {
8594 for (const auto& hwModule : mHwModules) {
8595 // the MSD module checks for different conditions
8596 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8597 continue;
8598 }
8599 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8600 : hwModule->getOutputProfiles();
8601 for (const auto& profile : ioProfiles) {
8602 if (!profile->areAllDevicesSupported(devices) ||
8603 !profile->isCompatibleProfileForFlags(
8604 flags, false /*exactMatchRequiredForInputFlags*/)) {
8605 continue;
8606 }
8607 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8608 }
8609 }
8610
8611 if (!isInput) {
8612 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8613 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8614 if (msdModule != nullptr) {
8615 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8616 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8617 for (const auto &profile: msdModule->getOutputProfiles()) {
8618 if (!profile->asAudioPort()->isDirectOutput()) {
8619 continue;
8620 }
8621 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8622 }
8623 } else {
8624 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8625 }
8626 }
8627 }
8628
8629 return NO_ERROR;
8630}
8631
jiabin3ff8d7d2022-12-13 06:27:44 +00008632sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8633 const audio_config_t *config,
8634 audio_output_flags_t flags,
8635 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008636 closeOutput(outputDesc->mIoHandle);
8637 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8638 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8639 if (preferredOutput == nullptr) {
8640 ALOGE("%s failed to reopen output device=%d, caller=%s",
8641 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008642 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008643 return preferredOutput;
8644}
8645
8646void AudioPolicyManager::reopenOutputsWithDevices(
8647 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8648 for (const auto& [output, devices] : outputsToReopen) {
8649 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8650 closeOutput(output);
8651 openOutputWithProfileAndDevice(desc->mProfile, devices);
8652 }
jiabina84c3d32022-12-02 18:59:55 +00008653}
8654
jiabinc44b3462022-12-08 12:52:31 -08008655PortHandleVector AudioPolicyManager::getClientsForStream(
8656 audio_stream_type_t streamType) const {
8657 PortHandleVector clients;
8658 for (size_t i = 0; i < mOutputs.size(); ++i) {
8659 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8660 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8661 }
8662 return clients;
8663}
8664
8665void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8666 PortHandleVector clients;
8667 for (auto stream : streams) {
8668 PortHandleVector clientsForStream = getClientsForStream(stream);
8669 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8670 }
8671 mpClientInterface->invalidateTracks(clients);
8672}
8673
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008674} // namespace android