blob: 81369e222e953f3a849893f73aa7c486b23d8a27 [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
Andy Hung9dd1a5b2022-05-10 15:39:39 -07001631 && canBeSpatializedInt(attr, config, devices.toTypeAddrVector())) {
Eric Laurentb0a7bc92022-04-05 15:06:08 +02001632 *isSpatialized = true;
Eric Laurentfa0f6742021-08-17 18:39:44 +02001633 return mSpatializerOutput->mIoHandle;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02001634 }
1635
Eric Laurentc529cf62020-04-17 18:19:10 -07001636 audio_config_t directConfig = *config;
1637 directConfig.channel_mask = channelMask;
1638 status_t status = openDirectOutput(stream, session, &directConfig, *flags, devices, &output);
1639 if (status != NAME_NOT_FOUND) {
Eric Laurente552edb2014-03-10 17:42:56 -07001640 return output;
1641 }
1642
Eric Laurent14cbfca2016-03-17 09:42:16 -07001643 // A request for HW A/V sync cannot fallback to a mixed output because time
1644 // stamps are embedded in audio data
Phil Burk2d059932018-02-15 15:55:11 -08001645 if ((*flags & (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ)) != 0) {
Eric Laurent14cbfca2016-03-17 09:42:16 -07001646 return AUDIO_IO_HANDLE_NONE;
1647 }
Pierre Couillaude73496b2023-03-06 16:19:05 +00001648 // A request for Tuner cannot fallback to a mixed output
1649 if ((directConfig.offload_info.content_id || directConfig.offload_info.sync_id)) {
1650 return AUDIO_IO_HANDLE_NONE;
1651 }
Eric Laurent14cbfca2016-03-17 09:42:16 -07001652
Eric Laurente552edb2014-03-10 17:42:56 -07001653 // ignoring channel mask due to downmix capability in mixer
1654
1655 // open a non direct output
1656
1657 // for non direct outputs, only PCM is supported
Eric Laurentfe231122017-11-17 17:48:06 -08001658 if (audio_is_linear_pcm(config->format)) {
Eric Laurente552edb2014-03-10 17:42:56 -07001659 // get which output is suitable for the specified stream. The actual
1660 // routing change will happen when startOutput() will be called
François Gaffie11d30102018-11-02 16:09:09 +01001661 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabina84c3d32022-12-02 18:59:55 +00001662 if (prefMixerConfigInfo != nullptr) {
1663 for (audio_io_handle_t outputHandle : outputs) {
1664 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(outputHandle);
1665 if (outputDesc->mProfile == prefMixerConfigInfo->getProfile()) {
1666 output = outputHandle;
1667 break;
1668 }
1669 }
1670 if (output == AUDIO_IO_HANDLE_NONE) {
1671 // No output open with the preferred profile. Open a new one.
1672 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
1673 config.channel_mask = prefMixerConfigInfo->getConfigBase().channel_mask;
1674 config.sample_rate = prefMixerConfigInfo->getConfigBase().sample_rate;
1675 config.format = prefMixerConfigInfo->getConfigBase().format;
1676 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
1677 prefMixerConfigInfo->getProfile(), devices, nullptr /*mixerConfig*/,
1678 &config, prefMixerConfigInfo->getFlags());
1679 if (preferredOutput == nullptr) {
1680 ALOGE("%s failed to open output with preferred mixer config", __func__);
1681 } else {
1682 output = preferredOutput->mIoHandle;
1683 }
1684 }
1685 } else {
1686 // at this stage we should ignore the DIRECT flag as no direct output could be
1687 // found earlier
1688 *flags = (audio_output_flags_t) (*flags & ~AUDIO_OUTPUT_FLAG_DIRECT);
1689 output = selectOutput(
1690 outputs, *flags, config->format, channelMask, config->sample_rate, session);
1691 }
Eric Laurente552edb2014-03-10 17:42:56 -07001692 }
François Gaffie11d30102018-11-02 16:09:09 +01001693 ALOGW_IF((output == 0), "getOutputForDevices() could not find output for stream %d, "
Glenn Kasten49f36ba2017-12-06 13:02:02 -08001694 "sampling rate %d, format %#x, channels %#x, flags %#x",
jiabine375d412019-02-26 12:54:53 -08001695 stream, config->sample_rate, config->format, channelMask, *flags);
Eric Laurente552edb2014-03-10 17:42:56 -07001696
Eric Laurente552edb2014-03-10 17:42:56 -07001697 return output;
1698}
1699
Mikhail Naganovf02f3672018-11-09 12:44:16 -08001700sp<DeviceDescriptor> AudioPolicyManager::getMsdAudioInDevice() const {
François Gaffie11d30102018-11-02 16:09:09 +01001701 auto msdInDevices = mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1702 mAvailableInputDevices);
1703 return msdInDevices.isEmpty()? nullptr : msdInDevices.itemAt(0);
1704}
1705
1706DeviceVector AudioPolicyManager::getMsdAudioOutDevices() const {
1707 return mHwModules.getAvailableDevicesFromModuleName(AUDIO_HARDWARE_MODULE_ID_MSD,
1708 mAvailableOutputDevices);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001709}
1710
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001711const AudioPatchCollection AudioPolicyManager::getMsdOutputPatches() const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001712 AudioPatchCollection msdPatches;
Mikhail Naganov86112352018-10-04 09:02:49 -07001713 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1714 if (msdModule != 0) {
1715 for (size_t i = 0; i < mAudioPatches.size(); ++i) {
1716 sp<AudioPatch> patch = mAudioPatches.valueAt(i);
1717 for (size_t j = 0; j < patch->mPatch.num_sources; ++j) {
1718 const struct audio_port_config *source = &patch->mPatch.sources[j];
1719 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
1720 source->ext.device.hw_module == msdModule->getHandle()) {
François Gaffieafd4cea2019-11-18 15:50:22 +01001721 msdPatches.addAudioPatch(patch->getHandle(), patch);
Mikhail Naganov86112352018-10-04 09:02:49 -07001722 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001723 }
1724 }
1725 }
1726 return msdPatches;
1727}
1728
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02001729bool AudioPolicyManager::isMsdPatch(const audio_patch_handle_t &handle) const {
1730 ssize_t index = mAudioPatches.indexOfKey(handle);
1731 if (index < 0) {
1732 return false;
1733 }
1734 const sp<AudioPatch> patch = mAudioPatches.valueAt(index);
1735 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1736 if (msdModule == nullptr) {
1737 return false;
1738 }
1739 const struct audio_port_config *sink = &patch->mPatch.sinks[0];
1740 if (getMsdAudioOutDevices().contains(mAvailableOutputDevices.getDeviceFromId(sink->id))) {
1741 return true;
1742 }
1743 index = getMsdOutputPatches().indexOfKey(handle);
1744 if (index < 0) {
1745 return false;
1746 }
1747 return true;
1748}
1749
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001750status_t AudioPolicyManager::getMsdProfiles(bool hwAvSync,
1751 const InputProfileCollection &inputProfiles,
1752 const OutputProfileCollection &outputProfiles,
1753 const sp<DeviceDescriptor> &sourceDevice,
1754 const sp<DeviceDescriptor> &sinkDevice,
1755 AudioProfileVector& sourceProfiles,
1756 AudioProfileVector& sinkProfiles) const {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001757 if (inputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001758 ALOGE("%s() no input profiles for source module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001759 return NO_INIT;
1760 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001761 if (outputProfiles.isEmpty()) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001762 ALOGE("%s() no output profiles for sink module", __func__);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001763 return NO_INIT;
1764 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001765 for (const auto &inProfile : inputProfiles) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001766 if (hwAvSync == ((inProfile->getFlags() & AUDIO_INPUT_FLAG_HW_AV_SYNC) != 0) &&
1767 inProfile->supportsDevice(sourceDevice)) {
1768 appendAudioProfiles(sourceProfiles, inProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001769 }
1770 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001771 for (const auto &outProfile : outputProfiles) {
Michael Chan6fb34492020-12-08 15:44:49 +11001772 if (hwAvSync == ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_HW_AV_SYNC) != 0) &&
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001773 outProfile->supportsDevice(sinkDevice)) {
1774 appendAudioProfiles(sinkProfiles, outProfile->getAudioProfiles());
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001775 }
1776 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001777 return NO_ERROR;
1778}
1779
1780status_t AudioPolicyManager::getBestMsdConfig(bool hwAvSync,
1781 const AudioProfileVector &sourceProfiles, const AudioProfileVector &sinkProfiles,
1782 audio_port_config *sourceConfig, audio_port_config *sinkConfig) const
1783{
Dean Wheatley16809da2022-12-09 14:55:46 +11001784 // Compressed formats for MSD module, ordered from most preferred to least preferred.
1785 static const std::vector<audio_format_t> formatsOrder = {{
1786 AUDIO_FORMAT_IEC60958, AUDIO_FORMAT_MAT_2_1, AUDIO_FORMAT_MAT_2_0, AUDIO_FORMAT_E_AC3,
Dean Wheatley0f27c602023-08-23 13:57:21 +10001787 AUDIO_FORMAT_AC3, AUDIO_FORMAT_PCM_FLOAT, AUDIO_FORMAT_PCM_32_BIT,
1788 AUDIO_FORMAT_PCM_8_24_BIT, AUDIO_FORMAT_PCM_24_BIT_PACKED, AUDIO_FORMAT_PCM_16_BIT }};
Dean Wheatley16809da2022-12-09 14:55:46 +11001789 static const std::vector<audio_channel_mask_t> channelMasksOrder = [](){
1790 // Channel position masks for MSD module, 3D > 2D > 1D ordering (most preferred to least
1791 // preferred).
1792 std::vector<audio_channel_mask_t> masks = {{
1793 AUDIO_CHANNEL_OUT_3POINT1POINT2, AUDIO_CHANNEL_OUT_3POINT0POINT2,
1794 AUDIO_CHANNEL_OUT_2POINT1POINT2, AUDIO_CHANNEL_OUT_2POINT0POINT2,
1795 AUDIO_CHANNEL_OUT_5POINT1, AUDIO_CHANNEL_OUT_STEREO }};
1796 // insert index masks (higher counts most preferred) as preferred over position masks
1797 for (int i = 1; i <= AUDIO_CHANNEL_COUNT_MAX; i++) {
1798 masks.insert(
1799 masks.begin(), audio_channel_mask_for_index_assignment_from_count(i));
1800 }
1801 return masks;
1802 }();
1803
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001804 struct audio_config_base bestSinkConfig;
Dean Wheatley16809da2022-12-09 14:55:46 +11001805 status_t result = findBestMatchingOutputConfig(sourceProfiles, sinkProfiles, formatsOrder,
1806 channelMasksOrder, true /*preferHigherSamplingRates*/, bestSinkConfig);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001807 if (result != NO_ERROR) {
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001808 ALOGD("%s() no matching config found for sink, hwAvSync: %d",
1809 __func__, hwAvSync);
Greg Kaiser83289652018-07-30 06:13:57 -07001810 return result;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001811 }
1812 sinkConfig->sample_rate = bestSinkConfig.sample_rate;
1813 sinkConfig->channel_mask = bestSinkConfig.channel_mask;
1814 sinkConfig->format = bestSinkConfig.format;
1815 // For encoded streams force direct flag to prevent downstream mixing.
1816 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1817 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_DIRECT);
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001818 if (audio_is_iec61937_compatible(sinkConfig->format)) {
1819 // For formats compatible with IEC61937 encapsulation, assume that
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001820 // the input is IEC61937 framed (for proportional buffer sizing).
Dean Wheatley5c9f0832019-11-21 13:39:31 +11001821 // Add the AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO flag so downstream HAL can distinguish between
1822 // raw and IEC61937 framed streams.
1823 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1824 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_IEC958_NONAUDIO);
1825 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001826 sourceConfig->sample_rate = bestSinkConfig.sample_rate;
1827 // Specify exact channel mask to prevent guessing by bit count in PatchPanel.
Dean Wheatley16809da2022-12-09 14:55:46 +11001828 sourceConfig->channel_mask =
1829 audio_channel_mask_get_representation(bestSinkConfig.channel_mask)
1830 == AUDIO_CHANNEL_REPRESENTATION_INDEX ?
1831 bestSinkConfig.channel_mask : audio_channel_mask_out_to_in(bestSinkConfig.channel_mask);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001832 sourceConfig->format = bestSinkConfig.format;
1833 // Copy input stream directly without any processing (e.g. resampling).
1834 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1835 sourceConfig->flags.input | AUDIO_INPUT_FLAG_DIRECT);
1836 if (hwAvSync) {
1837 sinkConfig->flags.output = static_cast<audio_output_flags_t>(
1838 sinkConfig->flags.output | AUDIO_OUTPUT_FLAG_HW_AV_SYNC);
1839 sourceConfig->flags.input = static_cast<audio_input_flags_t>(
1840 sourceConfig->flags.input | AUDIO_INPUT_FLAG_HW_AV_SYNC);
1841 }
1842 const unsigned int config_mask = AUDIO_PORT_CONFIG_SAMPLE_RATE |
1843 AUDIO_PORT_CONFIG_CHANNEL_MASK | AUDIO_PORT_CONFIG_FORMAT | AUDIO_PORT_CONFIG_FLAGS;
1844 sinkConfig->config_mask |= config_mask;
1845 sourceConfig->config_mask |= config_mask;
1846 return NO_ERROR;
1847}
1848
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001849PatchBuilder AudioPolicyManager::buildMsdPatch(bool msdIsSource,
1850 const sp<DeviceDescriptor> &device) const
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001851{
1852 PatchBuilder patchBuilder;
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001853 sp<HwModule> msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
1854 ALOG_ASSERT(msdModule != nullptr, "MSD module not available");
1855 sp<HwModule> deviceModule = mHwModules.getModuleForDevice(device, AUDIO_FORMAT_DEFAULT);
1856 if (deviceModule == nullptr) {
1857 ALOGE("%s() unable to get module for %s", __func__, device->toString().c_str());
1858 return patchBuilder;
1859 }
1860 const InputProfileCollection inputProfiles = msdIsSource ?
1861 msdModule->getInputProfiles() : deviceModule->getInputProfiles();
1862 const OutputProfileCollection outputProfiles = msdIsSource ?
1863 deviceModule->getOutputProfiles() : msdModule->getOutputProfiles();
1864
1865 const sp<DeviceDescriptor> sourceDevice = msdIsSource ? getMsdAudioInDevice() : device;
1866 const sp<DeviceDescriptor> sinkDevice = msdIsSource ?
1867 device : getMsdAudioOutDevices().itemAt(0);
1868 patchBuilder.addSource(sourceDevice).addSink(sinkDevice);
1869
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001870 audio_port_config sourceConfig = patchBuilder.patch()->sources[0];
1871 audio_port_config sinkConfig = patchBuilder.patch()->sinks[0];
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001872 AudioProfileVector sourceProfiles;
1873 AudioProfileVector sinkProfiles;
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001874 // TODO: Figure out whether MSD module has HW_AV_SYNC flag set in the AP config file.
1875 // For now, we just forcefully try with HwAvSync first.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001876 for (auto hwAvSync : { true, false }) {
1877 if (getMsdProfiles(hwAvSync, inputProfiles, outputProfiles, sourceDevice, sinkDevice,
1878 sourceProfiles, sinkProfiles) != NO_ERROR) {
1879 continue;
1880 }
1881 if (getBestMsdConfig(hwAvSync, sourceProfiles, sinkProfiles, &sourceConfig,
1882 &sinkConfig) == NO_ERROR) {
1883 // Found a matching config. Re-create PatchBuilder with this config.
1884 return (PatchBuilder()).addSource(sourceConfig).addSink(sinkConfig);
1885 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001886 }
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001887 ALOGV("%s() no matching config found. Fall through to default PCM patch"
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001888 " supporting PCM format conversion.", __func__);
1889 return patchBuilder;
1890}
1891
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001892status_t AudioPolicyManager::setMsdOutputPatches(const DeviceVector *outputDevices) {
Michael Chan6fb34492020-12-08 15:44:49 +11001893 DeviceVector devices;
1894 if (outputDevices != nullptr && outputDevices->size() > 0) {
1895 devices.add(*outputDevices);
1896 } else {
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001897 // Use media strategy for unspecified output device. This should only
1898 // occur on checkForDeviceAndOutputChanges(). Device connection events may
1899 // therefore invalidate explicit routing requests.
Michael Chan6fb34492020-12-08 15:44:49 +11001900 devices = mEngine->getOutputDevicesForAttributes(
François Gaffiec005e562018-11-06 15:04:49 +01001901 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
Michael Chan6fb34492020-12-08 15:44:49 +11001902 LOG_ALWAYS_FATAL_IF(devices.isEmpty(), "no output device to set MSD patch");
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001903 }
Michael Chan6fb34492020-12-08 15:44:49 +11001904 std::vector<PatchBuilder> patchesToCreate;
1905 for (auto i = 0u; i < devices.size(); ++i) {
1906 ALOGV("%s() for device %s", __func__, devices[i]->toString().c_str());
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001907 patchesToCreate.push_back(buildMsdPatch(true /*msdIsSource*/, devices[i]));
Michael Chan6fb34492020-12-08 15:44:49 +11001908 }
1909 // Retain only the MSD patches associated with outputDevices request.
1910 // Tear down the others, and create new ones as needed.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001911 AudioPatchCollection patchesToRemove = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001912 for (auto it = patchesToCreate.begin(); it != patchesToCreate.end(); ) {
1913 auto retainedPatch = false;
1914 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1915 if (audio_patches_are_equal(it->patch(), &patchesToRemove[i]->mPatch)) {
1916 patchesToRemove.removeItemsAt(i);
1917 retainedPatch = true;
1918 break;
1919 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001920 }
Michael Chan6fb34492020-12-08 15:44:49 +11001921 if (retainedPatch) {
1922 it = patchesToCreate.erase(it);
1923 continue;
1924 }
1925 ++it;
1926 }
1927 if (patchesToCreate.size() == 0 && patchesToRemove.size() == 0) {
1928 return NO_ERROR;
1929 }
1930 for (auto i = 0u; i < patchesToRemove.size(); ++i) {
1931 auto &currentPatch = patchesToRemove.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01001932 releaseAudioPatch(currentPatch->getHandle(), mUidCached);
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001933 }
Michael Chan6fb34492020-12-08 15:44:49 +11001934 status_t status = NO_ERROR;
1935 for (const auto &p : patchesToCreate) {
1936 auto currStatus = installPatch(__func__, -1 /*index*/, nullptr /*patchHandle*/,
1937 p.patch(), 0 /*delayMs*/, mUidCached, nullptr /*patchDescPtr*/);
1938 char message[256];
1939 snprintf(message, sizeof(message), "%s() %s: creating MSD patch from device:IN_BUS to "
1940 "device:%#x (format:%#x channels:%#x samplerate:%d)", __func__,
1941 currStatus == NO_ERROR ? "Success" : "Error",
1942 p.patch()->sinks[0].ext.device.type, p.patch()->sources[0].format,
1943 p.patch()->sources[0].channel_mask, p.patch()->sources[0].sample_rate);
1944 if (currStatus == NO_ERROR) {
1945 ALOGD("%s", message);
1946 } else {
1947 ALOGE("%s", message);
1948 if (status == NO_ERROR) {
1949 status = currStatus;
1950 }
1951 }
1952 }
Mikhail Naganov15be9d22017-11-08 14:18:13 +11001953 return status;
1954}
1955
Dean Wheatley8bee85a2021-02-10 16:02:23 +11001956void AudioPolicyManager::releaseMsdOutputPatches(const DeviceVector& devices) {
1957 AudioPatchCollection msdPatches = getMsdOutputPatches();
Michael Chan6fb34492020-12-08 15:44:49 +11001958 for (size_t i = 0; i < msdPatches.size(); i++) {
1959 const auto& patch = msdPatches[i];
1960 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1961 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1962 if (sink->type == AUDIO_PORT_TYPE_DEVICE && devices.getDevice(sink->ext.device.type,
1963 String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT) != nullptr) {
1964 releaseAudioPatch(patch->getHandle(), mUidCached);
1965 break;
1966 }
1967 }
1968 }
1969}
1970
Dorin Drimus94d94412022-02-02 09:05:02 +01001971bool AudioPolicyManager::msdHasPatchesToAllDevices(const AudioDeviceTypeAddrVector& devices) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07001972 DeviceVector devicesToCheck =
1973 mConfig->getOutputDevices().getDevicesFromDeviceTypeAddrVec(devices);
Dorin Drimus94d94412022-02-02 09:05:02 +01001974 AudioPatchCollection msdPatches = getMsdOutputPatches();
1975 for (size_t i = 0; i < msdPatches.size(); i++) {
1976 const auto& patch = msdPatches[i];
1977 for (size_t j = 0; j < patch->mPatch.num_sinks; ++j) {
1978 const struct audio_port_config *sink = &patch->mPatch.sinks[j];
1979 if (sink->type == AUDIO_PORT_TYPE_DEVICE) {
1980 const auto& foundDevice = devicesToCheck.getDevice(
1981 sink->ext.device.type, String8(sink->ext.device.address), AUDIO_FORMAT_DEFAULT);
1982 if (foundDevice != nullptr) {
1983 devicesToCheck.remove(foundDevice);
1984 if (devicesToCheck.isEmpty()) {
1985 return true;
1986 }
1987 }
1988 }
1989 }
1990 }
1991 return false;
1992}
1993
Eric Laurente0720872014-03-11 09:30:41 -07001994audio_io_handle_t AudioPolicyManager::selectOutput(const SortedVector<audio_io_handle_t>& outputs,
jiabinebb6af42020-06-09 17:31:17 -07001995 audio_output_flags_t flags,
1996 audio_format_t format,
1997 audio_channel_mask_t channelMask,
1998 uint32_t samplingRate,
1999 audio_session_t sessionId)
Eric Laurente552edb2014-03-10 17:42:56 -07002000{
Eric Laurent16c66dd2019-05-01 17:54:10 -07002001 LOG_ALWAYS_FATAL_IF(!(format == AUDIO_FORMAT_INVALID || audio_is_linear_pcm(format)),
2002 "%s called with format %#x", __func__, format);
2003
jiabinebb6af42020-06-09 17:31:17 -07002004 // Return the output that haptic-generating attached to when 1) session id is specified,
2005 // 2) haptic-generating effect exists for given session id and 3) the output that
2006 // haptic-generating effect attached to is in given outputs.
2007 if (sessionId != AUDIO_SESSION_NONE) {
2008 audio_io_handle_t hapticGeneratingOutput = mEffects.getIoForSession(
2009 sessionId, FX_IID_HAPTICGENERATOR);
2010 if (outputs.indexOf(hapticGeneratingOutput) >= 0) {
2011 return hapticGeneratingOutput;
2012 }
2013 }
2014
Eric Laurent16c66dd2019-05-01 17:54:10 -07002015 // Flags disqualifying an output: the match must happen before calling selectOutput()
2016 static const audio_output_flags_t kExcludedFlags = (audio_output_flags_t)
2017 (AUDIO_OUTPUT_FLAG_HW_AV_SYNC | AUDIO_OUTPUT_FLAG_MMAP_NOIRQ | AUDIO_OUTPUT_FLAG_DIRECT);
2018
2019 // Flags expressing a functional request: must be honored in priority over
2020 // other criteria
2021 static const audio_output_flags_t kFunctionalFlags = (audio_output_flags_t)
2022 (AUDIO_OUTPUT_FLAG_VOIP_RX | AUDIO_OUTPUT_FLAG_INCALL_MUSIC |
Eric Laurente28c66d2022-01-21 13:40:41 +01002023 AUDIO_OUTPUT_FLAG_TTS | AUDIO_OUTPUT_FLAG_DIRECT_PCM | AUDIO_OUTPUT_FLAG_ULTRASOUND |
2024 AUDIO_OUTPUT_FLAG_SPATIALIZER);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002025 // Flags expressing a performance request: have lower priority than serving
2026 // requested sampling rate or channel mask
2027 static const audio_output_flags_t kPerformanceFlags = (audio_output_flags_t)
2028 (AUDIO_OUTPUT_FLAG_FAST | AUDIO_OUTPUT_FLAG_DEEP_BUFFER |
2029 AUDIO_OUTPUT_FLAG_RAW | AUDIO_OUTPUT_FLAG_SYNC);
2030
2031 const audio_output_flags_t functionalFlags =
2032 (audio_output_flags_t)(flags & kFunctionalFlags);
2033 const audio_output_flags_t performanceFlags =
2034 (audio_output_flags_t)(flags & kPerformanceFlags);
2035
2036 audio_io_handle_t bestOutput = (outputs.size() == 0) ? AUDIO_IO_HANDLE_NONE : outputs[0];
2037
Eric Laurente552edb2014-03-10 17:42:56 -07002038 // select one output among several that provide a path to a particular device or set of
François Gaffie11d30102018-11-02 16:09:09 +01002039 // devices (the list was previously build by getOutputsForDevices()).
Eric Laurente552edb2014-03-10 17:42:56 -07002040 // The priority is as follows:
jiabin40573322018-11-08 12:08:02 -08002041 // 1: the output supporting haptic playback when requesting haptic playback
Eric Laurent16c66dd2019-05-01 17:54:10 -07002042 // 2: the output with the highest number of requested functional flags
Carter Hsu199f1892021-10-15 15:47:29 +08002043 // with tiebreak preferring the minimum number of extra functional flags
2044 // (see b/200293124, the incorrect selection of AUDIO_OUTPUT_FLAG_VOIP_RX).
Eric Laurent16c66dd2019-05-01 17:54:10 -07002045 // 3: the output supporting the exact channel mask
2046 // 4: the output with a higher channel count than requested
jiabinb12a6da2022-06-03 20:48:18 +00002047 // 5: the output with the highest sampling rate if the requested sample rate is
2048 // greater than default sampling rate
Eric Laurent16c66dd2019-05-01 17:54:10 -07002049 // 6: the output with the highest number of requested performance flags
2050 // 7: the output with the bit depth the closest to the requested one
2051 // 8: the primary output
2052 // 9: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07002053
Eric Laurent16c66dd2019-05-01 17:54:10 -07002054 // matching criteria values in priority order for best matching output so far
2055 std::vector<uint32_t> bestMatchCriteria(8, 0);
Eric Laurente552edb2014-03-10 17:42:56 -07002056
Eric Laurent16c66dd2019-05-01 17:54:10 -07002057 const uint32_t channelCount = audio_channel_count_from_out_mask(channelMask);
2058 const uint32_t hapticChannelCount = audio_channel_count_from_out_mask(
2059 channelMask & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurente78b6762018-12-19 16:29:01 -08002060
Mikhail Naganovcf84e592017-12-07 11:25:11 -08002061 for (audio_io_handle_t output : outputs) {
2062 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueFor(output);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002063 // matching criteria values in priority order for current output
2064 std::vector<uint32_t> currentMatchCriteria(8, 0);
jiabin40573322018-11-08 12:08:02 -08002065
Eric Laurent16c66dd2019-05-01 17:54:10 -07002066 if (outputDesc->isDuplicated()) {
2067 continue;
2068 }
2069 if ((kExcludedFlags & outputDesc->mFlags) != 0) {
2070 continue;
2071 }
Eric Laurent8838a382014-09-08 16:44:28 -07002072
Eric Laurent16c66dd2019-05-01 17:54:10 -07002073 // If haptic channel is specified, use the haptic output if present.
2074 // When using haptic output, same audio format and sample rate are required.
2075 const uint32_t outputHapticChannelCount = audio_channel_count_from_out_mask(
jiabin5740f082019-08-19 15:08:30 -07002076 outputDesc->getChannelMask() & AUDIO_CHANNEL_HAPTIC_ALL);
Eric Laurent16c66dd2019-05-01 17:54:10 -07002077 if ((hapticChannelCount == 0) != (outputHapticChannelCount == 0)) {
2078 continue;
2079 }
2080 if (outputHapticChannelCount >= hapticChannelCount
jiabin5740f082019-08-19 15:08:30 -07002081 && format == outputDesc->getFormat()
2082 && samplingRate == outputDesc->getSamplingRate()) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002083 currentMatchCriteria[0] = outputHapticChannelCount;
2084 }
2085
2086 // functional flags match
Carter Hsu199f1892021-10-15 15:47:29 +08002087 const int matchingFunctionalFlags =
2088 __builtin_popcount(outputDesc->mFlags & functionalFlags);
2089 const int totalFunctionalFlags =
2090 __builtin_popcount(outputDesc->mFlags & kFunctionalFlags);
2091 // Prefer matching functional flags, but subtract unnecessary functional flags.
2092 currentMatchCriteria[1] = 100 * (matchingFunctionalFlags + 1) - totalFunctionalFlags;
Eric Laurent16c66dd2019-05-01 17:54:10 -07002093
2094 // channel mask and channel count match
jiabin5740f082019-08-19 15:08:30 -07002095 uint32_t outputChannelCount = audio_channel_count_from_out_mask(
2096 outputDesc->getChannelMask());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002097 if (channelMask != AUDIO_CHANNEL_NONE && channelCount > 2 &&
2098 channelCount <= outputChannelCount) {
2099 if ((audio_channel_mask_get_representation(channelMask) ==
jiabin5740f082019-08-19 15:08:30 -07002100 audio_channel_mask_get_representation(outputDesc->getChannelMask())) &&
2101 ((channelMask & outputDesc->getChannelMask()) == channelMask)) {
Eric Laurent16c66dd2019-05-01 17:54:10 -07002102 currentMatchCriteria[2] = outputChannelCount;
Eric Laurente552edb2014-03-10 17:42:56 -07002103 }
Eric Laurent16c66dd2019-05-01 17:54:10 -07002104 currentMatchCriteria[3] = outputChannelCount;
2105 }
2106
2107 // sampling rate match
jiabinb12a6da2022-06-03 20:48:18 +00002108 if (samplingRate > SAMPLE_RATE_HZ_DEFAULT) {
jiabin5740f082019-08-19 15:08:30 -07002109 currentMatchCriteria[4] = outputDesc->getSamplingRate();
Eric Laurent16c66dd2019-05-01 17:54:10 -07002110 }
2111
2112 // performance flags match
2113 currentMatchCriteria[5] = popcount(outputDesc->mFlags & performanceFlags);
2114
2115 // format match
2116 if (format != AUDIO_FORMAT_INVALID) {
2117 currentMatchCriteria[6] =
jiabin4ef93452019-09-10 14:29:54 -07002118 PolicyAudioPort::kFormatDistanceMax -
2119 PolicyAudioPort::formatDistance(format, outputDesc->getFormat());
Eric Laurent16c66dd2019-05-01 17:54:10 -07002120 }
2121
2122 // primary output match
2123 currentMatchCriteria[7] = outputDesc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY;
2124
2125 // compare match criteria by priority then value
2126 if (std::lexicographical_compare(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2127 currentMatchCriteria.begin(), currentMatchCriteria.end())) {
2128 bestMatchCriteria = currentMatchCriteria;
2129 bestOutput = output;
2130
2131 std::stringstream result;
2132 std::copy(bestMatchCriteria.begin(), bestMatchCriteria.end(),
2133 std::ostream_iterator<int>(result, " "));
2134 ALOGV("%s new bestOutput %d criteria %s",
2135 __func__, bestOutput, result.str().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07002136 }
2137 }
2138
Eric Laurent16c66dd2019-05-01 17:54:10 -07002139 return bestOutput;
Eric Laurente552edb2014-03-10 17:42:56 -07002140}
2141
Eric Laurent8fc147b2018-07-22 19:13:55 -07002142status_t AudioPolicyManager::startOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002143{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002144 ALOGV("%s portId %d", __FUNCTION__, portId);
2145
2146 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2147 if (outputDesc == 0) {
2148 ALOGW("startOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002149 return BAD_VALUE;
2150 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002151 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002152
Eric Laurent8fc147b2018-07-22 19:13:55 -07002153 ALOGV("startOutput() output %d, stream %d, session %d",
Eric Laurent97ac8712018-07-27 18:59:02 -07002154 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurentc75307b2015-03-17 15:29:32 -07002155
Eric Laurent733ce942017-12-07 12:18:25 -08002156 status_t status = outputDesc->start();
2157 if (status != NO_ERROR) {
2158 return status;
Eric Laurent3974e3b2017-12-07 17:58:43 -08002159 }
2160
Eric Laurent97ac8712018-07-27 18:59:02 -07002161 uint32_t delayMs;
2162 status = startSource(outputDesc, client, &delayMs);
Eric Laurentc75307b2015-03-17 15:29:32 -07002163
2164 if (status != NO_ERROR) {
Eric Laurent733ce942017-12-07 12:18:25 -08002165 outputDesc->stop();
jiabin3ff8d7d2022-12-13 06:27:44 +00002166 if (status == DEAD_OBJECT) {
2167 sp<SwAudioOutputDescriptor> desc =
2168 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2169 if (desc == nullptr) {
2170 // This is not common, it may indicate something wrong with the HAL.
2171 ALOGE("%s unable to open output with default config", __func__);
2172 return status;
2173 }
2174 desc->mUsePreferredMixerAttributes = true;
2175 }
Eric Laurent8c7e6da2015-04-21 17:37:00 -07002176 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002177 }
jiabina84c3d32022-12-02 18:59:55 +00002178
2179 // If the client is the first one active on preferred mixer parameters, reopen the output
2180 // if the current mixer parameters doesn't match the preferred one.
2181 if (outputDesc->devices().size() == 1) {
2182 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2183 outputDesc->devices()[0]->getId(), client->strategy());
2184 if (info != nullptr && info->getUid() == client->uid()) {
2185 if (info->getActiveClientCount() == 0 && !outputDesc->isConfigurationMatched(
2186 info->getConfigBase(), info->getFlags())) {
2187 stopSource(outputDesc, client);
2188 outputDesc->stop();
2189 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
2190 config.channel_mask = info->getConfigBase().channel_mask;
2191 config.sample_rate = info->getConfigBase().sample_rate;
2192 config.format = info->getConfigBase().format;
jiabin3ff8d7d2022-12-13 06:27:44 +00002193 sp<SwAudioOutputDescriptor> desc =
2194 reopenOutput(outputDesc, &config, info->getFlags(), __func__);
2195 if (desc == nullptr) {
2196 return BAD_VALUE;
jiabina84c3d32022-12-02 18:59:55 +00002197 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002198 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00002199 // Intentionally return error to let the client side resending request for
2200 // creating and starting.
2201 return DEAD_OBJECT;
2202 }
2203 info->increaseActiveClient();
jiabine3d1f552023-06-14 17:42:17 +00002204 if (info->getActiveClientCount() == 1 &&
2205 (info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE) {
2206 // If it is first bit-perfect client, reroute all clients that will be routed to
2207 // the bit-perfect sink so that it is guaranteed only bit-perfect stream is active.
2208 PortHandleVector clientsToInvalidate;
2209 for (size_t i = 0; i < mOutputs.size(); i++) {
2210 if (mOutputs[i] == outputDesc ||
jiabin98c519c2023-07-05 17:34:21 +00002211 mOutputs[i]->devices().filter(outputDesc->devices()).isEmpty()) {
jiabine3d1f552023-06-14 17:42:17 +00002212 continue;
2213 }
2214 for (const auto& c : mOutputs[i]->getClientIterable()) {
2215 clientsToInvalidate.push_back(c->portId());
2216 }
2217 }
2218 if (!clientsToInvalidate.empty()) {
2219 ALOGD("%s Invalidate clients due to first bit-perfect client started",
2220 __func__);
2221 mpClientInterface->invalidateTracks(clientsToInvalidate);
2222 }
2223 }
jiabina84c3d32022-12-02 18:59:55 +00002224 }
2225 }
2226
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002227 if (client->hasPreferredDevice()) {
2228 // playback activity with preferred device impacts routing occurred, inform upper layers
2229 mpClientInterface->onRoutingUpdated();
2230 }
Eric Laurentc75307b2015-03-17 15:29:32 -07002231 if (delayMs != 0) {
2232 usleep(delayMs * 1000);
2233 }
2234
2235 return status;
2236}
2237
Eric Laurent96d1dda2022-03-14 17:14:19 +01002238bool AudioPolicyManager::isLeUnicastActive() const {
2239 if (isInCall()) {
2240 return true;
2241 }
2242 return isAnyDeviceTypeActive(getAudioDeviceOutLeAudioUnicastSet());
2243}
2244
2245bool AudioPolicyManager::isAnyDeviceTypeActive(const DeviceTypeSet& deviceTypes) const {
2246 if (mAvailableOutputDevices.getDevicesFromTypes(deviceTypes).isEmpty()) {
2247 return false;
2248 }
2249 bool active = mOutputs.isAnyDeviceTypeActive(deviceTypes);
2250 ALOGV("%s active %d", __func__, active);
2251 return active;
2252}
2253
Eric Laurent97ac8712018-07-27 18:59:02 -07002254status_t AudioPolicyManager::startSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2255 const sp<TrackClientDescriptor>& client,
2256 uint32_t *delayMs)
Eric Laurentc75307b2015-03-17 15:29:32 -07002257{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002258 // cannot start playback of STREAM_TTS if any other output is being used
2259 uint32_t beaconMuteLatency = 0;
Eric Laurentc75307b2015-03-17 15:29:32 -07002260
2261 *delayMs = 0;
Eric Laurent97ac8712018-07-27 18:59:02 -07002262 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002263 auto clientVolSrc = client->volumeSource();
François Gaffiec005e562018-11-06 15:04:49 +01002264 auto clientStrategy = client->strategy();
2265 auto clientAttr = client->attributes();
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002266 if (stream == AUDIO_STREAM_TTS) {
2267 ALOGV("\t found BEACON stream");
François Gaffie1c878552018-11-22 16:53:21 +01002268 if (!mTtsOutputAvailable && mOutputs.isAnyOutputActive(
Francois Gaffie4404ddb2021-02-04 17:03:38 +01002269 toVolumeSource(AUDIO_STREAM_TTS, false) /*sourceToIgnore*/)) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002270 return INVALID_OPERATION;
2271 } else {
2272 beaconMuteLatency = handleEventForBeacon(STARTING_BEACON);
2273 }
2274 } else {
2275 // some playback other than beacon starts
2276 beaconMuteLatency = handleEventForBeacon(STARTING_OUTPUT);
2277 }
2278
Eric Laurent77305a62016-07-25 16:39:22 -07002279 // force device change if the output is inactive and no audio patch is already present.
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002280 // check active before incrementing usage count
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02002281 bool force = !outputDesc->isActive() && !outputDesc->isRouted();
Eric Laurent7c1ec5f2015-07-09 14:52:47 -07002282
François Gaffie11d30102018-11-02 16:09:09 +01002283 DeviceVector devices;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002284 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
Eric Laurent97ac8712018-07-27 18:59:02 -07002285 const char *address = NULL;
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002286 if (policyMix != nullptr) {
François Gaffie11d30102018-11-02 16:09:09 +01002287 audio_devices_t newDeviceType;
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00002288 address = policyMix->mDeviceAddress.c_str();
Kevin Rocard153f92d2018-12-18 18:33:28 -08002289 if ((policyMix->mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie11d30102018-11-02 16:09:09 +01002290 newDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Kevin Rocard153f92d2018-12-18 18:33:28 -08002291 } else {
2292 newDeviceType = policyMix->mDeviceType;
Eric Laurent97ac8712018-07-27 18:59:02 -07002293 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08002294 sp device = mAvailableOutputDevices.getDevice(newDeviceType, String8(address),
2295 AUDIO_FORMAT_DEFAULT);
2296 ALOG_ASSERT(device, "%s: no device found t=%u, a=%s", __func__, newDeviceType, address);
2297 devices.add(device);
Eric Laurent97ac8712018-07-27 18:59:02 -07002298 }
2299
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002300 // requiresMuteCheck is false when we can bypass mute strategy.
2301 // It covers a common case when there is no materially active audio
2302 // and muting would result in unnecessary delay and dropped audio.
2303 const uint32_t outputLatencyMs = outputDesc->latency();
2304 bool requiresMuteCheck = outputDesc->isActive(outputLatencyMs * 2); // account for drain
Eric Laurent96d1dda2022-03-14 17:14:19 +01002305 bool wasLeUnicastActive = isLeUnicastActive();
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002306
Eric Laurente552edb2014-03-10 17:42:56 -07002307 // increment usage count for this stream on the requested output:
2308 // NOTE that the usage count is the same for duplicated output and hardware output which is
2309 // necessary for a correct control of hardware output routing by startOutput() and stopOutput()
Eric Laurent592dd7b2018-08-05 18:58:48 -07002310 outputDesc->setClientActive(client, true);
Eric Laurent97ac8712018-07-27 18:59:02 -07002311
2312 if (client->hasPreferredDevice(true)) {
Eric Laurent72af8012023-03-15 17:36:22 +01002313 if (outputDesc->sameExclusivePreferredDevicesCount() > 0) {
François Gaffief96e5432019-04-09 17:13:56 +02002314 // Preferred device may be exclusive, use only if no other active clients on this output
2315 devices = DeviceVector(
2316 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId()));
2317 } else {
2318 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
2319 }
François Gaffie11d30102018-11-02 16:09:09 +01002320 if (devices != outputDesc->devices()) {
François Gaffiec005e562018-11-06 15:04:49 +01002321 checkStrategyRoute(clientStrategy, outputDesc->mIoHandle);
Eric Laurent97ac8712018-07-27 18:59:02 -07002322 }
2323 }
Eric Laurente552edb2014-03-10 17:42:56 -07002324
François Gaffiec005e562018-11-06 15:04:49 +01002325 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002326 selectOutputForMusicEffects();
2327 }
2328
François Gaffie1c878552018-11-22 16:53:21 +01002329 if (outputDesc->getActivityCount(clientVolSrc) == 1 || !devices.isEmpty()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08002330 // starting an output being rerouted?
François Gaffie11d30102018-11-02 16:09:09 +01002331 if (devices.isEmpty()) {
2332 devices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Eric Laurent275e8e92014-11-30 15:14:47 -08002333 }
François Gaffiec005e562018-11-06 15:04:49 +01002334 bool shouldWait =
2335 (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM)) ||
2336 followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_NOTIFICATION)) ||
2337 (beaconMuteLatency > 0));
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002338 uint32_t waitMs = beaconMuteLatency;
Eric Laurente552edb2014-03-10 17:42:56 -07002339 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002340 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente552edb2014-03-10 17:42:56 -07002341 if (desc != outputDesc) {
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002342 // An output has a shared device if
2343 // - managed by the same hw module
2344 // - supports the currently selected device
2345 const bool sharedDevice = outputDesc->sharesHwModuleWith(desc)
François Gaffie11d30102018-11-02 16:09:09 +01002346 && (!desc->filterSupportedDevices(devices).isEmpty());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002347
Eric Laurent77305a62016-07-25 16:39:22 -07002348 // force a device change if any other output is:
2349 // - managed by the same hw module
Jean-Michel Trivi4a5b4812018-02-08 17:22:32 +00002350 // - supports currently selected device
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002351 // - has a current device selection that differs from selected device.
Eric Laurent77305a62016-07-25 16:39:22 -07002352 // - has an active audio patch
Eric Laurente552edb2014-03-10 17:42:56 -07002353 // In this case, the audio HAL must receive the new device selection so that it can
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002354 // change the device currently selected by the other output.
2355 if (sharedDevice &&
François Gaffie11d30102018-11-02 16:09:09 +01002356 desc->devices() != devices &&
Eric Laurent77305a62016-07-25 16:39:22 -07002357 desc->getPatchHandle() != AUDIO_PATCH_HANDLE_NONE) {
Eric Laurente552edb2014-03-10 17:42:56 -07002358 force = true;
2359 }
2360 // wait for audio on other active outputs to be presented when starting
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002361 // a notification so that audio focus effect can propagate, or that a mute/unmute
2362 // event occurred for beacon
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002363 const uint32_t latencyMs = desc->latency();
2364 const bool isActive = desc->isActive(latencyMs * 2); // account for drain
2365
2366 if (shouldWait && isActive && (waitMs < latencyMs)) {
2367 waitMs = latencyMs;
Eric Laurente552edb2014-03-10 17:42:56 -07002368 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002369
2370 // Require mute check if another output is on a shared device
2371 // and currently active to have proper drain and avoid pops.
2372 // Note restoring AudioTracks onto this output needs to invoke
2373 // a volume ramp if there is no mute.
2374 requiresMuteCheck |= sharedDevice && isActive;
Eric Laurente552edb2014-03-10 17:42:56 -07002375 }
2376 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002377
jiabin3ff8d7d2022-12-13 06:27:44 +00002378 if (outputDesc->mUsePreferredMixerAttributes && devices != outputDesc->devices()) {
2379 // If the output is open with preferred mixer attributes, but the routed device is
2380 // changed when calling this function, returning DEAD_OBJECT to indicate routing
2381 // changed.
2382 return DEAD_OBJECT;
2383 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002384 const uint32_t muteWaitMs =
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302385 setOutputDevices(__func__, outputDesc, devices, force, 0, nullptr,
2386 requiresMuteCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002387
Eric Laurente552edb2014-03-10 17:42:56 -07002388 // apply volume rules for current stream and device if necessary
François Gaffieaaac0fd2018-11-22 17:56:39 +01002389 auto &curves = getVolumeCurves(client->attributes());
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002390 if (NO_ERROR != checkAndSetVolume(curves, client->volumeSource(),
François Gaffieaaac0fd2018-11-22 17:56:39 +01002391 curves.getVolumeIndex(outputDesc->devices().types()),
Eric Laurentc75307b2015-03-17 15:29:32 -07002392 outputDesc,
Francois Gaffied11442b2020-04-27 11:51:09 +02002393 outputDesc->devices().types(), 0 /*delay*/,
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00002394 outputDesc->useHwGain() /*force*/)) {
2395 // request AudioService to reinitialize the volume curves asynchronously
2396 ALOGE("checkAndSetVolume failed, requesting volume range init");
2397 mpClientInterface->onVolumeRangeInitRequest();
2398 };
Eric Laurente552edb2014-03-10 17:42:56 -07002399
2400 // update the outputs if starting an output with a stream that can affect notification
2401 // routing
2402 handleNotificationRoutingForStream(stream);
Eric Laurentc722f302014-12-10 11:21:49 -08002403
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002404 // force reevaluating accessibility routing when ringtone or alarm starts
François Gaffiec005e562018-11-06 15:04:49 +01002405 if (followsSameRouting(clientAttr, attributes_initializer(AUDIO_USAGE_ALARM))) {
jiabinc44b3462022-12-08 12:52:31 -08002406 invalidateStreams({AUDIO_STREAM_ACCESSIBILITY});
Eric Laurent2cbe89a2014-12-19 11:49:08 -08002407 }
Eric Laurentdc462862016-07-19 12:29:53 -07002408
2409 if (waitMs > muteWaitMs) {
2410 *delayMs = waitMs - muteWaitMs;
2411 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00002412
2413 // FIXME: A device change (muteWaitMs > 0) likely introduces a volume change.
2414 // A volume change enacted by APM with 0 delay is not synchronous, as it goes
2415 // via AudioCommandThread to AudioFlinger. Hence it is possible that the volume
2416 // change occurs after the MixerThread starts and causes a stream volume
2417 // glitch.
2418 //
2419 // We do not introduce additional delay here.
Eric Laurente552edb2014-03-10 17:42:56 -07002420 }
Eric Laurentdc462862016-07-19 12:29:53 -07002421
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002422 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
jiabin9a3361e2019-10-01 09:38:30 -07002423 mEngine->getForceUse(
2424 AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
François Gaffiec005e562018-11-06 15:04:49 +01002425 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), true, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002426 }
2427
Eric Laurent97ac8712018-07-27 18:59:02 -07002428 // Automatically enable the remote submix input when output is started on a re routing mix
2429 // of type MIX_TYPE_RECORDERS
jiabin9a3361e2019-10-01 09:38:30 -07002430 if (isSingleDeviceType(devices.types(), &audio_is_remote_submix_device) &&
2431 policyMix != NULL && policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002432 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2433 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
2434 address,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002435 "remote-submix",
2436 AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002437 }
2438
Eric Laurent96d1dda2022-03-14 17:14:19 +01002439 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, *delayMs);
2440
Eric Laurente552edb2014-03-10 17:42:56 -07002441 return NO_ERROR;
2442}
2443
Eric Laurent96d1dda2022-03-14 17:14:19 +01002444void AudioPolicyManager::checkLeBroadcastRoutes(bool wasUnicastActive,
2445 sp<SwAudioOutputDescriptor> ignoredOutput, uint32_t delayMs) {
2446 bool isUnicastActive = isLeUnicastActive();
2447
2448 if (wasUnicastActive != isUnicastActive) {
jiabin3ff8d7d2022-12-13 06:27:44 +00002449 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent96d1dda2022-03-14 17:14:19 +01002450 //reroute all outputs routed to LE broadcast if LE unicast activy changed on any output
2451 for (size_t i = 0; i < mOutputs.size(); i++) {
2452 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
2453 if (desc != ignoredOutput && desc->isActive()
2454 && ((isUnicastActive &&
2455 !desc->devices().
2456 getDevicesFromType(AUDIO_DEVICE_OUT_BLE_BROADCAST).isEmpty())
2457 || (wasUnicastActive &&
2458 !desc->devices().getDevicesFromTypes(
2459 getAudioDeviceOutLeAudioUnicastSet()).isEmpty()))) {
2460 DeviceVector newDevices = getNewOutputDevices(desc, false /*fromCache*/);
2461 bool force = desc->devices() != newDevices;
jiabin3ff8d7d2022-12-13 06:27:44 +00002462 if (desc->mUsePreferredMixerAttributes && force) {
2463 // If the device is using preferred mixer attributes, the output need to reopen
2464 // with default configuration when the new selected devices are different from
2465 // current routing devices.
2466 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
2467 continue;
2468 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302469 setOutputDevices(__func__, desc, newDevices, force, delayMs);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002470 // re-apply device specific volume if not done by setOutputDevice()
2471 if (!force) {
2472 applyStreamVolumes(desc, newDevices.types(), delayMs);
2473 }
2474 }
2475 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002476 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01002477 }
2478}
2479
Eric Laurent8fc147b2018-07-22 19:13:55 -07002480status_t AudioPolicyManager::stopOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002481{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002482 ALOGV("%s portId %d", __FUNCTION__, portId);
2483
2484 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2485 if (outputDesc == 0) {
2486 ALOGW("stopOutput() no output for client %d", portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002487 return BAD_VALUE;
2488 }
Andy Hung39efb7a2018-09-26 15:39:28 -07002489 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
Eric Laurente552edb2014-03-10 17:42:56 -07002490
Jean-Michel Trivib1f6e642023-02-07 20:49:04 +00002491 if (client->hasPreferredDevice(true)) {
2492 // playback activity with preferred device impacts routing occurred, inform upper layers
2493 mpClientInterface->onRoutingUpdated();
2494 }
2495
Eric Laurent97ac8712018-07-27 18:59:02 -07002496 ALOGV("stopOutput() output %d, stream %d, session %d",
2497 outputDesc->mIoHandle, client->stream(), client->session());
Eric Laurente552edb2014-03-10 17:42:56 -07002498
Eric Laurent97ac8712018-07-27 18:59:02 -07002499 status_t status = stopSource(outputDesc, client);
Eric Laurent3974e3b2017-12-07 17:58:43 -08002500
Eric Laurent733ce942017-12-07 12:18:25 -08002501 if (status == NO_ERROR ) {
2502 outputDesc->stop();
jiabina84c3d32022-12-02 18:59:55 +00002503 } else {
2504 return status;
2505 }
2506
2507 if (outputDesc->devices().size() == 1) {
2508 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
2509 outputDesc->devices()[0]->getId(), client->strategy());
2510 if (info != nullptr && info->getUid() == client->uid()) {
2511 info->decreaseActiveClient();
2512 if (info->getActiveClientCount() == 0) {
2513 reopenOutput(outputDesc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
2514 }
2515 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002516 }
2517 return status;
Eric Laurentc75307b2015-03-17 15:29:32 -07002518}
2519
Eric Laurent97ac8712018-07-27 18:59:02 -07002520status_t AudioPolicyManager::stopSource(const sp<SwAudioOutputDescriptor>& outputDesc,
2521 const sp<TrackClientDescriptor>& client)
Eric Laurentc75307b2015-03-17 15:29:32 -07002522{
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002523 // always handle stream stop, check which stream type is stopping
Eric Laurent97ac8712018-07-27 18:59:02 -07002524 audio_stream_type_t stream = client->stream();
François Gaffie1c878552018-11-22 16:53:21 +01002525 auto clientVolSrc = client->volumeSource();
Eric Laurent96d1dda2022-03-14 17:14:19 +01002526 bool wasLeUnicastActive = isLeUnicastActive();
Eric Laurent97ac8712018-07-27 18:59:02 -07002527
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07002528 handleEventForBeacon(stream == AUDIO_STREAM_TTS ? STOPPING_BEACON : STOPPING_OUTPUT);
2529
François Gaffie1c878552018-11-22 16:53:21 +01002530 if (outputDesc->getActivityCount(clientVolSrc) > 0) {
2531 if (outputDesc->getActivityCount(clientVolSrc) == 1) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002532 // Automatically disable the remote submix input when output is stopped on a
2533 // re routing mix of type MIX_TYPE_RECORDERS
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002534 sp<AudioPolicyMix> policyMix = outputDesc->mPolicyMix.promote();
jiabin9a3361e2019-10-01 09:38:30 -07002535 if (isSingleDeviceType(
2536 outputDesc->devices().types(), &audio_is_remote_submix_device) &&
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08002537 policyMix != nullptr &&
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002538 policyMix->mMixType == MIX_TYPE_RECORDERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07002539 setDeviceConnectionStateInt(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2540 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002541 policyMix->mDeviceAddress,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08002542 "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent97ac8712018-07-27 18:59:02 -07002543 }
2544 }
2545 bool forceDeviceUpdate = false;
Eric Laurent72af8012023-03-15 17:36:22 +01002546 if (client->hasPreferredDevice(true) &&
2547 outputDesc->sameExclusivePreferredDevicesCount() < 2) {
François Gaffiec005e562018-11-06 15:04:49 +01002548 checkStrategyRoute(client->strategy(), AUDIO_IO_HANDLE_NONE);
Eric Laurent97ac8712018-07-27 18:59:02 -07002549 forceDeviceUpdate = true;
2550 }
2551
Eric Laurente552edb2014-03-10 17:42:56 -07002552 // decrement usage count of this stream on the output
Eric Laurent592dd7b2018-08-05 18:58:48 -07002553 outputDesc->setClientActive(client, false);
Paul McLeanaa981192015-03-21 09:55:15 -07002554
Eric Laurente552edb2014-03-10 17:42:56 -07002555 // store time at which the stream was stopped - see isStreamActive()
François Gaffie1c878552018-11-22 16:53:21 +01002556 if (outputDesc->getActivityCount(clientVolSrc) == 0 || forceDeviceUpdate) {
François Gaffiec005e562018-11-06 15:04:49 +01002557 outputDesc->setStopTime(client, systemTime());
François Gaffie11d30102018-11-02 16:09:09 +01002558 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
Francois Gaffie3523ab32021-06-22 13:24:34 +02002559
2560 // If the routing does not change, if an output is routed on a device using HwGain
2561 // (aka setAudioPortConfig) and there are still active clients following different
2562 // volume group(s), force reapply volume
2563 bool requiresVolumeCheck = outputDesc->getActivityCount(clientVolSrc) == 0 &&
2564 outputDesc->useHwGain() && outputDesc->isAnyActive(VOLUME_SOURCE_NONE);
2565
Eric Laurente552edb2014-03-10 17:42:56 -07002566 // delay the device switch by twice the latency because stopOutput() is executed when
2567 // the track stop() command is received and at that time the audio track buffer can
2568 // still contain data that needs to be drained. The latency only covers the audio HAL
2569 // and kernel buffers. Also the latency does not always include additional delay in the
2570 // audio path (audio DSP, CODEC ...)
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302571 setOutputDevices(__func__, outputDesc, newDevices, false, outputDesc->latency()*2,
Francois Gaffie3523ab32021-06-22 13:24:34 +02002572 nullptr, true /*requiresMuteCheck*/, requiresVolumeCheck);
Eric Laurente552edb2014-03-10 17:42:56 -07002573
2574 // force restoring the device selection on other active outputs if it differs from the
2575 // one being selected for this output
jiabin3ff8d7d2022-12-13 06:27:44 +00002576 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent57de36c2016-09-28 16:59:11 -07002577 uint32_t delayMs = outputDesc->latency()*2;
Eric Laurente552edb2014-03-10 17:42:56 -07002578 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01002579 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurentc75307b2015-03-17 15:29:32 -07002580 if (desc != outputDesc &&
Eric Laurente552edb2014-03-10 17:42:56 -07002581 desc->isActive() &&
2582 outputDesc->sharesHwModuleWith(desc) &&
François Gaffie11d30102018-11-02 16:09:09 +01002583 (newDevices != desc->devices())) {
2584 DeviceVector newDevices2 = getNewOutputDevices(desc, false /*fromCache*/);
2585 bool force = desc->devices() != newDevices2;
Eric Laurentf3a5a602018-05-22 18:42:55 -07002586
jiabin3ff8d7d2022-12-13 06:27:44 +00002587 if (desc->mUsePreferredMixerAttributes && force) {
2588 // If the device is using preferred mixer attributes, the output need to
2589 // reopen with default configuration when the new selected devices are
2590 // different from current routing devices.
2591 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices2);
2592 continue;
2593 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05302594 setOutputDevices(__func__, desc, newDevices2, force, delayMs);
François Gaffie11d30102018-11-02 16:09:09 +01002595
Eric Laurent57de36c2016-09-28 16:59:11 -07002596 // re-apply device specific volume if not done by setOutputDevice()
2597 if (!force) {
François Gaffie11d30102018-11-02 16:09:09 +01002598 applyStreamVolumes(desc, newDevices2.types(), delayMs);
Eric Laurent57de36c2016-09-28 16:59:11 -07002599 }
Eric Laurente552edb2014-03-10 17:42:56 -07002600 }
2601 }
jiabin3ff8d7d2022-12-13 06:27:44 +00002602 reopenOutputsWithDevices(outputsToReopen);
Eric Laurente552edb2014-03-10 17:42:56 -07002603 // update the outputs if stopping one with a stream that can affect notification routing
2604 handleNotificationRoutingForStream(stream);
2605 }
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002606
2607 if (stream == AUDIO_STREAM_ENFORCED_AUDIBLE &&
2608 mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_SYSTEM_ENFORCED) {
Jean-Michel Trivi74e01fa2019-02-25 12:18:09 -08002609 setStrategyMute(streamToStrategy(AUDIO_STREAM_ALARM), false, outputDesc);
Tomoharu Kasaharab62d78b2018-01-18 20:55:02 +09002610 }
2611
François Gaffiec005e562018-11-06 15:04:49 +01002612 if (followsSameRouting(client->attributes(), attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07002613 selectOutputForMusicEffects();
2614 }
Eric Laurent96d1dda2022-03-14 17:14:19 +01002615
2616 checkLeBroadcastRoutes(wasLeUnicastActive, outputDesc, outputDesc->latency()*2);
2617
Eric Laurente552edb2014-03-10 17:42:56 -07002618 return NO_ERROR;
2619 } else {
Eric Laurentc75307b2015-03-17 15:29:32 -07002620 ALOGW("stopOutput() refcount is already 0");
Eric Laurente552edb2014-03-10 17:42:56 -07002621 return INVALID_OPERATION;
2622 }
2623}
2624
jiabinbce0c1d2020-10-05 11:20:18 -07002625bool AudioPolicyManager::releaseOutput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002626{
Eric Laurent8fc147b2018-07-22 19:13:55 -07002627 ALOGV("%s portId %d", __FUNCTION__, portId);
2628
2629 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputForClient(portId);
2630 if (outputDesc == 0) {
Andy Hung39efb7a2018-09-26 15:39:28 -07002631 // If an output descriptor is closed due to a device routing change,
2632 // then there are race conditions with releaseOutput from tracks
2633 // that may be destroyed (with no PlaybackThread) or a PlaybackThread
2634 // destroyed shortly thereafter.
2635 //
2636 // Here we just log a warning, instead of a fatal error.
Eric Laurent8fc147b2018-07-22 19:13:55 -07002637 ALOGW("releaseOutput() no output for client %d", portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002638 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002639 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002640
2641 ALOGV("releaseOutput() %d", outputDesc->mIoHandle);
Eric Laurente552edb2014-03-10 17:42:56 -07002642
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302643 sp<TrackClientDescriptor> client = outputDesc->getClient(portId);
2644 if (outputDesc->isClientActive(client)) {
2645 ALOGW("releaseOutput() inactivates portId %d in good faith", portId);
2646 stopOutput(portId);
2647 }
2648
Eric Laurent8fc147b2018-07-22 19:13:55 -07002649 if (outputDesc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
2650 if (outputDesc->mDirectOpenCount <= 0) {
Eric Laurente552edb2014-03-10 17:42:56 -07002651 ALOGW("releaseOutput() invalid open count %d for output %d",
Eric Laurent8fc147b2018-07-22 19:13:55 -07002652 outputDesc->mDirectOpenCount, outputDesc->mIoHandle);
jiabinbce0c1d2020-10-05 11:20:18 -07002653 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002654 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07002655 if (--outputDesc->mDirectOpenCount == 0) {
2656 closeOutput(outputDesc->mIoHandle);
Eric Laurentb52c1522014-05-20 11:27:36 -07002657 mpClientInterface->onAudioPortListUpdate();
Eric Laurente552edb2014-03-10 17:42:56 -07002658 }
2659 }
Jaideep Sharma7bf382e2020-11-26 17:07:29 +05302660
Andy Hung39efb7a2018-09-26 15:39:28 -07002661 outputDesc->removeClient(portId);
jiabinbce0c1d2020-10-05 11:20:18 -07002662 if (outputDesc->mPendingReopenToQueryProfiles && outputDesc->getClientCount() == 0) {
2663 // The output is pending reopened to query dynamic profiles and
2664 // there is no active clients
2665 closeOutput(outputDesc->mIoHandle);
2666 sp<SwAudioOutputDescriptor> newOutputDesc = openOutputWithProfileAndDevice(
2667 outputDesc->mProfile, mEngine->getActiveMediaDevices(mAvailableOutputDevices));
2668 if (newOutputDesc == nullptr) {
2669 ALOGE("%s failed to open output", __func__);
2670 }
2671 return true;
2672 }
2673 return false;
Eric Laurente552edb2014-03-10 17:42:56 -07002674}
2675
Eric Laurentcaf7f482014-11-25 17:50:47 -08002676status_t AudioPolicyManager::getInputForAttr(const audio_attributes_t *attr,
2677 audio_io_handle_t *input,
Mikhail Naganov2996f672019-04-18 12:29:59 -07002678 audio_unique_id_t riid,
Eric Laurentcaf7f482014-11-25 17:50:47 -08002679 audio_session_t session,
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002680 const AttributionSourceState& attributionSource,
jiabinf1c73972022-04-14 16:28:52 -07002681 audio_config_base_t *config,
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002682 audio_input_flags_t flags,
Eric Laurent2ac76942017-06-22 17:17:09 -07002683 audio_port_handle_t *selectedDeviceId,
Eric Laurent20b9ef02016-12-05 11:03:16 -08002684 input_type_t *inputType,
2685 audio_port_handle_t *portId)
Eric Laurente552edb2014-03-10 17:42:56 -07002686{
François Gaffiec005e562018-11-06 15:04:49 +01002687 ALOGV("%s() source %d, sampling rate %d, format %#x, channel mask %#x, session %d, "
Eric Laurent2f2c1982021-06-02 14:03:11 +02002688 "flags %#x attributes=%s requested device ID %d",
2689 __func__, attr->source, config->sample_rate, config->format, config->channel_mask,
2690 session, flags, toString(*attr).c_str(), *selectedDeviceId);
Eric Laurente552edb2014-03-10 17:42:56 -07002691
Eric Laurentad2e7b92017-09-14 20:06:42 -07002692 status_t status = NO_ERROR;
Francois Gaffie716e1432019-01-14 16:58:59 +01002693 audio_attributes_t attributes = *attr;
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002694 sp<AudioPolicyMix> policyMix;
François Gaffie11d30102018-11-02 16:09:09 +01002695 sp<DeviceDescriptor> device;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002696 sp<AudioInputDescriptor> inputDesc;
François Gaffie1b4753e2023-02-06 10:36:33 +01002697 sp<AudioInputDescriptor> previousInputDesc;
Eric Laurent8fc147b2018-07-22 19:13:55 -07002698 sp<RecordClientDescriptor> clientDesc;
2699 audio_port_handle_t requestedDeviceId = *selectedDeviceId;
Svet Ganov3e5f14f2021-05-13 22:51:08 +00002700 uid_t uid = VALUE_OR_RETURN_STATUS(aidl2legacy_int32_t_uid_t(attributionSource.uid));
Eric Laurent8f42ea12018-08-08 09:08:25 -07002701 bool isSoundTrigger;
Eric Laurent8f42ea12018-08-08 09:08:25 -07002702
2703 // The supplied portId must be AUDIO_PORT_HANDLE_NONE
2704 if (*portId != AUDIO_PORT_HANDLE_NONE) {
2705 return INVALID_OPERATION;
2706 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002707
Francois Gaffie716e1432019-01-14 16:58:59 +01002708 if (attr->source == AUDIO_SOURCE_DEFAULT) {
2709 attributes.source = AUDIO_SOURCE_MIC;
Eric Laurentfe231122017-11-17 17:48:06 -08002710 }
2711
Paul McLean466dc8e2015-04-17 13:15:36 -06002712 // Explicit routing?
Pattydd807582021-11-04 21:01:03 +08002713 sp<DeviceDescriptor> explicitRoutingDevice =
François Gaffie11d30102018-11-02 16:09:09 +01002714 mAvailableInputDevices.getDeviceFromId(*selectedDeviceId);
Paul McLean466dc8e2015-04-17 13:15:36 -06002715
Eric Laurentad2e7b92017-09-14 20:06:42 -07002716 // special case for mmap capture: if an input IO handle is specified, we reuse this input if
2717 // possible
2718 if ((flags & AUDIO_INPUT_FLAG_MMAP_NOIRQ) == AUDIO_INPUT_FLAG_MMAP_NOIRQ &&
2719 *input != AUDIO_IO_HANDLE_NONE) {
2720 ssize_t index = mInputs.indexOfKey(*input);
2721 if (index < 0) {
2722 ALOGW("getInputForAttr() unknown MMAP input %d", *input);
2723 status = BAD_VALUE;
2724 goto error;
2725 }
2726 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(index);
Eric Laurent8f42ea12018-08-08 09:08:25 -07002727 RecordClientVector clients = inputDesc->getClientsForSession(session);
2728 if (clients.size() == 0) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002729 ALOGW("getInputForAttr() unknown session %d on input %d", session, *input);
2730 status = BAD_VALUE;
2731 goto error;
2732 }
2733 // For MMAP mode, the first call to getInputForAttr() is made on behalf of audioflinger.
2734 // The second call is for the first active client and sets the UID. Any further call
Eric Laurent331679c2018-04-16 17:03:16 -07002735 // corresponds to a new client and is only permitted from the same UID.
2736 // If the first UID is silenced, allow a new UID connection and replace with new UID
Eric Laurent8f42ea12018-08-08 09:08:25 -07002737 if (clients.size() > 1) {
2738 for (const auto& client : clients) {
2739 // The client map is ordered by key values (portId) and portIds are allocated
2740 // incrementaly. So the first client in this list is the one opened by audio flinger
2741 // when the mmap stream is created and should be ignored as it does not correspond
2742 // to an actual client
2743 if (client == *clients.cbegin()) {
2744 continue;
2745 }
2746 if (uid != client->uid() && !client->isSilenced()) {
2747 ALOGW("getInputForAttr() bad uid %d for client %d uid %d",
2748 uid, client->portId(), client->uid());
2749 status = INVALID_OPERATION;
2750 goto error;
2751 }
Eric Laurent331679c2018-04-16 17:03:16 -07002752 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002753 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002754 *inputType = API_INPUT_LEGACY;
François Gaffie11d30102018-11-02 16:09:09 +01002755 device = inputDesc->getDevice();
Eric Laurentad2e7b92017-09-14 20:06:42 -07002756
Eric Laurentfecbceb2021-02-09 14:46:43 +01002757 ALOGV("%s reusing MMAP input %d for session %d", __FUNCTION__, *input, session);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002758 goto exit;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002759 }
2760
2761 *input = AUDIO_IO_HANDLE_NONE;
2762 *inputType = API_INPUT_INVALID;
2763
Francois Gaffie716e1432019-01-14 16:58:59 +01002764 if (attributes.source == AUDIO_SOURCE_REMOTE_SUBMIX &&
Jan Sebechlebskybc56bcd2022-09-26 13:15:19 +02002765 extractAddressFromAudioAttributes(attributes).has_value()) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002766 status = mPolicyMixes.getInputMixForAttr(attributes, &policyMix);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002767 if (status != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07002768 ALOGW("%s could not find input mix for attr %s",
2769 __func__, toString(attributes).c_str());
Eric Laurentad2e7b92017-09-14 20:06:42 -07002770 goto error;
François Gaffie036e1e92015-03-19 10:16:24 +01002771 }
jiabinc1de2df2019-05-07 14:26:40 -07002772 device = mAvailableInputDevices.getDevice(AUDIO_DEVICE_IN_REMOTE_SUBMIX,
2773 String8(attr->tags + strlen("addr=")),
2774 AUDIO_FORMAT_DEFAULT);
2775 if (device == nullptr) {
Kevin Rocard04ed0462019-05-02 17:53:24 -07002776 ALOGW("%s could not find in Remote Submix device for source %d, tags %s",
jiabinc1de2df2019-05-07 14:26:40 -07002777 __func__, attributes.source, attributes.tags);
2778 status = BAD_VALUE;
2779 goto error;
2780 }
2781
Kevin Rocard25f9b052019-02-27 15:08:54 -08002782 if (is_mix_loopback_render(policyMix->mRouteFlags)) {
2783 *inputType = API_INPUT_MIX_PUBLIC_CAPTURE_PLAYBACK;
2784 } else {
2785 *inputType = API_INPUT_MIX_EXT_POLICY_REROUTE;
2786 }
Eric Laurent275e8e92014-11-30 15:14:47 -08002787 } else {
François Gaffie11d30102018-11-02 16:09:09 +01002788 if (explicitRoutingDevice != nullptr) {
2789 device = explicitRoutingDevice;
Eric Laurent97ac8712018-07-27 18:59:02 -07002790 } else {
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01002791 // Prevent from storing invalid requested device id in clients
2792 requestedDeviceId = AUDIO_PORT_HANDLE_NONE;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02002793 device = mEngine->getInputDeviceForAttributes(attributes, uid, session, &policyMix);
yuanjiahsu4069d5d2021-04-19 07:54:27 +08002794 ALOGV_IF(device != nullptr, "%s found device type is 0x%X",
2795 __FUNCTION__, device->type());
Eric Laurent97ac8712018-07-27 18:59:02 -07002796 }
François Gaffie11d30102018-11-02 16:09:09 +01002797 if (device == nullptr) {
Francois Gaffie716e1432019-01-14 16:58:59 +01002798 ALOGW("getInputForAttr() could not find device for source %d", attributes.source);
Eric Laurentad2e7b92017-09-14 20:06:42 -07002799 status = BAD_VALUE;
2800 goto error;
Eric Laurent275e8e92014-11-30 15:14:47 -08002801 }
Alden DSouzab7d20782021-02-08 08:51:42 -08002802 if (device->type() == AUDIO_DEVICE_IN_ECHO_REFERENCE) {
2803 *inputType = API_INPUT_MIX_CAPTURE;
2804 } else if (policyMix) {
François Gaffie11d30102018-11-02 16:09:09 +01002805 ALOG_ASSERT(policyMix->mMixType == MIX_TYPE_RECORDERS, "Invalid Mix Type");
2806 // there is an external policy, but this input is attached to a mix of recorders,
2807 // meaning it receives audio injected into the framework, so the recorder doesn't
2808 // know about it and is therefore considered "legacy"
2809 *inputType = API_INPUT_LEGACY;
2810 } else if (audio_is_remote_submix_device(device->type())) {
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002811 *inputType = API_INPUT_MIX_CAPTURE;
François Gaffie11d30102018-11-02 16:09:09 +01002812 } else if (device->type() == AUDIO_DEVICE_IN_TELEPHONY_RX) {
Eric Laurent82db2692015-08-07 13:59:42 -07002813 *inputType = API_INPUT_TELEPHONY_RX;
Jean-Michel Trivi97bb33f2014-12-12 16:23:43 -08002814 } else {
2815 *inputType = API_INPUT_LEGACY;
Eric Laurentc722f302014-12-10 11:21:49 -08002816 }
Ravi Kumar Alamandab367f5b2015-08-25 08:21:37 -07002817
Eric Laurent599c7582015-12-07 18:05:55 -08002818 }
2819
François Gaffiec005e562018-11-06 15:04:49 +01002820 *input = getInputForDevice(device, session, attributes, config, flags, policyMix);
Eric Laurent599c7582015-12-07 18:05:55 -08002821 if (*input == AUDIO_IO_HANDLE_NONE) {
Eric Laurentad2e7b92017-09-14 20:06:42 -07002822 status = INVALID_OPERATION;
jiabinf1c73972022-04-14 16:28:52 -07002823 AudioProfileVector profiles;
2824 status_t ret = getProfilesForDevices(
2825 DeviceVector(device), profiles, flags, true /*isInput*/);
2826 if (ret == NO_ERROR && !profiles.empty()) {
Robert Wub98ff1b2023-06-15 22:53:58 +00002827 const auto channels = profiles[0]->getChannels();
2828 if (!channels.empty() && (channels.find(config->channel_mask) == channels.end())) {
2829 config->channel_mask = *channels.begin();
2830 }
2831 const auto sampleRates = profiles[0]->getSampleRates();
2832 if (!sampleRates.empty() &&
2833 (sampleRates.find(config->sample_rate) == sampleRates.end())) {
2834 config->sample_rate = *sampleRates.begin();
2835 }
jiabinf1c73972022-04-14 16:28:52 -07002836 config->format = profiles[0]->getFormat();
2837 }
Eric Laurentad2e7b92017-09-14 20:06:42 -07002838 goto error;
Eric Laurent599c7582015-12-07 18:05:55 -08002839 }
Eric Laurent20b9ef02016-12-05 11:03:16 -08002840
Eric Laurent8f42ea12018-08-08 09:08:25 -07002841exit:
2842
François Gaffiec005e562018-11-06 15:04:49 +01002843 *selectedDeviceId = mAvailableInputDevices.contains(device) ?
2844 device->getId() : AUDIO_PORT_HANDLE_NONE;
Eric Laurent2ac76942017-06-22 17:17:09 -07002845
Francois Gaffie716e1432019-01-14 16:58:59 +01002846 isSoundTrigger = attributes.source == AUDIO_SOURCE_HOTWORD &&
Carter Hsud0cce2e2019-05-03 17:36:28 +08002847 mSoundTriggerSessions.indexOfKey(session) >= 0;
jiabin4ef93452019-09-10 14:29:54 -07002848 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurent8f42ea12018-08-08 09:08:25 -07002849
Mikhail Naganov2996f672019-04-18 12:29:59 -07002850 clientDesc = new RecordClientDescriptor(*portId, riid, uid, session, attributes, *config,
Francois Gaffie716e1432019-01-14 16:58:59 +01002851 requestedDeviceId, attributes.source, flags,
2852 isSoundTrigger);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002853 inputDesc = mInputs.valueFor(*input);
François Gaffie1b4753e2023-02-06 10:36:33 +01002854 // Move (if found) effect for the client session to its input
2855 mEffects.moveEffectsForIo(session, *input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07002856 inputDesc->addClient(clientDesc);
Eric Laurent8fc147b2018-07-22 19:13:55 -07002857
2858 ALOGV("getInputForAttr() returns input %d type %d selectedDeviceId %d for port ID %d",
2859 *input, *inputType, *selectedDeviceId, *portId);
Eric Laurent2ac76942017-06-22 17:17:09 -07002860
Eric Laurent599c7582015-12-07 18:05:55 -08002861 return NO_ERROR;
Eric Laurentad2e7b92017-09-14 20:06:42 -07002862
2863error:
Eric Laurentad2e7b92017-09-14 20:06:42 -07002864 return status;
Eric Laurent599c7582015-12-07 18:05:55 -08002865}
2866
2867
François Gaffie11d30102018-11-02 16:09:09 +01002868audio_io_handle_t AudioPolicyManager::getInputForDevice(const sp<DeviceDescriptor> &device,
Eric Laurent599c7582015-12-07 18:05:55 -08002869 audio_session_t session,
François Gaffiec005e562018-11-06 15:04:49 +01002870 const audio_attributes_t &attributes,
jiabinf1c73972022-04-14 16:28:52 -07002871 audio_config_base_t *config,
Eric Laurent599c7582015-12-07 18:05:55 -08002872 audio_input_flags_t flags,
Mikhail Naganovbfac5832019-03-05 16:55:28 -08002873 const sp<AudioPolicyMix> &policyMix)
Eric Laurent599c7582015-12-07 18:05:55 -08002874{
2875 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
François Gaffiec005e562018-11-06 15:04:49 +01002876 audio_source_t halInputSource = attributes.source;
Eric Laurent599c7582015-12-07 18:05:55 -08002877 bool isSoundTrigger = false;
2878
François Gaffiec005e562018-11-06 15:04:49 +01002879 if (attributes.source == AUDIO_SOURCE_HOTWORD) {
Eric Laurent599c7582015-12-07 18:05:55 -08002880 ssize_t index = mSoundTriggerSessions.indexOfKey(session);
2881 if (index >= 0) {
2882 input = mSoundTriggerSessions.valueFor(session);
2883 isSoundTrigger = true;
2884 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_HW_HOTWORD);
2885 ALOGV("SoundTrigger capture on session %d input %d", session, input);
2886 } else {
2887 halInputSource = AUDIO_SOURCE_VOICE_RECOGNITION;
Eric Laurent5dbe4712014-09-19 19:04:57 -07002888 }
François Gaffiec005e562018-11-06 15:04:49 +01002889 } else if (attributes.source == AUDIO_SOURCE_VOICE_COMMUNICATION &&
Eric Laurentfe231122017-11-17 17:48:06 -08002890 audio_is_linear_pcm(config->format)) {
Haynes Mathew George851d3ff2017-06-19 20:01:57 -07002891 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_VOIP_TX);
Eric Laurent5dbe4712014-09-19 19:04:57 -07002892 }
2893
Carter Hsua3abb402021-10-26 11:11:20 +08002894 if (attributes.source == AUDIO_SOURCE_ULTRASOUND) {
2895 flags = (audio_input_flags_t)(flags | AUDIO_INPUT_FLAG_ULTRASOUND);
2896 }
2897
Eric Laurentfe231122017-11-17 17:48:06 -08002898 // sampling rate and flags may be updated by getInputProfile
2899 uint32_t profileSamplingRate = (config->sample_rate == 0) ?
2900 SAMPLE_RATE_HZ_DEFAULT : config->sample_rate;
jiabin2fd710d2022-05-02 23:20:22 +00002901 audio_format_t profileFormat = config->format;
Eric Laurentfe231122017-11-17 17:48:06 -08002902 audio_channel_mask_t profileChannelMask = config->channel_mask;
Andy Hungf129b032015-04-07 13:45:50 -07002903 audio_input_flags_t profileFlags = flags;
jiabin2fd710d2022-05-02 23:20:22 +00002904 // find a compatible input profile (not necessarily identical in parameters)
2905 sp<IOProfile> profile = getInputProfile(
2906 device, profileSamplingRate, profileFormat, profileChannelMask, profileFlags);
2907 if (profile == nullptr) {
2908 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07002909 }
jiabin2fd710d2022-05-02 23:20:22 +00002910
Glenn Kasten05ddca52016-02-11 08:17:12 -08002911 // Pick input sampling rate if not specified by client
Eric Laurentfe231122017-11-17 17:48:06 -08002912 uint32_t samplingRate = config->sample_rate;
Glenn Kasten05ddca52016-02-11 08:17:12 -08002913 if (samplingRate == 0) {
2914 samplingRate = profileSamplingRate;
2915 }
Eric Laurente552edb2014-03-10 17:42:56 -07002916
Eric Laurent322b4d22015-04-03 15:57:54 -07002917 if (profile->getModuleHandle() == 0) {
2918 ALOGE("getInputForAttr(): HW module %s not opened", profile->getModuleName());
Eric Laurent599c7582015-12-07 18:05:55 -08002919 return input;
Eric Laurentcf2c0212014-07-25 16:20:43 -07002920 }
2921
Eric Laurentec376dc2021-04-08 20:41:22 +02002922 // Reuse an already opened input if a client with the same session ID already exists
2923 // on that input
2924 for (size_t i = 0; i < mInputs.size(); i++) {
2925 sp <AudioInputDescriptor> desc = mInputs.valueAt(i);
2926 if (desc->mProfile != profile) {
2927 continue;
2928 }
2929 RecordClientVector clients = desc->clientsList();
2930 for (const auto &client : clients) {
2931 if (session == client->session()) {
2932 return desc->mIoHandle;
2933 }
2934 }
2935 }
2936
Eric Laurent3974e3b2017-12-07 17:58:43 -08002937 if (!profile->canOpenNewIo()) {
Eric Laurent4eb58f12018-12-07 16:41:02 -08002938 for (size_t i = 0; i < mInputs.size(); ) {
Eric Laurentc529cf62020-04-17 18:19:10 -07002939 sp<AudioInputDescriptor> desc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08002940 if (desc->mProfile != profile) {
Carter Hsu9a645a92019-05-15 12:15:32 +08002941 i++;
Eric Laurent4eb58f12018-12-07 16:41:02 -08002942 continue;
2943 }
2944 // if sound trigger, reuse input if used by other sound trigger on same session
2945 // else
2946 // reuse input if active client app is not in IDLE state
2947 //
2948 RecordClientVector clients = desc->clientsList();
2949 bool doClose = false;
2950 for (const auto& client : clients) {
2951 if (isSoundTrigger != client->isSoundTrigger()) {
2952 continue;
2953 }
2954 if (client->isSoundTrigger()) {
2955 if (session == client->session()) {
2956 return desc->mIoHandle;
2957 }
2958 continue;
2959 }
2960 if (client->active() && client->appState() != APP_STATE_IDLE) {
2961 return desc->mIoHandle;
2962 }
2963 doClose = true;
2964 }
2965 if (doClose) {
2966 closeInput(desc->mIoHandle);
2967 } else {
2968 i++;
2969 }
2970 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08002971 }
2972
Eric Laurentfe231122017-11-17 17:48:06 -08002973 sp<AudioInputDescriptor> inputDesc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07002974
Eric Laurentfe231122017-11-17 17:48:06 -08002975 audio_config_t lConfig = AUDIO_CONFIG_INITIALIZER;
2976 lConfig.sample_rate = profileSamplingRate;
2977 lConfig.channel_mask = profileChannelMask;
2978 lConfig.format = profileFormat;
Eric Laurente3014102017-05-03 11:15:43 -07002979
François Gaffie11d30102018-11-02 16:09:09 +01002980 status_t status = inputDesc->open(&lConfig, device, halInputSource, profileFlags, &input);
Eric Laurentcf2c0212014-07-25 16:20:43 -07002981
2982 // only accept input with the exact requested set of parameters
Eric Laurent599c7582015-12-07 18:05:55 -08002983 if (status != NO_ERROR || input == AUDIO_IO_HANDLE_NONE ||
Eric Laurentfe231122017-11-17 17:48:06 -08002984 (profileSamplingRate != lConfig.sample_rate) ||
2985 !audio_formats_match(profileFormat, lConfig.format) ||
2986 (profileChannelMask != lConfig.channel_mask)) {
2987 ALOGW("getInputForAttr() failed opening input: sampling rate %d"
Glenn Kasten49f36ba2017-12-06 13:02:02 -08002988 ", format %#x, channel mask %#x",
Eric Laurentfe231122017-11-17 17:48:06 -08002989 profileSamplingRate, profileFormat, profileChannelMask);
Eric Laurent599c7582015-12-07 18:05:55 -08002990 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentfe231122017-11-17 17:48:06 -08002991 inputDesc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07002992 }
Eric Laurent599c7582015-12-07 18:05:55 -08002993 return AUDIO_IO_HANDLE_NONE;
Eric Laurente552edb2014-03-10 17:42:56 -07002994 }
2995
Eric Laurentc722f302014-12-10 11:21:49 -08002996 inputDesc->mPolicyMix = policyMix;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07002997
Eric Laurent599c7582015-12-07 18:05:55 -08002998 addInput(input, inputDesc);
Eric Laurentb52c1522014-05-20 11:27:36 -07002999 mpClientInterface->onAudioPortListUpdate();
Paul McLean466dc8e2015-04-17 13:15:36 -06003000
Eric Laurent599c7582015-12-07 18:05:55 -08003001 return input;
Eric Laurente552edb2014-03-10 17:42:56 -07003002}
3003
Eric Laurent4eb58f12018-12-07 16:41:02 -08003004status_t AudioPolicyManager::startInput(audio_port_handle_t portId)
Eric Laurentbb948092017-01-23 18:33:30 -08003005{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003006 ALOGV("%s portId %d", __FUNCTION__, portId);
3007
3008 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3009 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003010 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurentd52a28c2020-08-21 17:10:39 -07003011 return DEAD_OBJECT;
Eric Laurent8fc147b2018-07-22 19:13:55 -07003012 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003013 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003014 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003015 if (client->active()) {
3016 ALOGW("%s input %d client %d already started", __FUNCTION__, input, client->portId());
3017 return INVALID_OPERATION;
Eric Laurent4dc68062014-07-28 17:26:49 -07003018 }
3019
Eric Laurent8f42ea12018-08-08 09:08:25 -07003020 audio_session_t session = client->session();
3021
Eric Laurent4eb58f12018-12-07 16:41:02 -08003022 ALOGV("%s input:%d, session:%d)", __FUNCTION__, input, session);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003023
Eric Laurent4eb58f12018-12-07 16:41:02 -08003024 Vector<sp<AudioInputDescriptor>> activeInputs = mInputs.getActiveInputs();
Eric Laurent74708e72017-04-07 17:13:42 -07003025
Eric Laurent4eb58f12018-12-07 16:41:02 -08003026 status_t status = inputDesc->start();
3027 if (status != NO_ERROR) {
3028 return status;
Eric Laurent74708e72017-04-07 17:13:42 -07003029 }
Eric Laurente552edb2014-03-10 17:42:56 -07003030
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003031 // increment activity count before calling getNewInputDevice() below as only active sessions
Eric Laurent313d1e72016-01-29 09:56:57 -08003032 // are considered for device selection
Eric Laurent8f42ea12018-08-08 09:08:25 -07003033 inputDesc->setClientActive(client, true);
Eric Laurent313d1e72016-01-29 09:56:57 -08003034
Eric Laurent8f42ea12018-08-08 09:08:25 -07003035 // indicate active capture to sound trigger service if starting capture from a mic on
3036 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003037 sp<DeviceDescriptor> device = getNewInputDevice(inputDesc);
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003038 if (device != nullptr) {
3039 status = setInputDevice(input, device, true /* force */);
3040 } else {
3041 ALOGW("%s no new input device can be found for descriptor %d",
3042 __FUNCTION__, inputDesc->getId());
3043 status = BAD_VALUE;
3044 }
Eric Laurente552edb2014-03-10 17:42:56 -07003045
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003046 if (status == NO_ERROR && inputDesc->activeCount() == 1) {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003047 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003048 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003049 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003050 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3051 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003052 MIX_STATE_MIXING);
Eric Laurent733ce942017-12-07 12:18:25 -08003053 }
Eric Laurent3974e3b2017-12-07 17:58:43 -08003054
François Gaffie11d30102018-11-02 16:09:09 +01003055 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3056 if (primaryInputDevices.contains(device) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003057 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 1) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003058 mpClientInterface->setSoundTriggerCaptureState(true);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003059 }
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003060
Eric Laurent8f42ea12018-08-08 09:08:25 -07003061 // automatically enable the remote submix output when input is started if not
3062 // used by a policy mix of type MIX_TYPE_RECORDERS
3063 // For remote submix (a virtual device), we open only one input per capture request.
François Gaffie11d30102018-11-02 16:09:09 +01003064 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003065 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003066 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003067 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003068 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3069 address = policyMix->mDeviceAddress;
Jean-Michel Trivieb6421d2016-03-17 12:32:52 -07003070 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003071 if (address != "") {
3072 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3073 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003074 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurentc722f302014-12-10 11:21:49 -08003075 }
Glenn Kasten74a8e252014-07-24 14:09:55 -07003076 }
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003077 } else if (status != NO_ERROR) {
3078 // Restore client activity state.
3079 inputDesc->setClientActive(client, false);
3080 inputDesc->stop();
Eric Laurente552edb2014-03-10 17:42:56 -07003081 }
3082
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003083 ALOGV("%s input %d source = %d status = %d exit",
3084 __FUNCTION__, input, client->source(), status);
Eric Laurente552edb2014-03-10 17:42:56 -07003085
Mikhail Naganov480ffee2019-07-01 15:07:19 -07003086 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07003087}
3088
Eric Laurent8fc147b2018-07-22 19:13:55 -07003089status_t AudioPolicyManager::stopInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003090{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003091 ALOGV("%s portId %d", __FUNCTION__, portId);
3092
3093 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3094 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003095 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003096 return BAD_VALUE;
3097 }
Eric Laurent8fc147b2018-07-22 19:13:55 -07003098 audio_io_handle_t input = inputDesc->mIoHandle;
Andy Hung39efb7a2018-09-26 15:39:28 -07003099 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003100 if (!client->active()) {
3101 ALOGW("%s input %d client %d already stopped", __FUNCTION__, input, client->portId());
Eric Laurente552edb2014-03-10 17:42:56 -07003102 return INVALID_OPERATION;
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003103 }
Carter Hsue6139d52021-07-08 10:30:20 +08003104 auto old_source = inputDesc->source();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003105 inputDesc->setClientActive(client, false);
Paul McLean466dc8e2015-04-17 13:15:36 -06003106
Eric Laurent8f42ea12018-08-08 09:08:25 -07003107 inputDesc->stop();
3108 if (inputDesc->isActive()) {
Carter Hsue6139d52021-07-08 10:30:20 +08003109 auto current_source = inputDesc->source();
3110 setInputDevice(input, getNewInputDevice(inputDesc),
3111 old_source != current_source /* force */);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003112 } else {
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003113 sp<AudioPolicyMix> policyMix = inputDesc->mPolicyMix.promote();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003114 // if input maps to a dynamic policy with an activity listener, notify of state change
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003115 if ((policyMix != nullptr)
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003116 && ((policyMix->mCbFlags & AudioMix::kCbFlagNotifyActivity) != 0)) {
3117 mpClientInterface->onDynamicPolicyMixStateUpdate(policyMix->mDeviceAddress,
Eric Laurent8f42ea12018-08-08 09:08:25 -07003118 MIX_STATE_IDLE);
Eric Laurent84332aa2016-01-28 22:19:18 +00003119 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003120
3121 // automatically disable the remote submix output when input is stopped if not
3122 // used by a policy mix of type MIX_TYPE_RECORDERS
François Gaffie11d30102018-11-02 16:09:09 +01003123 if (audio_is_remote_submix_device(inputDesc->getDeviceType())) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003124 String8 address = String8("");
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08003125 if (policyMix == nullptr) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003126 address = String8("0");
Mikhail Naganovbfac5832019-03-05 16:55:28 -08003127 } else if (policyMix->mMixType == MIX_TYPE_PLAYERS) {
3128 address = policyMix->mDeviceAddress;
Eric Laurent8f42ea12018-08-08 09:08:25 -07003129 }
3130 if (address != "") {
3131 setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_REMOTE_SUBMIX,
3132 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08003133 address, "remote-submix", AUDIO_FORMAT_DEFAULT);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003134 }
3135 }
Eric Laurent8f42ea12018-08-08 09:08:25 -07003136 resetInputDevice(input);
3137
3138 // indicate inactive capture to sound trigger service if stopping capture from a mic on
3139 // primary HW module
François Gaffie11d30102018-11-02 16:09:09 +01003140 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
3141 if (primaryInputDevices.contains(inputDesc->getDevice()) &&
Eric Laurent8f42ea12018-08-08 09:08:25 -07003142 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07003143 mpClientInterface->setSoundTriggerCaptureState(false);
Eric Laurent8f42ea12018-08-08 09:08:25 -07003144 }
3145 inputDesc->clearPreemptedSessions();
Eric Laurente552edb2014-03-10 17:42:56 -07003146 }
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003147 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07003148}
3149
Eric Laurent8fc147b2018-07-22 19:13:55 -07003150void AudioPolicyManager::releaseInput(audio_port_handle_t portId)
Eric Laurente552edb2014-03-10 17:42:56 -07003151{
Eric Laurent8fc147b2018-07-22 19:13:55 -07003152 ALOGV("%s portId %d", __FUNCTION__, portId);
3153
3154 sp<AudioInputDescriptor> inputDesc = mInputs.getInputForClient(portId);
3155 if (inputDesc == 0) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003156 ALOGW("%s no input for client %d", __FUNCTION__, portId);
Eric Laurente552edb2014-03-10 17:42:56 -07003157 return;
3158 }
Andy Hung39efb7a2018-09-26 15:39:28 -07003159 sp<RecordClientDescriptor> client = inputDesc->getClient(portId);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003160 audio_io_handle_t input = inputDesc->mIoHandle;
3161
Eric Laurent8f42ea12018-08-08 09:08:25 -07003162 ALOGV("%s %d", __FUNCTION__, input);
Paul McLean466dc8e2015-04-17 13:15:36 -06003163
Andy Hung39efb7a2018-09-26 15:39:28 -07003164 inputDesc->removeClient(portId);
François Gaffie1b4753e2023-02-06 10:36:33 +01003165 mEffects.putOrphanEffects(client->session(), input, &mInputs, mpClientInterface);
Andy Hung39efb7a2018-09-26 15:39:28 -07003166 if (inputDesc->getClientCount() > 0) {
3167 ALOGV("%s(%d) %zu clients remaining", __func__, portId, inputDesc->getClientCount());
Glenn Kasten6a8ab052014-07-24 14:08:35 -07003168 return;
3169 }
3170
Eric Laurent05b90f82014-08-27 15:32:29 -07003171 closeInput(input);
Eric Laurentb52c1522014-05-20 11:27:36 -07003172 mpClientInterface->onAudioPortListUpdate();
Eric Laurent8f42ea12018-08-08 09:08:25 -07003173 ALOGV("%s exit", __FUNCTION__);
Eric Laurente552edb2014-03-10 17:42:56 -07003174}
3175
Eric Laurent8f42ea12018-08-08 09:08:25 -07003176void AudioPolicyManager::closeActiveClients(const sp<AudioInputDescriptor>& input)
Eric Laurent8fc147b2018-07-22 19:13:55 -07003177{
Eric Laurent8f42ea12018-08-08 09:08:25 -07003178 RecordClientVector clients = input->clientsList(true);
Eric Laurent8fc147b2018-07-22 19:13:55 -07003179
3180 for (const auto& client : clients) {
Eric Laurent8f42ea12018-08-08 09:08:25 -07003181 closeClient(client->portId());
Eric Laurent8fc147b2018-07-22 19:13:55 -07003182 }
3183}
3184
Eric Laurent8f42ea12018-08-08 09:08:25 -07003185void AudioPolicyManager::closeClient(audio_port_handle_t portId)
3186{
3187 stopInput(portId);
3188 releaseInput(portId);
3189}
Eric Laurent8fc147b2018-07-22 19:13:55 -07003190
Eric Laurent0dd51852019-04-19 18:18:58 -07003191void AudioPolicyManager::checkCloseInputs() {
3192 // After connecting or disconnecting an input device, close input if:
3193 // - it has no client (was just opened to check profile) OR
3194 // - none of its supported devices are connected anymore OR
3195 // - one of its clients cannot be routed to one of its supported
3196 // devices anymore. Otherwise update device selection
3197 std::vector<audio_io_handle_t> inputsToClose;
3198 for (size_t i = 0; i < mInputs.size(); i++) {
3199 const sp<AudioInputDescriptor> input = mInputs.valueAt(i);
3200 if (input->clientsList().size() == 0
Eric Laurent85732f42020-03-19 11:31:10 -07003201 || !mAvailableInputDevices.containsAtLeastOne(input->supportedDevices())) {
Eric Laurent0dd51852019-04-19 18:18:58 -07003202 inputsToClose.push_back(mInputs.keyAt(i));
3203 } else {
3204 bool close = false;
3205 for (const auto& client : input->clientsList()) {
3206 sp<DeviceDescriptor> device =
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02003207 mEngine->getInputDeviceForAttributes(client->attributes(), client->uid(),
3208 client->session());
Eric Laurent0dd51852019-04-19 18:18:58 -07003209 if (!input->supportedDevices().contains(device)) {
3210 close = true;
3211 break;
3212 }
3213 }
3214 if (close) {
3215 inputsToClose.push_back(mInputs.keyAt(i));
3216 } else {
3217 setInputDevice(input->mIoHandle, getNewInputDevice(input));
3218 }
3219 }
3220 }
3221
3222 for (const audio_io_handle_t handle : inputsToClose) {
3223 ALOGV("%s closing input %d", __func__, handle);
3224 closeInput(handle);
Eric Laurent05b90f82014-08-27 15:32:29 -07003225 }
Eric Laurentd4692962014-05-05 18:13:44 -07003226}
3227
François Gaffie251c7f02018-11-07 10:41:08 +01003228void AudioPolicyManager::initStreamVolume(audio_stream_type_t stream, int indexMin, int indexMax)
Eric Laurente552edb2014-03-10 17:42:56 -07003229{
3230 ALOGV("initStreamVolume() stream %d, min %d, max %d", stream , indexMin, indexMax);
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08003231 if (indexMin < 0 || indexMax < 0) {
3232 ALOGE("%s for stream %d: invalid min %d or max %d", __func__, stream , indexMin, indexMax);
3233 return;
3234 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003235 getVolumeCurves(stream).initVolume(indexMin, indexMax);
Eric Laurent28d09f02016-03-08 10:43:05 -08003236
3237 // initialize other private stream volumes which follow this one
Eric Laurent794fde22016-03-11 09:50:45 -08003238 for (int curStream = 0; curStream < AUDIO_STREAM_FOR_POLICY_CNT; curStream++) {
3239 if (!streamsMatchForvolume(stream, (audio_stream_type_t)curStream)) {
Eric Laurent28d09f02016-03-08 10:43:05 -08003240 continue;
3241 }
Eric Laurentf5aa58d2019-02-22 18:20:11 -08003242 getVolumeCurves((audio_stream_type_t)curStream).initVolume(indexMin, indexMax);
Eric Laurent223fd5c2014-11-11 13:43:36 -08003243 }
Eric Laurente552edb2014-03-10 17:42:56 -07003244}
3245
Eric Laurente0720872014-03-11 09:30:41 -07003246status_t AudioPolicyManager::setStreamVolumeIndex(audio_stream_type_t stream,
François Gaffie53615e22015-03-19 09:24:12 +01003247 int index,
3248 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003249{
François Gaffieaaac0fd2018-11-22 17:56:39 +01003250 auto attributes = mEngine->getAttributesForStreamType(stream);
Eric Laurent242a9f82020-03-23 15:57:04 -07003251 if (attributes == AUDIO_ATTRIBUTES_INITIALIZER) {
3252 ALOGW("%s: no group for stream %s, bailing out", __func__, toString(stream).c_str());
3253 return NO_ERROR;
3254 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003255 ALOGV("%s: stream %s attributes=%s", __func__,
3256 toString(stream).c_str(), toString(attributes).c_str());
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003257 return setVolumeIndexForAttributes(attributes, index, device);
Eric Laurente552edb2014-03-10 17:42:56 -07003258}
3259
Eric Laurente0720872014-03-11 09:30:41 -07003260status_t AudioPolicyManager::getStreamVolumeIndex(audio_stream_type_t stream,
François Gaffieaaac0fd2018-11-22 17:56:39 +01003261 int *index,
3262 audio_devices_t device)
Eric Laurente552edb2014-03-10 17:42:56 -07003263{
François Gaffiec005e562018-11-06 15:04:49 +01003264 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3265 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003266 DeviceTypeSet deviceTypes = {device};
Eric Laurent5a2b6292016-04-14 18:05:57 -07003267 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
jiabin9a3361e2019-10-01 09:38:30 -07003268 deviceTypes = mEngine->getOutputDevicesForStream(
3269 stream, true /*fromCache*/).types();
Eric Laurente552edb2014-03-10 17:42:56 -07003270 }
jiabin9a3361e2019-10-01 09:38:30 -07003271 return getVolumeIndex(getVolumeCurves(stream), *index, deviceTypes);
Eric Laurente552edb2014-03-10 17:42:56 -07003272}
3273
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003274status_t AudioPolicyManager::setVolumeIndexForAttributes(const audio_attributes_t &attributes,
François Gaffiecfe17322018-11-07 13:41:29 +01003275 int index,
3276 audio_devices_t device)
3277{
3278 // Get Volume group matching the Audio Attributes
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003279 auto group = mEngine->getVolumeGroupForAttributes(attributes);
3280 if (group == VOLUME_GROUP_NONE) {
3281 ALOGD("%s: no group matching with %s", __FUNCTION__, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003282 return BAD_VALUE;
3283 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003284 ALOGV("%s: group %d matching with %s", __FUNCTION__, group, toString(attributes).c_str());
François Gaffiecfe17322018-11-07 13:41:29 +01003285 status_t status = NO_ERROR;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003286 IVolumeCurves &curves = getVolumeCurves(attributes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003287 VolumeSource vs = toVolumeSource(group);
Eric Laurentf9cccec2022-11-16 19:12:00 +01003288 // AUDIO_STREAM_BLUETOOTH_SCO is only used for volume control so we remap
3289 // to AUDIO_STREAM_VOICE_CALL to match with relevant playback activity
3290 VolumeSource activityVs = (vs == toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false)) ?
3291 toVolumeSource(AUDIO_STREAM_VOICE_CALL, false) : vs;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003292 product_strategy_t strategy = mEngine->getProductStrategyForAttributes(attributes);
3293
3294 status = setVolumeCurveIndex(index, device, curves);
3295 if (status != NO_ERROR) {
3296 ALOGE("%s failed to set curve index for group %d device 0x%X", __func__, group, device);
3297 return status;
3298 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003299
jiabin9a3361e2019-10-01 09:38:30 -07003300 DeviceTypeSet curSrcDevices;
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003301 auto curCurvAttrs = curves.getAttributes();
3302 if (!curCurvAttrs.empty() && curCurvAttrs.front() != defaultAttr) {
3303 auto attr = curCurvAttrs.front();
jiabin9a3361e2019-10-01 09:38:30 -07003304 curSrcDevices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003305 } else if (!curves.getStreamTypes().empty()) {
3306 auto stream = curves.getStreamTypes().front();
jiabin9a3361e2019-10-01 09:38:30 -07003307 curSrcDevices = mEngine->getOutputDevicesForStream(stream, false).types();
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003308 } else {
3309 ALOGE("%s: Invalid src %d: no valid attributes nor stream",__func__, vs);
3310 return BAD_VALUE;
3311 }
jiabin9a3361e2019-10-01 09:38:30 -07003312 audio_devices_t curSrcDevice = Volume::getDeviceForVolume(curSrcDevices);
3313 resetDeviceTypes(curSrcDevices, curSrcDevice);
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01003314
François Gaffiecfe17322018-11-07 13:41:29 +01003315 // update volume on all outputs and streams matching the following:
3316 // - The requested stream (or a stream matching for volume control) is active on the output
3317 // - The device (or devices) selected by the engine for this stream includes
3318 // the requested device
3319 // - For non default requested device, currently selected device on the output is either the
3320 // requested device or one of the devices selected by the engine for this stream
3321 // - For default requested device (AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME), apply volume only if
3322 // no specific device volume value exists for currently selected device.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003323 for (size_t i = 0; i < mOutputs.size(); i++) {
3324 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07003325 DeviceTypeSet curDevices = desc->devices().types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01003326
jiabin9a3361e2019-10-01 09:38:30 -07003327 if (curDevices.erase(AUDIO_DEVICE_OUT_SPEAKER_SAFE)) {
3328 curDevices.insert(AUDIO_DEVICE_OUT_SPEAKER);
Robert Lee5e66e792019-04-03 18:37:15 +08003329 }
Eric Laurentf9cccec2022-11-16 19:12:00 +01003330
3331 if (!(desc->isActive(activityVs) || isInCallOrScreening())) {
François Gaffieed91f582020-01-31 10:35:37 +01003332 continue;
3333 }
3334 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME &&
3335 curDevices.find(device) == curDevices.end()) {
3336 continue;
3337 }
3338 bool applyVolume = false;
3339 if (device != AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
3340 curSrcDevices.insert(device);
3341 applyVolume = (curSrcDevices.find(
3342 Volume::getDeviceForVolume(curDevices)) != curSrcDevices.end());
3343 } else {
3344 applyVolume = !curves.hasVolumeIndexForDevice(curSrcDevice);
3345 }
3346 if (!applyVolume) {
3347 continue; // next output
3348 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003349 // Inter / intra volume group priority management: Loop on strategies arranged by priority
3350 // If a higher priority strategy is active, and the output is routed to a device with a
3351 // HW Gain management, do not change the volume
François Gaffieaaac0fd2018-11-22 17:56:39 +01003352 if (desc->useHwGain()) {
François Gaffieed91f582020-01-31 10:35:37 +01003353 applyVolume = false;
Francois Gaffie593634d2021-06-22 13:31:31 +02003354 // If the volume source is active with higher priority source, ensure at least Sw Muted
3355 desc->setSwMute((index == 0), vs, curves.getStreamTypes(), curDevices, 0 /*delayMs*/);
François Gaffieaaac0fd2018-11-22 17:56:39 +01003356 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
3357 auto activeClients = desc->clientsList(true /*activeOnly*/, productStrategy,
3358 false /*preferredDevice*/);
3359 if (activeClients.empty()) {
3360 continue;
3361 }
3362 bool isPreempted = false;
3363 bool isHigherPriority = productStrategy < strategy;
3364 for (const auto &client : activeClients) {
Eric Laurentf9cccec2022-11-16 19:12:00 +01003365 if (isHigherPriority && (client->volumeSource() != activityVs)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003366 ALOGV("%s: Strategy=%d (\nrequester:\n"
3367 " group %d, volumeGroup=%d attributes=%s)\n"
3368 " higher priority source active:\n"
3369 " volumeGroup=%d attributes=%s) \n"
3370 " on output %zu, bailing out", __func__, productStrategy,
3371 group, group, toString(attributes).c_str(),
3372 client->volumeSource(), toString(client->attributes()).c_str(), i);
3373 applyVolume = false;
3374 isPreempted = true;
3375 break;
3376 }
3377 // However, continue for loop to ensure no higher prio clients running on output
Eric Laurentf9cccec2022-11-16 19:12:00 +01003378 if (client->volumeSource() == activityVs) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01003379 applyVolume = true;
3380 }
3381 }
3382 if (isPreempted || applyVolume) {
3383 break;
3384 }
3385 }
3386 if (!applyVolume) {
3387 continue; // next output
3388 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01003389 }
François Gaffieed91f582020-01-31 10:35:37 +01003390 //FIXME: workaround for truncated touch sounds
3391 // delayed volume change for system stream to be removed when the problem is
3392 // handled by system UI
3393 status_t volStatus = checkAndSetVolume(
3394 curves, vs, index, desc, curDevices,
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003395 ((vs == toVolumeSource(AUDIO_STREAM_SYSTEM, false))?
François Gaffieed91f582020-01-31 10:35:37 +01003396 TOUCH_SOUND_FIXED_DELAY_MS : 0));
3397 if (volStatus != NO_ERROR) {
3398 status = volStatus;
François Gaffieaaac0fd2018-11-22 17:56:39 +01003399 }
3400 }
François Gaffiecfe17322018-11-07 13:41:29 +01003401 mpClientInterface->onAudioVolumeGroupChanged(group, 0 /*flags*/);
3402 return status;
3403}
3404
François Gaffieaaac0fd2018-11-22 17:56:39 +01003405status_t AudioPolicyManager::setVolumeCurveIndex(int index,
François Gaffiecfe17322018-11-07 13:41:29 +01003406 audio_devices_t device,
3407 IVolumeCurves &volumeCurves)
3408{
3409 // VOICE_CALL stream has minVolumeIndex > 0 but can be muted directly by an
3410 // app that has MODIFY_PHONE_STATE permission.
François Gaffieaaac0fd2018-11-22 17:56:39 +01003411 bool hasVoice = hasVoiceStream(volumeCurves.getStreamTypes());
3412 if (((index < volumeCurves.getVolumeIndexMin()) && !(hasVoice && index == 0)) ||
François Gaffiecfe17322018-11-07 13:41:29 +01003413 (index > volumeCurves.getVolumeIndexMax())) {
3414 ALOGD("%s: wrong index %d min=%d max=%d", __FUNCTION__, index,
3415 volumeCurves.getVolumeIndexMin(), volumeCurves.getVolumeIndexMax());
3416 return BAD_VALUE;
3417 }
3418 if (!audio_is_output_device(device)) {
3419 return BAD_VALUE;
3420 }
3421
3422 // Force max volume if stream cannot be muted
3423 if (!volumeCurves.canBeMuted()) index = volumeCurves.getVolumeIndexMax();
3424
François Gaffieaaac0fd2018-11-22 17:56:39 +01003425 ALOGV("%s device %08x, index %d", __FUNCTION__ , device, index);
François Gaffiecfe17322018-11-07 13:41:29 +01003426 volumeCurves.addCurrentVolumeIndex(device, index);
3427 return NO_ERROR;
3428}
3429
3430status_t AudioPolicyManager::getVolumeIndexForAttributes(const audio_attributes_t &attr,
3431 int &index,
3432 audio_devices_t device)
3433{
3434 // if device is AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME, return volume for device selected for this
3435 // stream by the engine.
jiabin9a3361e2019-10-01 09:38:30 -07003436 DeviceTypeSet deviceTypes = {device};
François Gaffiecfe17322018-11-07 13:41:29 +01003437 if (device == AUDIO_DEVICE_OUT_DEFAULT_FOR_VOLUME) {
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003438 deviceTypes = mEngine->getOutputDevicesForAttributes(
jiabin9a3361e2019-10-01 09:38:30 -07003439 attr, nullptr, true /*fromCache*/).types();
François Gaffiecfe17322018-11-07 13:41:29 +01003440 }
jiabin9a3361e2019-10-01 09:38:30 -07003441 return getVolumeIndex(getVolumeCurves(attr), index, deviceTypes);
François Gaffiecfe17322018-11-07 13:41:29 +01003442}
3443
3444status_t AudioPolicyManager::getVolumeIndex(const IVolumeCurves &curves,
3445 int &index,
jiabin9a3361e2019-10-01 09:38:30 -07003446 const DeviceTypeSet& deviceTypes) const
François Gaffiecfe17322018-11-07 13:41:29 +01003447{
Mikhail Naganovbb990f22022-06-15 00:46:43 +00003448 if (!isSingleDeviceType(deviceTypes, audio_is_output_device)) {
François Gaffiecfe17322018-11-07 13:41:29 +01003449 return BAD_VALUE;
3450 }
jiabin9a3361e2019-10-01 09:38:30 -07003451 index = curves.getVolumeIndex(deviceTypes);
3452 ALOGV("%s: device %s index %d", __FUNCTION__, dumpDeviceTypes(deviceTypes).c_str(), index);
François Gaffiecfe17322018-11-07 13:41:29 +01003453 return NO_ERROR;
3454}
3455
3456status_t AudioPolicyManager::getMinVolumeIndexForAttributes(const audio_attributes_t &attr,
3457 int &index)
3458{
3459 index = getVolumeCurves(attr).getVolumeIndexMin();
3460 return NO_ERROR;
3461}
3462
3463status_t AudioPolicyManager::getMaxVolumeIndexForAttributes(const audio_attributes_t &attr,
3464 int &index)
3465{
3466 index = getVolumeCurves(attr).getVolumeIndexMax();
3467 return NO_ERROR;
3468}
3469
Eric Laurent36829f92017-04-07 19:04:42 -07003470audio_io_handle_t AudioPolicyManager::selectOutputForMusicEffects()
Eric Laurente552edb2014-03-10 17:42:56 -07003471{
3472 // select one output among several suitable for global effects.
3473 // The priority is as follows:
3474 // 1: An offloaded output. If the effect ends up not being offloadable,
3475 // AudioFlinger will invalidate the track and the offloaded output
3476 // will be closed causing the effect to be moved to a PCM output.
3477 // 2: A deep buffer output
Eric Laurent36829f92017-04-07 19:04:42 -07003478 // 3: The primary output
3479 // 4: the first output in the list
Eric Laurente552edb2014-03-10 17:42:56 -07003480
François Gaffiec005e562018-11-06 15:04:49 +01003481 DeviceVector devices = mEngine->getOutputDevicesForAttributes(
3482 attributes_initializer(AUDIO_USAGE_MEDIA), nullptr, false /*fromCache*/);
François Gaffie11d30102018-11-02 16:09:09 +01003483 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07003484
Eric Laurent36829f92017-04-07 19:04:42 -07003485 if (outputs.size() == 0) {
3486 return AUDIO_IO_HANDLE_NONE;
3487 }
Eric Laurente552edb2014-03-10 17:42:56 -07003488
Eric Laurent36829f92017-04-07 19:04:42 -07003489 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
3490 bool activeOnly = true;
3491
3492 while (output == AUDIO_IO_HANDLE_NONE) {
3493 audio_io_handle_t outputOffloaded = AUDIO_IO_HANDLE_NONE;
3494 audio_io_handle_t outputDeepBuffer = AUDIO_IO_HANDLE_NONE;
3495 audio_io_handle_t outputPrimary = AUDIO_IO_HANDLE_NONE;
3496
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003497 for (audio_io_handle_t output : outputs) {
3498 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
Eric Laurent83d17c22019-04-02 17:10:01 -07003499 if (activeOnly && !desc->isActive(toVolumeSource(AUDIO_STREAM_MUSIC))) {
Eric Laurent36829f92017-04-07 19:04:42 -07003500 continue;
3501 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003502 ALOGV("selectOutputForMusicEffects activeOnly %d output %d flags 0x%08x",
3503 activeOnly, output, desc->mFlags);
Eric Laurent36829f92017-04-07 19:04:42 -07003504 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003505 outputOffloaded = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003506 }
3507 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_DEEP_BUFFER) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003508 outputDeepBuffer = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003509 }
3510 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_PRIMARY) != 0) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003511 outputPrimary = output;
Eric Laurent36829f92017-04-07 19:04:42 -07003512 }
3513 }
3514 if (outputOffloaded != AUDIO_IO_HANDLE_NONE) {
3515 output = outputOffloaded;
3516 } else if (outputDeepBuffer != AUDIO_IO_HANDLE_NONE) {
3517 output = outputDeepBuffer;
3518 } else if (outputPrimary != AUDIO_IO_HANDLE_NONE) {
3519 output = outputPrimary;
3520 } else {
3521 output = outputs[0];
3522 }
3523 activeOnly = false;
3524 }
3525
3526 if (output != mMusicEffectOutput) {
François Gaffie1b4753e2023-02-06 10:36:33 +01003527 mEffects.moveEffects(AUDIO_SESSION_OUTPUT_MIX, mMusicEffectOutput, output,
3528 mpClientInterface);
Eric Laurent36829f92017-04-07 19:04:42 -07003529 mMusicEffectOutput = output;
3530 }
3531
3532 ALOGV("selectOutputForMusicEffects selected output %d", output);
Eric Laurente552edb2014-03-10 17:42:56 -07003533 return output;
3534}
3535
Eric Laurent36829f92017-04-07 19:04:42 -07003536audio_io_handle_t AudioPolicyManager::getOutputForEffect(const effect_descriptor_t *desc __unused)
3537{
3538 return selectOutputForMusicEffects();
3539}
3540
Eric Laurente0720872014-03-11 09:30:41 -07003541status_t AudioPolicyManager::registerEffect(const effect_descriptor_t *desc,
Eric Laurente552edb2014-03-10 17:42:56 -07003542 audio_io_handle_t io,
Ytai Ben-Tsvi0a4904a2021-01-06 12:57:05 -08003543 product_strategy_t strategy,
Eric Laurente552edb2014-03-10 17:42:56 -07003544 int session,
3545 int id)
3546{
Eric Laurentb82e6b72019-11-22 17:25:04 -08003547 if (session != AUDIO_SESSION_DEVICE) {
3548 ssize_t index = mOutputs.indexOfKey(io);
Eric Laurente552edb2014-03-10 17:42:56 -07003549 if (index < 0) {
Eric Laurentb82e6b72019-11-22 17:25:04 -08003550 index = mInputs.indexOfKey(io);
3551 if (index < 0) {
3552 ALOGW("registerEffect() unknown io %d", io);
3553 return INVALID_OPERATION;
3554 }
Eric Laurente552edb2014-03-10 17:42:56 -07003555 }
3556 }
Eric Laurentbf8f69f2022-03-25 17:48:38 +01003557 bool isMusicEffect = (session != AUDIO_SESSION_OUTPUT_STAGE)
3558 && ((strategy == streamToStrategy(AUDIO_STREAM_MUSIC)
3559 || strategy == PRODUCT_STRATEGY_NONE));
3560 return mEffects.registerEffect(desc, io, session, id, isMusicEffect);
Eric Laurente552edb2014-03-10 17:42:56 -07003561}
3562
Eric Laurentc241b0d2018-11-28 09:08:49 -08003563status_t AudioPolicyManager::unregisterEffect(int id)
3564{
3565 if (mEffects.getEffect(id) == nullptr) {
3566 return INVALID_OPERATION;
3567 }
Eric Laurentc241b0d2018-11-28 09:08:49 -08003568 if (mEffects.isEffectEnabled(id)) {
3569 ALOGW("%s effect %d enabled", __FUNCTION__, id);
3570 setEffectEnabled(id, false);
3571 }
3572 return mEffects.unregisterEffect(id);
3573}
3574
3575status_t AudioPolicyManager::setEffectEnabled(int id, bool enabled)
3576{
3577 sp<EffectDescriptor> effect = mEffects.getEffect(id);
3578 if (effect == nullptr) {
3579 return INVALID_OPERATION;
3580 }
3581
3582 status_t status = mEffects.setEffectEnabled(id, enabled);
3583 if (status == NO_ERROR) {
3584 mInputs.trackEffectEnabled(effect, enabled);
3585 }
3586 return status;
3587}
3588
Eric Laurent6c796322019-04-09 14:13:17 -07003589
3590status_t AudioPolicyManager::moveEffectsToIo(const std::vector<int>& ids, audio_io_handle_t io)
3591{
3592 mEffects.moveEffects(ids, io);
3593 return NO_ERROR;
3594}
3595
Eric Laurentc75307b2015-03-17 15:29:32 -07003596bool AudioPolicyManager::isStreamActive(audio_stream_type_t stream, uint32_t inPastMs) const
3597{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003598 auto vs = toVolumeSource(stream, false);
3599 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActive(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003600}
3601
3602bool AudioPolicyManager::isStreamActiveRemotely(audio_stream_type_t stream, uint32_t inPastMs) const
3603{
Francois Gaffie4404ddb2021-02-04 17:03:38 +01003604 auto vs = toVolumeSource(stream, false);
3605 return vs != VOLUME_SOURCE_NONE ? mOutputs.isActiveRemotely(vs, inPastMs) : false;
Eric Laurentc75307b2015-03-17 15:29:32 -07003606}
3607
Eric Laurente0720872014-03-11 09:30:41 -07003608bool AudioPolicyManager::isSourceActive(audio_source_t source) const
Eric Laurente552edb2014-03-10 17:42:56 -07003609{
3610 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07003611 const sp<AudioInputDescriptor> inputDescriptor = mInputs.valueAt(i);
Eric Laurent599c7582015-12-07 18:05:55 -08003612 if (inputDescriptor->isSourceActive(source)) {
Eric Laurente552edb2014-03-10 17:42:56 -07003613 return true;
3614 }
3615 }
3616 return false;
3617}
3618
Eric Laurent275e8e92014-11-30 15:14:47 -08003619// Register a list of custom mixes with their attributes and format.
3620// When a mix is registered, corresponding input and output profiles are
3621// added to the remote submix hw module. The profile contains only the
3622// parameters (sampling rate, format...) specified by the mix.
3623// The corresponding input remote submix device is also connected.
3624//
3625// When a remote submix device is connected, the address is checked to select the
3626// appropriate profile and the corresponding input or output stream is opened.
3627//
3628// When capture starts, getInputForAttr() will:
3629// - 1 look for a mix matching the address passed in attribtutes tags if any
3630// - 2 if none found, getDeviceForInputSource() will:
3631// - 2.1 look for a mix matching the attributes source
3632// - 2.2 if none found, default to device selection by policy rules
3633// At this time, the corresponding output remote submix device is also connected
3634// and active playback use cases can be transferred to this mix if needed when reconnecting
3635// after AudioTracks are invalidated
3636//
3637// When playback starts, getOutputForAttr() will:
3638// - 1 look for a mix matching the address passed in attribtutes tags if any
3639// - 2 if none found, look for a mix matching the attributes usage
3640// - 3 if none found, default to device and output selection by policy rules.
3641
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07003642status_t AudioPolicyManager::registerPolicyMixes(const Vector<AudioMix>& mixes)
Eric Laurent275e8e92014-11-30 15:14:47 -08003643{
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003644 ALOGV("registerPolicyMixes() %zu mix(es)", mixes.size());
3645 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003646 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003647 sp<HwModule> rSubmixModule;
3648 // examine each mix's route type
3649 for (size_t i = 0; i < mixes.size(); i++) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003650 AudioMix mix = mixes[i];
Kevin Rocard153f92d2018-12-18 18:33:28 -08003651 // Only capture of playback is allowed in LOOP_BACK & RENDER mode
3652 if (is_mix_loopback_render(mix.mRouteFlags) && mix.mMixType != MIX_TYPE_PLAYERS) {
3653 ALOGE("Unsupported Policy Mix %zu of %zu: "
3654 "Only capture of playback is allowed in LOOP_BACK & RENDER mode",
3655 i, mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003656 res = INVALID_OPERATION;
Eric Laurent275e8e92014-11-30 15:14:47 -08003657 break;
3658 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08003659 // LOOP_BACK and LOOP_BACK | RENDER have the same remote submix backend and are handled
3660 // in the same way.
Eric Laurent97ac8712018-07-27 18:59:02 -07003661 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003662 ALOGV("registerPolicyMixes() mix %zu of %zu is LOOP_BACK %d", i, mixes.size(),
3663 mix.mRouteFlags);
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003664 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003665 rSubmixModule = mHwModules.getModuleFromName(
3666 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3667 if (rSubmixModule == 0) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003668 ALOGE("Unable to find audio module for submix, aborting mix %zu registration",
Mikhail Naganovd4120142017-12-06 15:49:22 -08003669 i);
3670 res = INVALID_OPERATION;
3671 break;
3672 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003673 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003674
Eric Laurent97ac8712018-07-27 18:59:02 -07003675 String8 address = mix.mDeviceAddress;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003676 audio_devices_t deviceTypeToMakeAvailable;
Eric Laurent97ac8712018-07-27 18:59:02 -07003677 if (mix.mMixType == MIX_TYPE_PLAYERS) {
Eric Laurent97ac8712018-07-27 18:59:02 -07003678 mix.mDeviceType = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003679 deviceTypeToMakeAvailable = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3680 } else {
3681 mix.mDeviceType = AUDIO_DEVICE_IN_REMOTE_SUBMIX;
3682 deviceTypeToMakeAvailable = AUDIO_DEVICE_OUT_REMOTE_SUBMIX;
Eric Laurent97ac8712018-07-27 18:59:02 -07003683 }
François Gaffie036e1e92015-03-19 10:16:24 +01003684
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003685 if (mPolicyMixes.registerMix(mix, 0 /*output desc*/) != NO_ERROR) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003686 ALOGE("Error registering mix %zu for address %s", i, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003687 res = INVALID_OPERATION;
3688 break;
3689 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003690 audio_config_t outputConfig = mix.mFormat;
3691 audio_config_t inputConfig = mix.mFormat;
Eric Laurentc529cf62020-04-17 18:19:10 -07003692 // NOTE: audio flinger mixer does not support mono output: configure remote submix HAL
3693 // in stereo and let audio flinger do the channel conversion if needed.
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003694 outputConfig.channel_mask = AUDIO_CHANNEL_OUT_STEREO;
3695 inputConfig.channel_mask = AUDIO_CHANNEL_IN_STEREO;
jiabin5740f082019-08-19 15:08:30 -07003696 rSubmixModule->addOutputProfile(address.c_str(), &outputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003697 AUDIO_DEVICE_OUT_REMOTE_SUBMIX, address,
3698 audio_is_linear_pcm(outputConfig.format)
3699 ? AUDIO_OUTPUT_FLAG_NONE : AUDIO_OUTPUT_FLAG_DIRECT);
jiabin5740f082019-08-19 15:08:30 -07003700 rSubmixModule->addInputProfile(address.c_str(), &inputConfig,
Dean Wheatley80551862023-11-17 01:32:22 +11003701 AUDIO_DEVICE_IN_REMOTE_SUBMIX, address,
3702 audio_is_linear_pcm(inputConfig.format)
3703 ? AUDIO_INPUT_FLAG_NONE : AUDIO_INPUT_FLAG_DIRECT);
François Gaffie036e1e92015-03-19 10:16:24 +01003704
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003705 if ((res = setDeviceConnectionStateInt(deviceTypeToMakeAvailable,
jiabinc1de2df2019-05-07 14:26:40 -07003706 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003707 address.c_str(), "remote-submix", AUDIO_FORMAT_DEFAULT)) != NO_ERROR) {
jiabinc1de2df2019-05-07 14:26:40 -07003708 ALOGE("Failed to set remote submix device available, type %u, address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003709 mix.mDeviceType, address.c_str());
jiabinc1de2df2019-05-07 14:26:40 -07003710 break;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003711 }
Eric Laurent97ac8712018-07-27 18:59:02 -07003712 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
3713 String8 address = mix.mDeviceAddress;
Eric Laurent2c80be02019-01-23 18:06:37 -08003714 audio_devices_t type = mix.mDeviceType;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003715 ALOGV(" registerPolicyMixes() mix %zu of %zu is RENDER, dev=0x%X addr=%s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003716 i, mixes.size(), type, address.c_str());
Eric Laurent2c80be02019-01-23 18:06:37 -08003717
3718 sp<DeviceDescriptor> device = mHwModules.getDeviceDescriptor(
3719 mix.mDeviceType, mix.mDeviceAddress,
3720 String8(), AUDIO_FORMAT_DEFAULT);
3721 if (device == nullptr) {
3722 res = INVALID_OPERATION;
3723 break;
3724 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003725
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003726 bool foundOutput = false;
Eric Laurentc529cf62020-04-17 18:19:10 -07003727 // First try to find an already opened output supporting the device
3728 for (size_t j = 0 ; j < mOutputs.size() && !foundOutput && res == NO_ERROR; j++) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003729 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurent2c80be02019-01-23 18:06:37 -08003730
Eric Laurentc529cf62020-04-17 18:19:10 -07003731 if (!desc->isDuplicated() && desc->supportedDevices().contains(device)) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003732 if (mPolicyMixes.registerMix(mix, desc) != NO_ERROR) {
Kevin Rocard153f92d2018-12-18 18:33:28 -08003733 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003734 address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003735 res = INVALID_OPERATION;
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003736 } else {
3737 foundOutput = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003738 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003739 }
3740 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003741 // If no output found, try to find a direct output profile supporting the device
3742 for (size_t i = 0; i < mHwModules.size() && !foundOutput && res == NO_ERROR; i++) {
3743 sp<HwModule> module = mHwModules[i];
3744 for (size_t j = 0;
3745 j < module->getOutputProfiles().size() && !foundOutput && res == NO_ERROR;
3746 j++) {
3747 sp<IOProfile> profile = module->getOutputProfiles()[j];
3748 if (profile->isDirectOutput() && profile->supportsDevice(device)) {
3749 if (mPolicyMixes.registerMix(mix, nullptr) != NO_ERROR) {
3750 ALOGE("Could not register mix RENDER, dev=0x%X addr=%s", type,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003751 address.c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003752 res = INVALID_OPERATION;
3753 } else {
3754 foundOutput = true;
3755 }
3756 }
3757 }
3758 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003759 if (res != NO_ERROR) {
3760 ALOGE(" Error registering mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003761 i, type, address.c_str());
Jean-Michel Trivi5ac8cd42016-03-24 16:35:36 -07003762 res = INVALID_OPERATION;
3763 break;
3764 } else if (!foundOutput) {
3765 ALOGE(" Output not found for mix %zu for device 0x%X addr %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003766 i, type, address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003767 res = INVALID_OPERATION;
3768 break;
Eric Laurentc209fe42020-06-05 18:11:23 -07003769 } else {
3770 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003771 }
Eric Laurentc722f302014-12-10 11:21:49 -08003772 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003773 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003774 if (res != NO_ERROR) {
3775 unregisterPolicyMixes(mixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07003776 } else if (checkOutputs) {
3777 checkForDeviceAndOutputChanges();
3778 updateCallAndOutputRouting();
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003779 }
3780 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003781}
3782
3783status_t AudioPolicyManager::unregisterPolicyMixes(Vector<AudioMix> mixes)
3784{
Eric Laurent7b279bb2015-12-14 10:18:23 -08003785 ALOGV("unregisterPolicyMixes() num mixes %zu", mixes.size());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003786 status_t res = NO_ERROR;
Eric Laurentc209fe42020-06-05 18:11:23 -07003787 bool checkOutputs = false;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003788 sp<HwModule> rSubmixModule;
3789 // examine each mix's route type
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003790 for (const auto& mix : mixes) {
3791 if ((mix.mRouteFlags & MIX_ROUTE_FLAG_LOOP_BACK) == MIX_ROUTE_FLAG_LOOP_BACK) {
François Gaffie036e1e92015-03-19 10:16:24 +01003792
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003793 if (rSubmixModule == 0) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08003794 rSubmixModule = mHwModules.getModuleFromName(
3795 AUDIO_HARDWARE_MODULE_ID_REMOTE_SUBMIX);
3796 if (rSubmixModule == 0) {
3797 res = INVALID_OPERATION;
3798 continue;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003799 }
3800 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003801
Mikhail Naganovcf84e592017-12-07 11:25:11 -08003802 String8 address = mix.mDeviceAddress;
Eric Laurent275e8e92014-11-30 15:14:47 -08003803
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003804 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003805 res = INVALID_OPERATION;
3806 continue;
3807 }
3808
Kevin Rocard04ed0462019-05-02 17:53:24 -07003809 for (auto device : {AUDIO_DEVICE_IN_REMOTE_SUBMIX, AUDIO_DEVICE_OUT_REMOTE_SUBMIX}) {
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003810 if (getDeviceConnectionState(device, address.c_str()) ==
Kevin Rocard04ed0462019-05-02 17:53:24 -07003811 AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
3812 res = setDeviceConnectionStateInt(device, AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003813 address.c_str(), "remote-submix",
Kevin Rocard04ed0462019-05-02 17:53:24 -07003814 AUDIO_FORMAT_DEFAULT);
3815 if (res != OK) {
3816 ALOGE("Error making RemoteSubmix device unavailable for mix "
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00003817 "with type %d, address %s", device, address.c_str());
Kevin Rocard04ed0462019-05-02 17:53:24 -07003818 }
3819 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003820 }
jiabin5740f082019-08-19 15:08:30 -07003821 rSubmixModule->removeOutputProfile(address.c_str());
3822 rSubmixModule->removeInputProfile(address.c_str());
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003823
Kevin Rocard153f92d2018-12-18 18:33:28 -08003824 } else if ((mix.mRouteFlags & MIX_ROUTE_FLAG_RENDER) == MIX_ROUTE_FLAG_RENDER) {
Jean-Michel Trivi67917272019-05-22 11:54:37 -07003825 if (mPolicyMixes.unregisterMix(mix) != NO_ERROR) {
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003826 res = INVALID_OPERATION;
3827 continue;
Eric Laurentc209fe42020-06-05 18:11:23 -07003828 } else {
3829 checkOutputs = true;
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003830 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003831 }
Eric Laurent275e8e92014-11-30 15:14:47 -08003832 }
Eric Laurentc209fe42020-06-05 18:11:23 -07003833 if (res == NO_ERROR && checkOutputs) {
3834 checkForDeviceAndOutputChanges();
3835 updateCallAndOutputRouting();
3836 }
Jean-Michel Trivi7638ca22016-03-04 17:42:44 -08003837 return res;
Eric Laurent275e8e92014-11-30 15:14:47 -08003838}
3839
Jan Sebechlebsky0af8e872023-08-11 14:45:08 +02003840status_t AudioPolicyManager::updatePolicyMix(
3841 const AudioMix& mix,
3842 const std::vector<AudioMixMatchCriterion>& updatedCriteria) {
3843 status_t res = mPolicyMixes.updateMix(mix, updatedCriteria);
3844 if (res == NO_ERROR) {
3845 checkForDeviceAndOutputChanges();
3846 updateCallAndOutputRouting();
3847 }
3848 return res;
3849}
3850
Mikhail Naganov100f0122018-11-29 11:22:16 -08003851void AudioPolicyManager::dumpManualSurroundFormats(String8 *dst) const
3852{
3853 size_t i = 0;
3854 constexpr size_t audioFormatPrefixLen = sizeof("AUDIO_FORMAT_");
3855 for (const auto& fmt : mManualSurroundFormats) {
3856 if (i++ != 0) dst->append(", ");
3857 std::string sfmt;
3858 FormatConverter::toString(fmt, sfmt);
3859 dst->append(sfmt.size() >= audioFormatPrefixLen ?
3860 sfmt.c_str() + audioFormatPrefixLen - 1 : sfmt.c_str());
3861 }
3862}
3863
Eric Laurentc529cf62020-04-17 18:19:10 -07003864// Returns true if all devices types match the predicate and are supported by one HW module
3865bool AudioPolicyManager::areAllDevicesSupported(
jiabin6a02d532020-08-07 11:56:38 -07003866 const AudioDeviceTypeAddrVector& devices,
Eric Laurentc529cf62020-04-17 18:19:10 -07003867 std::function<bool(audio_devices_t)> predicate,
Eric Laurent78fedbf2023-03-09 14:40:44 +01003868 const char *context,
3869 bool matchAddress) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003870 for (size_t i = 0; i < devices.size(); i++) {
3871 sp<DeviceDescriptor> devDesc = mHwModules.getDeviceDescriptor(
jiabin0a488932020-08-07 17:32:40 -07003872 devices[i].mType, devices[i].getAddress(), String8(),
Eric Laurent78fedbf2023-03-09 14:40:44 +01003873 AUDIO_FORMAT_DEFAULT, false /*allowToCreate*/, matchAddress);
Eric Laurentc529cf62020-04-17 18:19:10 -07003874 if (devDesc == nullptr || (predicate != nullptr && !predicate(devices[i].mType))) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00003875 ALOGE("%s: device type %#x address %s not supported or not match predicate",
jiabin0a488932020-08-07 17:32:40 -07003876 context, devices[i].mType, devices[i].getAddress());
Eric Laurentc529cf62020-04-17 18:19:10 -07003877 return false;
3878 }
3879 }
3880 return true;
3881}
3882
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003883void AudioPolicyManager::changeOutputDevicesMuteState(
3884 const AudioDeviceTypeAddrVector& devices) {
3885 ALOGVV("%s() num devices %zu", __func__, devices.size());
3886
3887 std::vector<sp<SwAudioOutputDescriptor>> outputs =
3888 getSoftwareOutputsForDevices(devices);
3889
3890 for (size_t i = 0; i < outputs.size(); i++) {
3891 sp<SwAudioOutputDescriptor> outputDesc = outputs[i];
3892 DeviceVector prevDevices = outputDesc->devices();
3893 checkDeviceMuteStrategies(outputDesc, prevDevices, 0 /* delayMs */);
3894 }
3895}
3896
3897std::vector<sp<SwAudioOutputDescriptor>> AudioPolicyManager::getSoftwareOutputsForDevices(
3898 const AudioDeviceTypeAddrVector& devices) const
3899{
3900 std::vector<sp<SwAudioOutputDescriptor>> outputs;
3901 DeviceVector deviceDescriptors;
3902 for (size_t j = 0; j < devices.size(); j++) {
3903 sp<DeviceDescriptor> desc = mHwModules.getDeviceDescriptor(
3904 devices[j].mType, devices[j].getAddress(), String8(), AUDIO_FORMAT_DEFAULT);
3905 if (desc == nullptr || !audio_is_output_device(devices[j].mType)) {
3906 ALOGE("%s: device type %#x address %s not supported or not an output device",
3907 __func__, devices[j].mType, devices[j].getAddress());
3908 continue;
3909 }
3910 deviceDescriptors.add(desc);
3911 }
3912 for (size_t i = 0; i < mOutputs.size(); i++) {
3913 if (!mOutputs.valueAt(i)->supportsAtLeastOne(deviceDescriptors)) {
3914 continue;
3915 }
3916 outputs.push_back(mOutputs.valueAt(i));
3917 }
3918 return outputs;
3919}
3920
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003921status_t AudioPolicyManager::setUidDeviceAffinities(uid_t uid,
jiabin6a02d532020-08-07 11:56:38 -07003922 const AudioDeviceTypeAddrVector& devices) {
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003923 ALOGV("%s() uid=%d num devices %zu", __FUNCTION__, uid, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07003924 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
3925 return BAD_VALUE;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003926 }
3927 status_t res = mPolicyMixes.setUidDeviceAffinities(uid, devices);
Eric Laurentc529cf62020-04-17 18:19:10 -07003928 if (res != NO_ERROR) {
3929 ALOGE("%s() Could not set all device affinities for uid = %d", __FUNCTION__, uid);
3930 return res;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003931 }
Eric Laurentc529cf62020-04-17 18:19:10 -07003932
3933 checkForDeviceAndOutputChanges();
3934 updateCallAndOutputRouting();
3935
3936 return NO_ERROR;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003937}
3938
3939status_t AudioPolicyManager::removeUidDeviceAffinities(uid_t uid) {
3940 ALOGV("%s() uid=%d", __FUNCTION__, uid);
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003941 status_t res = mPolicyMixes.removeUidDeviceAffinities(uid);
3942 if (res != NO_ERROR) {
Eric Laurentc529cf62020-04-17 18:19:10 -07003943 ALOGE("%s() Could not remove all device affinities for uid = %d",
Oscar Azucena4b2a8212019-04-26 23:48:59 -07003944 __FUNCTION__, uid);
3945 return INVALID_OPERATION;
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003946 }
3947
Eric Laurentc529cf62020-04-17 18:19:10 -07003948 checkForDeviceAndOutputChanges();
3949 updateCallAndOutputRouting();
3950
Jean-Michel Trivibda70da2018-12-19 07:30:15 -08003951 return res;
3952}
3953
Eric Laurent2517af32020-11-25 15:31:27 +01003954
jiabin0a488932020-08-07 17:32:40 -07003955status_t AudioPolicyManager::setDevicesRoleForStrategy(product_strategy_t strategy,
3956 device_role_t role,
3957 const AudioDeviceTypeAddrVector &devices) {
3958 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
3959 dumpAudioDeviceTypeAddrVector(devices).c_str());
Eric Laurentc529cf62020-04-17 18:19:10 -07003960
Eric Laurentc529cf62020-04-17 18:19:10 -07003961 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003962 return BAD_VALUE;
3963 }
jiabin0a488932020-08-07 17:32:40 -07003964 status_t status = mEngine->setDevicesRoleForStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003965 if (status != NO_ERROR) {
jiabin0a488932020-08-07 17:32:40 -07003966 ALOGW("Engine could not set preferred devices %s for strategy %d role %d",
3967 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003968 return status;
3969 }
3970
3971 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01003972
3973 bool forceVolumeReeval = false;
3974 // FIXME: workaround for truncated touch sounds
3975 // to be removed when the problem is handled by system UI
3976 uint32_t delayMs = 0;
3977 if (strategy == mCommunnicationStrategy) {
3978 forceVolumeReeval = true;
3979 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
3980 updateInputRouting();
3981 }
3982 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003983
3984 return NO_ERROR;
3985}
3986
Oscar Azucena6acf34b2023-04-27 16:32:09 -07003987void AudioPolicyManager::updateCallAndOutputRouting(bool forceVolumeReeval, uint32_t delayMs,
3988 bool skipDelays)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003989{
3990 uint32_t waitMs = 0;
Eric Laurent96d1dda2022-03-14 17:14:19 +01003991 bool wasLeUnicastActive = isLeUnicastActive();
Francois Gaffie19fd6c52021-02-04 17:02:59 +01003992 if (updateCallRouting(true /*fromCache*/, delayMs, &waitMs) == NO_ERROR) {
Eric Laurentb36b4ac2020-08-21 12:50:41 -07003993 // Only apply special touch sound delay once
3994 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003995 }
jiabin3ff8d7d2022-12-13 06:27:44 +00003996 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07003997 for (size_t i = 0; i < mOutputs.size(); i++) {
3998 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
3999 DeviceVector newDevices = getNewOutputDevices(outputDesc, true /*fromCache*/);
Francois Gaffie601801d2021-06-22 13:27:39 +02004000 if ((mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) ||
4001 (outputDesc != mPrimaryOutput && !isTelephonyRxOrTx(outputDesc))) {
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004002 // As done in setDeviceConnectionState, we could also fix default device issue by
4003 // preventing the force re-routing in case of default dev that distinguishes on address.
4004 // Let's give back to engine full device choice decision however.
Francois Gaffie601801d2021-06-22 13:27:39 +02004005 bool forceRouting = !newDevices.isEmpty();
jiabin3ff8d7d2022-12-13 06:27:44 +00004006 if (outputDesc->mUsePreferredMixerAttributes && newDevices != outputDesc->devices()) {
4007 // If the device is using preferred mixer attributes, the output need to reopen
4008 // with default configuration when the new selected devices are different from
4009 // current routing devices.
4010 outputsToReopen.emplace(mOutputs.keyAt(i), newDevices);
4011 continue;
4012 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05304013
4014 waitMs = setOutputDevices(__func__, outputDesc, newDevices, forceRouting, delayMs,
4015 nullptr, !skipDelays /*requiresMuteCheck*/,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004016 !forceRouting /*requiresVolumeCheck*/, skipDelays);
Eric Laurentb36b4ac2020-08-21 12:50:41 -07004017 // Only apply special touch sound delay once
4018 delayMs = 0;
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004019 }
4020 if (forceVolumeReeval && !newDevices.isEmpty()) {
4021 applyStreamVolumes(outputDesc, newDevices.types(), waitMs, true);
4022 }
4023 }
jiabin3ff8d7d2022-12-13 06:27:44 +00004024 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent96d1dda2022-03-14 17:14:19 +01004025 checkLeBroadcastRoutes(wasLeUnicastActive, nullptr, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004026}
4027
Eric Laurent2517af32020-11-25 15:31:27 +01004028void AudioPolicyManager::updateInputRouting() {
4029 for (const auto& activeDesc : mInputs.getActiveInputs()) {
Jaideep Sharma408349a2020-11-27 14:47:17 +05304030 // Skip for hotword recording as the input device switch
4031 // is handled within sound trigger HAL
4032 if (activeDesc->isSoundTrigger() && activeDesc->source() == AUDIO_SOURCE_HOTWORD) {
4033 continue;
4034 }
Eric Laurent2517af32020-11-25 15:31:27 +01004035 auto newDevice = getNewInputDevice(activeDesc);
4036 // Force new input selection if the new device can not be reached via current input
4037 if (activeDesc->mProfile->getSupportedDevices().contains(newDevice)) {
4038 setInputDevice(activeDesc->mIoHandle, newDevice);
4039 } else {
4040 closeInput(activeDesc->mIoHandle);
4041 }
4042 }
4043}
4044
Paul Wang5d7cdb52022-11-22 09:45:06 +00004045status_t
4046AudioPolicyManager::removeDevicesRoleForStrategy(product_strategy_t strategy,
4047 device_role_t role,
4048 const AudioDeviceTypeAddrVector &devices) {
4049 ALOGV("%s() strategy=%d role=%d %s", __func__, strategy, role,
4050 dumpAudioDeviceTypeAddrVector(devices).c_str());
4051
Eric Laurent78fedbf2023-03-09 14:40:44 +01004052 if (!areAllDevicesSupported(
4053 devices, audio_is_output_device, __func__, /*matchAddress*/false)) {
Paul Wang5d7cdb52022-11-22 09:45:06 +00004054 return BAD_VALUE;
4055 }
4056 status_t status = mEngine->removeDevicesRoleForStrategy(strategy, role, devices);
4057 if (status != NO_ERROR) {
4058 ALOGW("Engine could not remove devices %s for strategy %d role %d",
4059 dumpAudioDeviceTypeAddrVector(devices).c_str(), strategy, role);
4060 return status;
4061 }
4062
4063 checkForDeviceAndOutputChanges();
4064
4065 bool forceVolumeReeval = false;
4066 // TODO(b/263479999): workaround for truncated touch sounds
4067 // to be removed when the problem is handled by system UI
4068 uint32_t delayMs = 0;
4069 if (strategy == mCommunnicationStrategy) {
4070 forceVolumeReeval = true;
4071 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4072 updateInputRouting();
4073 }
4074 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
4075
4076 return NO_ERROR;
4077}
4078
4079status_t AudioPolicyManager::clearDevicesRoleForStrategy(product_strategy_t strategy,
4080 device_role_t role)
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004081{
Eric Laurentfecbceb2021-02-09 14:46:43 +01004082 ALOGV("%s() strategy=%d role=%d", __func__, strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004083
Paul Wang5d7cdb52022-11-22 09:45:06 +00004084 status_t status = mEngine->clearDevicesRoleForStrategy(strategy, role);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004085 if (status != NO_ERROR) {
Eric Laurent9ae44f32022-12-14 16:17:02 +01004086 ALOGW_IF(status != NAME_NOT_FOUND,
4087 "Engine could not remove device role for strategy %d status %d",
Eric Laurent2517af32020-11-25 15:31:27 +01004088 strategy, status);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004089 return status;
4090 }
4091
4092 checkForDeviceAndOutputChanges();
Eric Laurent2517af32020-11-25 15:31:27 +01004093
4094 bool forceVolumeReeval = false;
4095 // FIXME: workaround for truncated touch sounds
4096 // to be removed when the problem is handled by system UI
4097 uint32_t delayMs = 0;
4098 if (strategy == mCommunnicationStrategy) {
4099 forceVolumeReeval = true;
4100 delayMs = TOUCH_SOUND_FIXED_DELAY_MS;
4101 updateInputRouting();
4102 }
4103 updateCallAndOutputRouting(forceVolumeReeval, delayMs);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004104
4105 return NO_ERROR;
4106}
4107
jiabin0a488932020-08-07 17:32:40 -07004108status_t AudioPolicyManager::getDevicesForRoleAndStrategy(product_strategy_t strategy,
4109 device_role_t role,
4110 AudioDeviceTypeAddrVector &devices) {
4111 return mEngine->getDevicesForRoleAndStrategy(strategy, role, devices);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07004112}
4113
Jiabin Huang3b98d322020-09-03 17:54:16 +00004114status_t AudioPolicyManager::setDevicesRoleForCapturePreset(
4115 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4116 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4117 dumpAudioDeviceTypeAddrVector(devices).c_str());
4118
Mikhail Naganov55773032020-10-01 15:08:13 -07004119 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004120 return BAD_VALUE;
4121 }
4122 status_t status = mEngine->setDevicesRoleForCapturePreset(audioSource, role, devices);
4123 ALOGW_IF(status != NO_ERROR,
4124 "Engine could not set preferred devices %s for audio source %d role %d",
4125 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4126
4127 return status;
4128}
4129
4130status_t AudioPolicyManager::addDevicesRoleForCapturePreset(
4131 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector &devices) {
4132 ALOGV("%s() audioSource=%d role=%d %s", __func__, audioSource, role,
4133 dumpAudioDeviceTypeAddrVector(devices).c_str());
4134
Mikhail Naganov55773032020-10-01 15:08:13 -07004135 if (!areAllDevicesSupported(devices, audio_call_is_input_device, __func__)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004136 return BAD_VALUE;
4137 }
4138 status_t status = mEngine->addDevicesRoleForCapturePreset(audioSource, role, devices);
4139 ALOGW_IF(status != NO_ERROR,
4140 "Engine could not add preferred devices %s for audio source %d role %d",
4141 dumpAudioDeviceTypeAddrVector(devices).c_str(), audioSource, role);
4142
Eric Laurent2517af32020-11-25 15:31:27 +01004143 updateInputRouting();
Jiabin Huang3b98d322020-09-03 17:54:16 +00004144 return status;
4145}
4146
4147status_t AudioPolicyManager::removeDevicesRoleForCapturePreset(
4148 audio_source_t audioSource, device_role_t role, const AudioDeviceTypeAddrVector& devices)
4149{
4150 ALOGV("%s() audioSource=%d role=%d devices=%s", __func__, audioSource, role,
4151 dumpAudioDeviceTypeAddrVector(devices).c_str());
4152
Eric Laurent78fedbf2023-03-09 14:40:44 +01004153 if (!areAllDevicesSupported(
4154 devices, audio_call_is_input_device, __func__, /*matchAddress*/false)) {
Jiabin Huang3b98d322020-09-03 17:54:16 +00004155 return BAD_VALUE;
4156 }
4157
4158 status_t status = mEngine->removeDevicesRoleForCapturePreset(
4159 audioSource, role, devices);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004160 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004161 "Engine could not remove devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004162 if (status == NO_ERROR) {
4163 updateInputRouting();
4164 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004165 return status;
4166}
4167
4168status_t AudioPolicyManager::clearDevicesRoleForCapturePreset(audio_source_t audioSource,
4169 device_role_t role) {
4170 ALOGV("%s() audioSource=%d role=%d", __func__, audioSource, role);
4171
4172 status_t status = mEngine->clearDevicesRoleForCapturePreset(audioSource, role);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004173 ALOGW_IF(status != NO_ERROR && status != NAME_NOT_FOUND,
Jiabin Huang3b98d322020-09-03 17:54:16 +00004174 "Engine could not clear devices role (%d) for capture preset %d", role, audioSource);
Eric Laurent9ae44f32022-12-14 16:17:02 +01004175 if (status == NO_ERROR) {
4176 updateInputRouting();
4177 }
Jiabin Huang3b98d322020-09-03 17:54:16 +00004178 return status;
4179}
4180
4181status_t AudioPolicyManager::getDevicesForRoleAndCapturePreset(
4182 audio_source_t audioSource, device_role_t role, AudioDeviceTypeAddrVector &devices) {
4183 return mEngine->getDevicesForRoleAndCapturePreset(audioSource, role, devices);
4184}
4185
Oscar Azucena90e77632019-11-27 17:12:28 -08004186status_t AudioPolicyManager::setUserIdDeviceAffinities(int userId,
jiabin6a02d532020-08-07 11:56:38 -07004187 const AudioDeviceTypeAddrVector& devices) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004188 ALOGV("%s() userId=%d num devices %zu", __func__, userId, devices.size());
Eric Laurentc529cf62020-04-17 18:19:10 -07004189 if (!areAllDevicesSupported(devices, audio_is_output_device, __func__)) {
4190 return BAD_VALUE;
Oscar Azucena90e77632019-11-27 17:12:28 -08004191 }
Oscar Azucena90e77632019-11-27 17:12:28 -08004192 status_t status = mPolicyMixes.setUserIdDeviceAffinities(userId, devices);
4193 if (status != NO_ERROR) {
4194 ALOGE("%s() could not set device affinity for userId %d",
4195 __FUNCTION__, userId);
4196 return status;
4197 }
4198
4199 // reevaluate outputs for all devices
4200 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004201 changeOutputDevicesMuteState(devices);
4202 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4203 true /* skipDelays */);
4204 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004205
4206 return NO_ERROR;
4207}
4208
4209status_t AudioPolicyManager::removeUserIdDeviceAffinities(int userId) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01004210 ALOGV("%s() userId=%d", __FUNCTION__, userId);
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004211 AudioDeviceTypeAddrVector devices;
4212 mPolicyMixes.getDevicesForUserId(userId, devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004213 status_t status = mPolicyMixes.removeUserIdDeviceAffinities(userId);
4214 if (status != NO_ERROR) {
4215 ALOGE("%s() Could not remove all device affinities fo userId = %d",
4216 __FUNCTION__, userId);
4217 return status;
4218 }
4219
4220 // reevaluate outputs for all devices
4221 checkForDeviceAndOutputChanges();
Oscar Azucena6acf34b2023-04-27 16:32:09 -07004222 changeOutputDevicesMuteState(devices);
4223 updateCallAndOutputRouting(false /* forceVolumeReeval */, 0 /* delayMs */,
4224 true /* skipDelays */);
4225 changeOutputDevicesMuteState(devices);
Oscar Azucena90e77632019-11-27 17:12:28 -08004226
4227 return NO_ERROR;
4228}
4229
Andy Hungc29d82b2018-10-05 12:23:17 -07004230void AudioPolicyManager::dump(String8 *dst) const
Eric Laurente552edb2014-03-10 17:42:56 -07004231{
Andy Hungc29d82b2018-10-05 12:23:17 -07004232 dst->appendFormat("\nAudioPolicyManager Dump: %p\n", this);
Mikhail Naganov0dbe87b2021-12-01 02:03:31 +00004233 dst->appendFormat(" Primary Output I/O handle: %d\n",
Eric Laurent87ffa392015-05-22 10:32:38 -07004234 hasPrimaryOutput() ? mPrimaryOutput->mIoHandle : AUDIO_IO_HANDLE_NONE);
Mikhail Naganov0d6a0332016-04-19 17:12:38 -07004235 std::string stateLiteral;
4236 AudioModeConverter::toString(mEngine->getPhoneState(), stateLiteral);
Andy Hungc29d82b2018-10-05 12:23:17 -07004237 dst->appendFormat(" Phone state: %s\n", stateLiteral.c_str());
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004238 const char* forceUses[AUDIO_POLICY_FORCE_USE_CNT] = {
4239 "communications", "media", "record", "dock", "system",
4240 "HDMI system audio", "encoded surround output", "vibrate ringing" };
4241 for (audio_policy_force_use_t i = AUDIO_POLICY_FORCE_FOR_COMMUNICATION;
4242 i < AUDIO_POLICY_FORCE_USE_CNT; i = (audio_policy_force_use_t)((int)i + 1)) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08004243 audio_policy_forced_cfg_t forceUseValue = mEngine->getForceUse(i);
4244 dst->appendFormat(" Force use for %s: %d", forceUses[i], forceUseValue);
4245 if (i == AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND &&
4246 forceUseValue == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
4247 dst->append(" (MANUAL: ");
4248 dumpManualSurroundFormats(dst);
4249 dst->append(")");
4250 }
4251 dst->append("\n");
Mikhail Naganov2e5167e12018-04-19 13:41:22 -07004252 }
Andy Hungc29d82b2018-10-05 12:23:17 -07004253 dst->appendFormat(" TTS output %savailable\n", mTtsOutputAvailable ? "" : "not ");
4254 dst->appendFormat(" Master mono: %s\n", mMasterMono ? "on" : "off");
Mikhail Naganovb3bcb4f2022-02-23 23:46:56 +00004255 dst->appendFormat(" Communication Strategy id: %d\n", mCommunnicationStrategy);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004256 dst->appendFormat(" Config source: %s\n", mConfig->getSource().c_str());
Eric Laurent2517af32020-11-25 15:31:27 +01004257
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004258 dst->append("\n");
4259 mAvailableOutputDevices.dump(dst, String8("Available output"), 1);
4260 dst->append("\n");
4261 mAvailableInputDevices.dump(dst, String8("Available input"), 1);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004262 mHwModules.dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004263 mOutputs.dump(dst);
4264 mInputs.dump(dst);
Mikhail Naganov0f413b22021-12-02 05:29:27 +00004265 mEffects.dump(dst, 1);
Andy Hungc29d82b2018-10-05 12:23:17 -07004266 mAudioPatches.dump(dst);
4267 mPolicyMixes.dump(dst);
4268 mAudioSources.dump(dst);
François Gaffiec005e562018-11-06 15:04:49 +01004269
Kevin Rocardb99cc752019-03-21 20:52:24 -07004270 dst->appendFormat(" AllowedCapturePolicies:\n");
4271 for (auto& policy : mAllowedCapturePolicies) {
4272 dst->appendFormat(" - uid=%d flag_mask=%#x\n", policy.first, policy.second);
4273 }
4274
jiabina84c3d32022-12-02 18:59:55 +00004275 dst->appendFormat(" Preferred mixer audio configuration:\n");
4276 for (const auto it : mPreferredMixerAttrInfos) {
4277 dst->appendFormat(" - device port id: %d\n", it.first);
4278 for (const auto preferredMixerInfoIt : it.second) {
4279 dst->appendFormat(" - strategy: %d; ", preferredMixerInfoIt.first);
4280 preferredMixerInfoIt.second->dump(dst);
4281 }
4282 }
4283
François Gaffiec005e562018-11-06 15:04:49 +01004284 dst->appendFormat("\nPolicy Engine dump:\n");
4285 mEngine->dump(dst);
Andy Hungc29d82b2018-10-05 12:23:17 -07004286}
4287
4288status_t AudioPolicyManager::dump(int fd)
4289{
4290 String8 result;
4291 dump(&result);
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00004292 write(fd, result.c_str(), result.size());
Eric Laurente552edb2014-03-10 17:42:56 -07004293 return NO_ERROR;
4294}
4295
Kevin Rocardb99cc752019-03-21 20:52:24 -07004296status_t AudioPolicyManager::setAllowedCapturePolicy(uid_t uid, audio_flags_mask_t capturePolicy)
4297{
4298 mAllowedCapturePolicies[uid] = capturePolicy;
4299 return NO_ERROR;
4300}
4301
Eric Laurente552edb2014-03-10 17:42:56 -07004302// This function checks for the parameters which can be offloaded.
4303// This can be enhanced depending on the capability of the DSP and policy
4304// of the system.
Eric Laurent90fe31c2020-11-26 20:06:35 +01004305audio_offload_mode_t AudioPolicyManager::getOffloadSupport(const audio_offload_info_t& offloadInfo)
Eric Laurente552edb2014-03-10 17:42:56 -07004306{
Eric Laurent90fe31c2020-11-26 20:06:35 +01004307 ALOGV("%s: SR=%u, CM=0x%x, Format=0x%x, StreamType=%d,"
Eric Laurentd4692962014-05-05 18:13:44 -07004308 " BitRate=%u, duration=%" PRId64 " us, has_video=%d",
Eric Laurent90fe31c2020-11-26 20:06:35 +01004309 __func__, offloadInfo.sample_rate, offloadInfo.channel_mask,
Eric Laurente552edb2014-03-10 17:42:56 -07004310 offloadInfo.format,
4311 offloadInfo.stream_type, offloadInfo.bit_rate, offloadInfo.duration_us,
4312 offloadInfo.has_video);
4313
jiabin2b9d5a12021-12-10 01:06:29 +00004314 if (!isOffloadPossible(offloadInfo)) {
Eric Laurent90fe31c2020-11-26 20:06:35 +01004315 return AUDIO_OFFLOAD_NOT_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004316 }
4317
4318 // See if there is a profile to support this.
4319 // AUDIO_DEVICE_NONE
François Gaffie11d30102018-11-02 16:09:09 +01004320 sp<IOProfile> profile = getProfileForOutput(DeviceVector() /*ignore device */,
Eric Laurente552edb2014-03-10 17:42:56 -07004321 offloadInfo.sample_rate,
4322 offloadInfo.format,
4323 offloadInfo.channel_mask,
Michael Chana94fbb22018-04-24 14:31:19 +10004324 AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD,
4325 true /* directOnly */);
Eric Laurent94365442021-01-08 18:36:05 +01004326 ALOGV("%s: profile %sfound%s", __func__, profile != nullptr ? "" : "NOT ",
4327 (profile != nullptr && (profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0)
4328 ? ", supports gapless" : "");
Eric Laurent90fe31c2020-11-26 20:06:35 +01004329 if (profile == nullptr) {
4330 return AUDIO_OFFLOAD_NOT_SUPPORTED;
4331 }
4332 if ((profile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD) != 0) {
4333 return AUDIO_OFFLOAD_GAPLESS_SUPPORTED;
4334 }
4335 return AUDIO_OFFLOAD_SUPPORTED;
Eric Laurente552edb2014-03-10 17:42:56 -07004336}
4337
Michael Chana94fbb22018-04-24 14:31:19 +10004338bool AudioPolicyManager::isDirectOutputSupported(const audio_config_base_t& config,
4339 const audio_attributes_t& attributes) {
4340 audio_output_flags_t output_flags = AUDIO_OUTPUT_FLAG_NONE;
François Gaffie58d4be52018-11-06 15:30:12 +01004341 audio_flags_to_audio_output_flags(attributes.flags, &output_flags);
Dorin Drimus9901eb02022-01-14 11:36:51 +00004342 DeviceVector outputDevices = mEngine->getOutputDevicesForAttributes(attributes);
4343 sp<IOProfile> profile = getProfileForOutput(outputDevices,
Michael Chana94fbb22018-04-24 14:31:19 +10004344 config.sample_rate,
4345 config.format,
4346 config.channel_mask,
4347 output_flags,
4348 true /* directOnly */);
4349 ALOGV("%s() profile %sfound with name: %s, "
4350 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4351 __FUNCTION__, profile != 0 ? "" : "NOT ",
jiabin5740f082019-08-19 15:08:30 -07004352 (profile != 0 ? profile->getTagName().c_str() : "null"),
Michael Chana94fbb22018-04-24 14:31:19 +10004353 config.sample_rate, config.format, config.channel_mask, output_flags);
Dorin Drimusecc9f422022-03-09 17:57:40 +01004354
4355 // also try the MSD module if compatible profile not found
4356 if (profile == nullptr) {
4357 profile = getMsdProfileForOutput(outputDevices,
4358 config.sample_rate,
4359 config.format,
4360 config.channel_mask,
4361 output_flags,
4362 true /* directOnly */);
4363 ALOGV("%s() MSD profile %sfound with name: %s, "
4364 "sample rate: %u, format: 0x%x, channel_mask: 0x%x, output flags: 0x%x",
4365 __FUNCTION__, profile != 0 ? "" : "NOT ",
4366 (profile != 0 ? profile->getTagName().c_str() : "null"),
4367 config.sample_rate, config.format, config.channel_mask, output_flags);
4368 }
4369 return (profile != nullptr);
Michael Chana94fbb22018-04-24 14:31:19 +10004370}
4371
jiabin2b9d5a12021-12-10 01:06:29 +00004372bool AudioPolicyManager::isOffloadPossible(const audio_offload_info_t &offloadInfo,
4373 bool durationIgnored) {
4374 if (mMasterMono) {
4375 return false; // no offloading if mono is set.
4376 }
4377
4378 // Check if offload has been disabled
4379 if (property_get_bool("audio.offload.disable", false /* default_value */)) {
4380 ALOGV("%s: offload disabled by audio.offload.disable", __func__);
4381 return false;
4382 }
4383
4384 // Check if stream type is music, then only allow offload as of now.
4385 if (offloadInfo.stream_type != AUDIO_STREAM_MUSIC)
4386 {
4387 ALOGV("%s: stream_type != MUSIC, returning false", __func__);
4388 return false;
4389 }
4390
4391 //TODO: enable audio offloading with video when ready
4392 const bool allowOffloadWithVideo =
4393 property_get_bool("audio.offload.video", false /* default_value */);
4394 if (offloadInfo.has_video && !allowOffloadWithVideo) {
4395 ALOGV("%s: has_video == true, returning false", __func__);
4396 return false;
4397 }
4398
4399 //If duration is less than minimum value defined in property, return false
4400 const int min_duration_secs = property_get_int32(
4401 "audio.offload.min.duration.secs", -1 /* default_value */);
4402 if (!durationIgnored) {
4403 if (min_duration_secs >= 0) {
4404 if (offloadInfo.duration_us < min_duration_secs * 1000000LL) {
4405 ALOGV("%s: Offload denied by duration < audio.offload.min.duration.secs(=%d)",
4406 __func__, min_duration_secs);
4407 return false;
4408 }
4409 } else if (offloadInfo.duration_us < OFFLOAD_DEFAULT_MIN_DURATION_SECS * 1000000) {
4410 ALOGV("%s: Offload denied by duration < default min(=%u)",
4411 __func__, OFFLOAD_DEFAULT_MIN_DURATION_SECS);
4412 return false;
4413 }
4414 }
4415
4416 // Do not allow offloading if one non offloadable effect is enabled. This prevents from
4417 // creating an offloaded track and tearing it down immediately after start when audioflinger
4418 // detects there is an active non offloadable effect.
4419 // FIXME: We should check the audio session here but we do not have it in this context.
4420 // This may prevent offloading in rare situations where effects are left active by apps
4421 // in the background.
4422 if (mEffects.isNonOffloadableEffectEnabled()) {
4423 return false;
4424 }
4425
4426 return true;
4427}
4428
4429audio_direct_mode_t AudioPolicyManager::getDirectPlaybackSupport(const audio_attributes_t *attr,
4430 const audio_config_t *config) {
4431 audio_offload_info_t offloadInfo = AUDIO_INFO_INITIALIZER;
4432 offloadInfo.format = config->format;
4433 offloadInfo.sample_rate = config->sample_rate;
4434 offloadInfo.channel_mask = config->channel_mask;
4435 offloadInfo.stream_type = mEngine->getStreamTypeForAttributes(*attr);
4436 offloadInfo.has_video = false;
4437 offloadInfo.is_streaming = false;
4438 const bool offloadPossible = isOffloadPossible(offloadInfo, true /*durationIgnored*/);
4439
4440 audio_direct_mode_t directMode = AUDIO_DIRECT_NOT_SUPPORTED;
4441 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4442 audio_flags_to_audio_output_flags(attr->flags, &flags);
4443 // only retain flags that will drive compressed offload or passthrough
4444 uint32_t relevantFlags = AUDIO_OUTPUT_FLAG_HW_AV_SYNC;
4445 if (offloadPossible) {
4446 relevantFlags |= AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD;
4447 }
4448 flags = (audio_output_flags_t)((flags & relevantFlags) | AUDIO_OUTPUT_FLAG_DIRECT);
4449
Dorin Drimusfae3c642022-03-17 18:36:30 +01004450 DeviceVector engineOutputDevices = mEngine->getOutputDevicesForAttributes(*attr);
jiabin2b9d5a12021-12-10 01:06:29 +00004451 for (const auto& hwModule : mHwModules) {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004452 DeviceVector outputDevices = engineOutputDevices;
4453 // the MSD module checks for different conditions and output devices
4454 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
4455 if (!msdHasPatchesToAllDevices(engineOutputDevices.toTypeAddrVector())) {
4456 continue;
4457 }
4458 outputDevices = getMsdAudioOutDevices();
4459 }
jiabin2b9d5a12021-12-10 01:06:29 +00004460 for (const auto& curProfile : hwModule->getOutputProfiles()) {
jiabinc8f7dfc2022-01-06 18:42:08 +00004461 if (!curProfile->isCompatibleProfile(outputDevices,
jiabin2b9d5a12021-12-10 01:06:29 +00004462 config->sample_rate, nullptr /*updatedSamplingRate*/,
4463 config->format, nullptr /*updatedFormat*/,
4464 config->channel_mask, nullptr /*updatedChannelMask*/,
4465 flags)) {
4466 continue;
4467 }
4468 // reject profiles not corresponding to a device currently available
4469 if (!mAvailableOutputDevices.containsAtLeastOne(curProfile->getSupportedDevices())) {
4470 continue;
4471 }
Yinchu Chen9f667582023-10-10 09:44:54 +00004472 if (offloadPossible && ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD)
4473 != AUDIO_OUTPUT_FLAG_NONE)) {
jiabinc6132d62022-01-01 07:36:31 +00004474 if ((directMode & AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED)
jiabin2b9d5a12021-12-10 01:06:29 +00004475 != AUDIO_DIRECT_NOT_SUPPORTED) {
4476 // Already reports offload gapless supported. No need to report offload support.
4477 continue;
4478 }
4479 if ((curProfile->getFlags() & AUDIO_OUTPUT_FLAG_GAPLESS_OFFLOAD)
4480 != AUDIO_OUTPUT_FLAG_NONE) {
4481 // If offload gapless is reported, no need to report offload support.
4482 directMode = (audio_direct_mode_t) ((directMode &
4483 ~AUDIO_DIRECT_OFFLOAD_SUPPORTED) |
4484 AUDIO_DIRECT_OFFLOAD_GAPLESS_SUPPORTED);
4485 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004486 directMode = (audio_direct_mode_t)(directMode | AUDIO_DIRECT_OFFLOAD_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004487 }
4488 } else {
Dorin Drimusfae3c642022-03-17 18:36:30 +01004489 directMode = (audio_direct_mode_t) (directMode | AUDIO_DIRECT_BITSTREAM_SUPPORTED);
jiabin2b9d5a12021-12-10 01:06:29 +00004490 }
4491 }
4492 }
4493 return directMode;
4494}
4495
Dorin Drimusf2196d82022-01-03 12:11:18 +01004496status_t AudioPolicyManager::getDirectProfilesForAttributes(const audio_attributes_t* attr,
4497 AudioProfileVector& audioProfilesVector) {
Dorin Drimus17112632022-09-23 15:28:51 +00004498 if (mEffects.isNonOffloadableEffectEnabled()) {
4499 return OK;
4500 }
jiabinf1c73972022-04-14 16:28:52 -07004501 DeviceVector devices;
4502 status_t status = getDevicesForAttributes(*attr, devices, false /* forVolume */);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004503 if (status != OK) {
4504 return status;
4505 }
4506 ALOGV("%s: found %zu output devices for attributes.", __func__, devices.size());
4507 if (devices.empty()) {
4508 return OK; // no output devices for the attributes
4509 }
jiabinf1c73972022-04-14 16:28:52 -07004510 return getProfilesForDevices(devices, audioProfilesVector,
4511 AUDIO_OUTPUT_FLAG_DIRECT /*flags*/, false /*isInput*/);
Dorin Drimusf2196d82022-01-03 12:11:18 +01004512}
4513
jiabina84c3d32022-12-02 18:59:55 +00004514status_t AudioPolicyManager::getSupportedMixerAttributes(
4515 audio_port_handle_t portId, std::vector<audio_mixer_attributes_t> &mixerAttrs) {
4516 ALOGV("%s, portId=%d", __func__, portId);
4517 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4518 if (deviceDescriptor == nullptr) {
4519 ALOGE("%s the requested device is currently unavailable", __func__);
4520 return BAD_VALUE;
4521 }
jiabin96daffc2023-05-11 17:51:55 +00004522 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4523 ALOGE("%s the requested device(type=%#x) is not usb device", __func__,
4524 deviceDescriptor->type());
4525 return BAD_VALUE;
4526 }
jiabina84c3d32022-12-02 18:59:55 +00004527 for (const auto& hwModule : mHwModules) {
4528 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4529 if (curProfile->supportsDevice(deviceDescriptor)) {
4530 curProfile->toSupportedMixerAttributes(&mixerAttrs);
4531 }
4532 }
4533 }
4534 return NO_ERROR;
4535}
4536
4537status_t AudioPolicyManager::setPreferredMixerAttributes(
4538 const audio_attributes_t *attr,
4539 audio_port_handle_t portId,
4540 uid_t uid,
4541 const audio_mixer_attributes_t *mixerAttributes) {
4542 ALOGV("%s, attr=%s, mixerAttributes={format=%#x, channelMask=%#x, samplingRate=%u, "
4543 "mixerBehavior=%d}, uid=%d, portId=%u",
4544 __func__, toString(*attr).c_str(), mixerAttributes->config.format,
4545 mixerAttributes->config.channel_mask, mixerAttributes->config.sample_rate,
4546 mixerAttributes->mixer_behavior, uid, portId);
4547 if (attr->usage != AUDIO_USAGE_MEDIA) {
4548 ALOGE("%s failed, only media is allowed, the given usage is %d", __func__, attr->usage);
4549 return BAD_VALUE;
4550 }
4551 sp<DeviceDescriptor> deviceDescriptor = mAvailableOutputDevices.getDeviceFromId(portId);
4552 if (deviceDescriptor == nullptr) {
4553 ALOGE("%s the requested device is currently unavailable", __func__);
4554 return BAD_VALUE;
4555 }
4556 if (!audio_is_usb_out_device(deviceDescriptor->type())) {
4557 ALOGE("%s(%d), type=%d, is not a usb output device",
4558 __func__, portId, deviceDescriptor->type());
4559 return BAD_VALUE;
4560 }
4561
4562 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
4563 audio_flags_to_audio_output_flags(attr->flags, &flags);
4564 flags = (audio_output_flags_t) (flags |
4565 audio_output_flags_from_mixer_behavior(mixerAttributes->mixer_behavior));
4566 sp<IOProfile> profile = nullptr;
4567 DeviceVector devices(deviceDescriptor);
4568 for (const auto& hwModule : mHwModules) {
4569 for (const auto& curProfile : hwModule->getOutputProfiles()) {
4570 if (curProfile->hasDynamicAudioProfile()
4571 && curProfile->isCompatibleProfile(devices,
4572 mixerAttributes->config.sample_rate,
4573 nullptr /*updatedSamplingRate*/,
4574 mixerAttributes->config.format,
4575 nullptr /*updatedFormat*/,
4576 mixerAttributes->config.channel_mask,
4577 nullptr /*updatedChannelMask*/,
4578 flags,
4579 false /*exactMatchRequiredForInputFlags*/)) {
4580 profile = curProfile;
4581 break;
4582 }
4583 }
4584 }
4585 if (profile == nullptr) {
4586 ALOGE("%s, there is no compatible profile found", __func__);
4587 return BAD_VALUE;
4588 }
4589
4590 sp<PreferredMixerAttributesInfo> mixerAttrInfo =
4591 sp<PreferredMixerAttributesInfo>::make(
4592 uid, portId, profile, flags, *mixerAttributes);
4593 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4594 mPreferredMixerAttrInfos[portId][strategy] = mixerAttrInfo;
4595
4596 // If 1) there is any client from the preferred mixer configuration owner that is currently
4597 // active and matches the strategy and 2) current output is on the preferred device and the
4598 // mixer configuration doesn't match the preferred one, reopen output with preferred mixer
4599 // configuration.
4600 std::vector<audio_io_handle_t> outputsToReopen;
4601 for (size_t i = 0; i < mOutputs.size(); i++) {
4602 const auto output = mOutputs.valueAt(i);
jiabin3ff8d7d2022-12-13 06:27:44 +00004603 if (output->mProfile == profile && output->devices().onlyContainsDevice(deviceDescriptor)) {
4604 if (output->isConfigurationMatched(mixerAttributes->config, flags)) {
4605 output->mUsePreferredMixerAttributes = true;
4606 } else {
4607 for (const auto &client: output->getActiveClients()) {
4608 if (client->uid() == uid && client->strategy() == strategy) {
4609 client->setIsInvalid();
4610 outputsToReopen.push_back(output->mIoHandle);
4611 }
jiabina84c3d32022-12-02 18:59:55 +00004612 }
4613 }
4614 }
4615 }
4616 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
4617 config.sample_rate = mixerAttributes->config.sample_rate;
4618 config.channel_mask = mixerAttributes->config.channel_mask;
4619 config.format = mixerAttributes->config.format;
4620 for (const auto output : outputsToReopen) {
jiabin3ff8d7d2022-12-13 06:27:44 +00004621 sp<SwAudioOutputDescriptor> desc =
4622 reopenOutput(mOutputs.valueFor(output), &config, flags, __func__);
4623 if (desc == nullptr) {
4624 ALOGE("%s, failed to reopen output with preferred mixer attributes", __func__);
4625 continue;
4626 }
4627 desc->mUsePreferredMixerAttributes = true;
jiabina84c3d32022-12-02 18:59:55 +00004628 }
4629
4630 return NO_ERROR;
4631}
4632
4633sp<PreferredMixerAttributesInfo> AudioPolicyManager::getPreferredMixerAttributesInfo(
jiabind9a58d32023-06-01 17:57:30 +00004634 audio_port_handle_t devicePortId,
4635 product_strategy_t strategy,
4636 bool activeBitPerfectPreferred) {
jiabina84c3d32022-12-02 18:59:55 +00004637 auto it = mPreferredMixerAttrInfos.find(devicePortId);
4638 if (it == mPreferredMixerAttrInfos.end()) {
4639 return nullptr;
4640 }
jiabind9a58d32023-06-01 17:57:30 +00004641 if (activeBitPerfectPreferred) {
4642 for (auto [strategy, info] : it->second) {
4643 if ((info->getFlags() & AUDIO_OUTPUT_FLAG_BIT_PERFECT) != AUDIO_OUTPUT_FLAG_NONE
4644 && info->getActiveClientCount() != 0) {
4645 return info;
4646 }
4647 }
jiabina84c3d32022-12-02 18:59:55 +00004648 }
jiabind9a58d32023-06-01 17:57:30 +00004649 auto strategyMatchedMixerAttrInfoIt = it->second.find(strategy);
4650 return strategyMatchedMixerAttrInfoIt == it->second.end()
4651 ? nullptr : strategyMatchedMixerAttrInfoIt->second;
jiabina84c3d32022-12-02 18:59:55 +00004652}
4653
4654status_t AudioPolicyManager::getPreferredMixerAttributes(
4655 const audio_attributes_t *attr,
4656 audio_port_handle_t portId,
4657 audio_mixer_attributes_t* mixerAttributes) {
4658 sp<PreferredMixerAttributesInfo> info = getPreferredMixerAttributesInfo(
4659 portId, mEngine->getProductStrategyForAttributes(*attr));
4660 if (info == nullptr) {
4661 return NAME_NOT_FOUND;
4662 }
4663 *mixerAttributes = info->getMixerAttributes();
4664 return NO_ERROR;
4665}
4666
4667status_t AudioPolicyManager::clearPreferredMixerAttributes(const audio_attributes_t *attr,
4668 audio_port_handle_t portId,
4669 uid_t uid) {
4670 const product_strategy_t strategy = mEngine->getProductStrategyForAttributes(*attr);
4671 const auto preferredMixerAttrInfo = getPreferredMixerAttributesInfo(portId, strategy);
4672 if (preferredMixerAttrInfo == nullptr) {
4673 return NAME_NOT_FOUND;
4674 }
4675 if (preferredMixerAttrInfo->getUid() != uid) {
4676 ALOGE("%s, requested uid=%d, owned uid=%d",
4677 __func__, uid, preferredMixerAttrInfo->getUid());
4678 return PERMISSION_DENIED;
4679 }
4680 mPreferredMixerAttrInfos[portId].erase(strategy);
4681 if (mPreferredMixerAttrInfos[portId].empty()) {
4682 mPreferredMixerAttrInfos.erase(portId);
4683 }
4684
4685 // Reconfig existing output
4686 std::vector<audio_io_handle_t> potentialOutputsToReopen;
4687 for (size_t i = 0; i < mOutputs.size(); i++) {
4688 if (mOutputs.valueAt(i)->mProfile == preferredMixerAttrInfo->getProfile()) {
4689 potentialOutputsToReopen.push_back(mOutputs.keyAt(i));
4690 }
4691 }
4692 for (const auto output : potentialOutputsToReopen) {
4693 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
4694 if (desc->isConfigurationMatched(preferredMixerAttrInfo->getConfigBase(),
4695 preferredMixerAttrInfo->getFlags())) {
4696 reopenOutput(desc, nullptr /*config*/, AUDIO_OUTPUT_FLAG_NONE, __func__);
4697 }
4698 }
4699 return NO_ERROR;
4700}
4701
Eric Laurent6a94d692014-05-20 11:18:06 -07004702status_t AudioPolicyManager::listAudioPorts(audio_port_role_t role,
4703 audio_port_type_t type,
4704 unsigned int *num_ports,
jiabin19cdba52020-11-24 11:28:58 -08004705 struct audio_port_v7 *ports,
Eric Laurent6a94d692014-05-20 11:18:06 -07004706 unsigned int *generation)
4707{
jiabin19cdba52020-11-24 11:28:58 -08004708 if (num_ports == nullptr || (*num_ports != 0 && ports == nullptr) ||
4709 generation == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004710 return BAD_VALUE;
4711 }
4712 ALOGV("listAudioPorts() role %d type %d num_ports %d ports %p", role, type, *num_ports, ports);
jiabin19cdba52020-11-24 11:28:58 -08004713 if (ports == nullptr) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004714 *num_ports = 0;
4715 }
4716
4717 size_t portsWritten = 0;
4718 size_t portsMax = *num_ports;
4719 *num_ports = 0;
4720 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004721 // do not report devices with type AUDIO_DEVICE_IN_STUB or AUDIO_DEVICE_OUT_STUB
4722 // as they are used by stub HALs by convention
Eric Laurent6a94d692014-05-20 11:18:06 -07004723 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004724 for (const auto& dev : mAvailableOutputDevices) {
4725 if (dev->type() == AUDIO_DEVICE_OUT_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004726 continue;
4727 }
4728 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004729 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004730 }
4731 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004732 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004733 }
4734 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004735 for (const auto& dev : mAvailableInputDevices) {
4736 if (dev->type() == AUDIO_DEVICE_IN_STUB) {
Eric Laurent5a2b6292016-04-14 18:05:57 -07004737 continue;
4738 }
4739 if (portsWritten < portsMax) {
Mikhail Naganovcf84e592017-12-07 11:25:11 -08004740 dev->toAudioPort(&ports[portsWritten++]);
Eric Laurent5a2b6292016-04-14 18:05:57 -07004741 }
4742 (*num_ports)++;
Eric Laurent6a94d692014-05-20 11:18:06 -07004743 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004744 }
4745 }
4746 if (type == AUDIO_PORT_TYPE_NONE || type == AUDIO_PORT_TYPE_MIX) {
4747 if (role == AUDIO_PORT_ROLE_SINK || role == AUDIO_PORT_ROLE_NONE) {
4748 for (size_t i = 0; i < mInputs.size() && portsWritten < portsMax; i++) {
4749 mInputs[i]->toAudioPort(&ports[portsWritten++]);
4750 }
4751 *num_ports += mInputs.size();
4752 }
4753 if (role == AUDIO_PORT_ROLE_SOURCE || role == AUDIO_PORT_ROLE_NONE) {
Eric Laurent84c70242014-06-23 08:46:27 -07004754 size_t numOutputs = 0;
4755 for (size_t i = 0; i < mOutputs.size(); i++) {
4756 if (!mOutputs[i]->isDuplicated()) {
4757 numOutputs++;
4758 if (portsWritten < portsMax) {
4759 mOutputs[i]->toAudioPort(&ports[portsWritten++]);
4760 }
4761 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004762 }
Eric Laurent84c70242014-06-23 08:46:27 -07004763 *num_ports += numOutputs;
Eric Laurent6a94d692014-05-20 11:18:06 -07004764 }
4765 }
jiabina84c3d32022-12-02 18:59:55 +00004766
Eric Laurent6a94d692014-05-20 11:18:06 -07004767 *generation = curAudioPortGeneration();
Mark Salyzynbeb9e302014-06-18 16:33:15 -07004768 ALOGV("listAudioPorts() got %zu ports needed %d", portsWritten, *num_ports);
Eric Laurent6a94d692014-05-20 11:18:06 -07004769 return NO_ERROR;
4770}
4771
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004772status_t AudioPolicyManager::listDeclaredDevicePorts(media::AudioPortRole role,
4773 std::vector<media::AudioPortFw>* _aidl_return) {
4774 auto pushPort = [&](const sp<DeviceDescriptor>& dev) -> status_t {
4775 audio_port_v7 port;
4776 dev->toAudioPort(&port);
4777 auto aidlPort = VALUE_OR_RETURN_STATUS(legacy2aidl_audio_port_v7_AudioPortFw(port));
4778 _aidl_return->push_back(std::move(aidlPort));
4779 return OK;
4780 };
4781
Mikhail Naganov68e3f642023-04-28 13:06:32 -07004782 for (const auto& module : mHwModules) {
Mikhail Naganov5edc5ed2023-03-23 14:52:15 -07004783 for (const auto& dev : module->getDeclaredDevices()) {
4784 if (role == media::AudioPortRole::NONE ||
4785 ((role == media::AudioPortRole::SOURCE)
4786 == audio_is_input_device(dev->type()))) {
4787 RETURN_STATUS_IF_ERROR(pushPort(dev));
4788 }
4789 }
4790 }
4791 return OK;
4792}
4793
jiabin19cdba52020-11-24 11:28:58 -08004794status_t AudioPolicyManager::getAudioPort(struct audio_port_v7 *port)
Eric Laurent6a94d692014-05-20 11:18:06 -07004795{
Eric Laurent99fcae42018-05-17 16:59:18 -07004796 if (port == nullptr || port->id == AUDIO_PORT_HANDLE_NONE) {
4797 return BAD_VALUE;
4798 }
4799 sp<DeviceDescriptor> dev = mAvailableOutputDevices.getDeviceFromId(port->id);
4800 if (dev != 0) {
4801 dev->toAudioPort(port);
4802 return NO_ERROR;
4803 }
4804 dev = mAvailableInputDevices.getDeviceFromId(port->id);
4805 if (dev != 0) {
4806 dev->toAudioPort(port);
4807 return NO_ERROR;
4808 }
4809 sp<SwAudioOutputDescriptor> out = mOutputs.getOutputFromId(port->id);
4810 if (out != 0) {
4811 out->toAudioPort(port);
4812 return NO_ERROR;
4813 }
4814 sp<AudioInputDescriptor> in = mInputs.getInputFromId(port->id);
4815 if (in != 0) {
4816 in->toAudioPort(port);
4817 return NO_ERROR;
4818 }
4819 return BAD_VALUE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004820}
4821
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004822status_t AudioPolicyManager::createAudioPatch(const struct audio_patch *patch,
4823 audio_patch_handle_t *handle,
4824 uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07004825{
François Gaffieafd4cea2019-11-18 15:50:22 +01004826 ALOGV("%s", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07004827 if (handle == NULL || patch == NULL) {
4828 return BAD_VALUE;
4829 }
François Gaffieafd4cea2019-11-18 15:50:22 +01004830 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Mikhail Naganovac9858b2018-06-15 13:12:37 -07004831 if (!audio_patch_is_valid(patch)) {
Eric Laurent874c42872014-08-08 15:13:39 -07004832 return BAD_VALUE;
4833 }
4834 // only one source per audio patch supported for now
4835 if (patch->num_sources > 1) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004836 return INVALID_OPERATION;
4837 }
Eric Laurent874c42872014-08-08 15:13:39 -07004838 if (patch->sources[0].role != AUDIO_PORT_ROLE_SOURCE) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004839 return INVALID_OPERATION;
4840 }
Eric Laurent874c42872014-08-08 15:13:39 -07004841 for (size_t i = 0; i < patch->num_sinks; i++) {
4842 if (patch->sinks[i].role != AUDIO_PORT_ROLE_SINK) {
4843 return INVALID_OPERATION;
4844 }
4845 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004846
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02004847 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
4848 sp<DeviceDescriptor> sinkDevice = mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id);
4849 if (srcDevice == nullptr || sinkDevice == nullptr) {
4850 ALOGW("%s could not create patch, invalid sink and/or source device(s)", __func__);
4851 return BAD_VALUE;
4852 }
4853 ALOGV("%s between source %s and sink %s", __func__,
4854 srcDevice->toString().c_str(), sinkDevice->toString().c_str());
4855 audio_port_handle_t portId = PolicyAudioPort::getNextUniqueId();
4856 // Default attributes, default volume priority, not to infer with non raw audio patches.
4857 audio_attributes_t attributes = attributes_initializer(AUDIO_USAGE_MEDIA);
4858 const struct audio_port_config *source = &patch->sources[0];
4859 sp<SourceClientDescriptor> sourceDesc =
4860 new InternalSourceClientDescriptor(
4861 portId, uid, attributes, *source, srcDevice, sinkDevice,
4862 mEngine->getProductStrategyForAttributes(attributes), toVolumeSource(attributes));
4863
4864 status_t status =
4865 connectAudioSourceToSink(sourceDesc, sinkDevice, patch, *handle, uid, 0 /* delayMs */);
4866
4867 if (status != NO_ERROR) {
4868 return INVALID_OPERATION;
4869 }
4870 mAudioSources.add(portId, sourceDesc);
4871 return NO_ERROR;
4872}
4873
4874status_t AudioPolicyManager::connectAudioSourceToSink(
4875 const sp<SourceClientDescriptor>& sourceDesc, const sp<DeviceDescriptor> &sinkDevice,
4876 const struct audio_patch *patch,
4877 audio_patch_handle_t &handle,
4878 uid_t uid, uint32_t delayMs)
4879{
4880 status_t status = createAudioPatchInternal(patch, &handle, uid, delayMs, sourceDesc);
4881 if (status != NO_ERROR || mAudioPatches.indexOfKey(handle) < 0) {
4882 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
4883 return INVALID_OPERATION;
4884 }
4885 sourceDesc->connect(handle, sinkDevice);
4886 if (isMsdPatch(handle)) {
4887 return NO_ERROR;
4888 }
4889 // SW Bridge? (@todo: HW bridge, keep track of HwOutput for device selection "reconsideration")
4890 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
4891 ALOG_ASSERT(swOutput != nullptr, "%s: a swOutput shall always be associated", __func__);
4892 if (swOutput->getClient(sourceDesc->portId()) != nullptr) {
4893 ALOGW("%s source portId has already been attached to outputDesc", __func__);
4894 goto FailurePatchAdded;
4895 }
4896 status = swOutput->start();
4897 if (status != NO_ERROR) {
4898 goto FailureSourceAdded;
4899 }
4900 swOutput->addClient(sourceDesc);
4901 status = startSource(swOutput, sourceDesc, &delayMs);
4902 if (status != NO_ERROR) {
4903 ALOGW("%s failed to start source, error %d", __FUNCTION__, status);
4904 goto FailureSourceActive;
4905 }
4906 if (delayMs != 0) {
4907 usleep(delayMs * 1000);
4908 }
4909 return NO_ERROR;
4910
4911FailureSourceActive:
4912 swOutput->stop();
4913 releaseOutput(sourceDesc->portId());
4914FailureSourceAdded:
4915 sourceDesc->setSwOutput(nullptr);
4916FailurePatchAdded:
4917 releaseAudioPatchInternal(handle);
4918 return INVALID_OPERATION;
4919}
4920
4921status_t AudioPolicyManager::createAudioPatchInternal(const struct audio_patch *patch,
4922 audio_patch_handle_t *handle,
4923 uid_t uid, uint32_t delayMs,
4924 const sp<SourceClientDescriptor>& sourceDesc)
4925{
4926 ALOGV("%s num sources %d num sinks %d", __func__, patch->num_sources, patch->num_sinks);
Eric Laurent6a94d692014-05-20 11:18:06 -07004927 sp<AudioPatch> patchDesc;
4928 ssize_t index = mAudioPatches.indexOfKey(*handle);
4929
François Gaffieafd4cea2019-11-18 15:50:22 +01004930 ALOGV("%s source id %d role %d type %d", __func__, patch->sources[0].id,
4931 patch->sources[0].role,
4932 patch->sources[0].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004933#if LOG_NDEBUG == 0
4934 for (size_t i = 0; i < patch->num_sinks; i++) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004935 ALOGV("%s sink %zu: id %d role %d type %d", __func__ ,i, patch->sinks[i].id,
4936 patch->sinks[i].role,
4937 patch->sinks[i].type);
Eric Laurent874c42872014-08-08 15:13:39 -07004938 }
4939#endif
Eric Laurent6a94d692014-05-20 11:18:06 -07004940
4941 if (index >= 0) {
4942 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01004943 ALOGV("%s mUidCached %d patchDesc->mUid %d uid %d",
4944 __func__, mUidCached, patchDesc->getUid(), uid);
4945 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004946 return INVALID_OPERATION;
4947 }
4948 } else {
Glenn Kastena13cde92016-03-28 15:26:02 -07004949 *handle = AUDIO_PATCH_HANDLE_NONE;
Eric Laurent6a94d692014-05-20 11:18:06 -07004950 }
4951
4952 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07004953 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004954 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004955 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004956 return BAD_VALUE;
4957 }
Eric Laurent84c70242014-06-23 08:46:27 -07004958 ALOG_ASSERT(!outputDesc->isDuplicated(),"duplicated output %d in source in ports",
4959 outputDesc->mIoHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07004960 if (patchDesc != 0) {
4961 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004962 ALOGV("%s source id differs for patch current id %d new id %d",
4963 __func__, patchDesc->mPatch.sources[0].id, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07004964 return BAD_VALUE;
4965 }
4966 }
Eric Laurent874c42872014-08-08 15:13:39 -07004967 DeviceVector devices;
4968 for (size_t i = 0; i < patch->num_sinks; i++) {
4969 // Only support mix to devices connection
4970 // TODO add support for mix to mix connection
4971 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004972 ALOGV("%s source mix but sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07004973 return INVALID_OPERATION;
4974 }
4975 sp<DeviceDescriptor> devDesc =
4976 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
4977 if (devDesc == 0) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004978 ALOGV("%s out device not found for id %d", __func__, patch->sinks[i].id);
Eric Laurent874c42872014-08-08 15:13:39 -07004979 return BAD_VALUE;
4980 }
Eric Laurent6a94d692014-05-20 11:18:06 -07004981
François Gaffie11d30102018-11-02 16:09:09 +01004982 if (!outputDesc->mProfile->isCompatibleProfile(DeviceVector(devDesc),
Eric Laurent874c42872014-08-08 15:13:39 -07004983 patch->sources[0].sample_rate,
François Gaffie53615e22015-03-19 09:24:12 +01004984 NULL, // updatedSamplingRate
4985 patch->sources[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07004986 NULL, // updatedFormat
François Gaffie53615e22015-03-19 09:24:12 +01004987 patch->sources[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07004988 NULL, // updatedChannelMask
François Gaffie53615e22015-03-19 09:24:12 +01004989 AUDIO_OUTPUT_FLAG_NONE /*FIXME*/)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01004990 ALOGV("%s profile not supported for device %08x", __func__, devDesc->type());
Eric Laurent874c42872014-08-08 15:13:39 -07004991 return INVALID_OPERATION;
4992 }
4993 devices.add(devDesc);
4994 }
4995 if (devices.size() == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07004996 return INVALID_OPERATION;
4997 }
Eric Laurent874c42872014-08-08 15:13:39 -07004998
Eric Laurent6a94d692014-05-20 11:18:06 -07004999 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005000 ALOGV("%s setting device %s on output %d",
5001 __func__, dumpDeviceTypes(devices.types()).c_str(), outputDesc->mIoHandle);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305002 setOutputDevices(__func__, outputDesc, devices, true, 0, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005003 index = mAudioPatches.indexOfKey(*handle);
5004 if (index >= 0) {
5005 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005006 ALOGW("%s setOutputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005007 }
5008 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005009 patchDesc->setUid(uid);
5010 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005011 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005012 ALOGW("%s setOutputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005013 return INVALID_OPERATION;
5014 }
5015 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5016 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
5017 // input device to input mix connection
Eric Laurent874c42872014-08-08 15:13:39 -07005018 // only one sink supported when connecting an input device to a mix
5019 if (patch->num_sinks > 1) {
5020 return INVALID_OPERATION;
5021 }
François Gaffie53615e22015-03-19 09:24:12 +01005022 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005023 if (inputDesc == NULL) {
5024 return BAD_VALUE;
5025 }
5026 if (patchDesc != 0) {
5027 if (patchDesc->mPatch.sinks[0].id != patch->sinks[0].id) {
5028 return BAD_VALUE;
5029 }
5030 }
François Gaffie11d30102018-11-02 16:09:09 +01005031 sp<DeviceDescriptor> device =
Eric Laurent6a94d692014-05-20 11:18:06 -07005032 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005033 if (device == 0) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005034 return BAD_VALUE;
5035 }
5036
François Gaffie11d30102018-11-02 16:09:09 +01005037 if (!inputDesc->mProfile->isCompatibleProfile(DeviceVector(device),
Eric Laurent275e8e92014-11-30 15:14:47 -08005038 patch->sinks[0].sample_rate,
5039 NULL, /*updatedSampleRate*/
5040 patch->sinks[0].format,
Andy Hungf129b032015-04-07 13:45:50 -07005041 NULL, /*updatedFormat*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005042 patch->sinks[0].channel_mask,
Andy Hungf129b032015-04-07 13:45:50 -07005043 NULL, /*updatedChannelMask*/
Eric Laurent275e8e92014-11-30 15:14:47 -08005044 // FIXME for the parameter type,
5045 // and the NONE
5046 (audio_output_flags_t)
Glenn Kasten6a8ab052014-07-24 14:08:35 -07005047 AUDIO_INPUT_FLAG_NONE)) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005048 return INVALID_OPERATION;
5049 }
5050 // TODO: reconfigure output format and channels here
François Gaffieafd4cea2019-11-18 15:50:22 +01005051 ALOGV("%s setting device %s on output %d", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01005052 device->toString().c_str(), inputDesc->mIoHandle);
5053 setInputDevice(inputDesc->mIoHandle, device, true, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005054 index = mAudioPatches.indexOfKey(*handle);
5055 if (index >= 0) {
5056 if (patchDesc != 0 && patchDesc != mAudioPatches.valueAt(index)) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005057 ALOGW("%s setInputDevice() did not reuse the patch provided", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005058 }
5059 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005060 patchDesc->setUid(uid);
5061 ALOGV("%s success", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005062 } else {
François Gaffieafd4cea2019-11-18 15:50:22 +01005063 ALOGW("%s setInputDevice() failed to create a patch", __func__);
Eric Laurent6a94d692014-05-20 11:18:06 -07005064 return INVALID_OPERATION;
5065 }
5066 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
5067 // device to device connection
5068 if (patchDesc != 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005069 if (patchDesc->mPatch.sources[0].id != patch->sources[0].id) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005070 return BAD_VALUE;
5071 }
5072 }
François Gaffie11d30102018-11-02 16:09:09 +01005073 sp<DeviceDescriptor> srcDevice =
Eric Laurent6a94d692014-05-20 11:18:06 -07005074 mAvailableInputDevices.getDeviceFromId(patch->sources[0].id);
François Gaffie11d30102018-11-02 16:09:09 +01005075 if (srcDevice == 0) {
Eric Laurent58f8eb72014-09-12 16:19:41 -07005076 return BAD_VALUE;
5077 }
Eric Laurent874c42872014-08-08 15:13:39 -07005078
Eric Laurent6a94d692014-05-20 11:18:06 -07005079 //update source and sink with our own data as the data passed in the patch may
5080 // be incomplete.
François Gaffieafd4cea2019-11-18 15:50:22 +01005081 PatchBuilder patchBuilder;
5082 audio_port_config sourcePortConfig = {};
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005083
5084 // if first sink is to MSD, establish single MSD patch
5085 if (getMsdAudioOutDevices().contains(
5086 mAvailableOutputDevices.getDeviceFromId(patch->sinks[0].id))) {
5087 ALOGV("%s patching to MSD", __FUNCTION__);
5088 patchBuilder = buildMsdPatch(false /*msdIsSource*/, srcDevice);
5089 goto installPatch;
5090 }
5091
François Gaffieafd4cea2019-11-18 15:50:22 +01005092 srcDevice->toAudioPortConfig(&sourcePortConfig, &patch->sources[0]);
5093 patchBuilder.addSource(sourcePortConfig);
Eric Laurent6a94d692014-05-20 11:18:06 -07005094
Eric Laurent874c42872014-08-08 15:13:39 -07005095 for (size_t i = 0; i < patch->num_sinks; i++) {
5096 if (patch->sinks[i].type != AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005097 ALOGV("%s source device but one sink is not a device", __func__);
Eric Laurent874c42872014-08-08 15:13:39 -07005098 return INVALID_OPERATION;
5099 }
François Gaffie11d30102018-11-02 16:09:09 +01005100 sp<DeviceDescriptor> sinkDevice =
Eric Laurent874c42872014-08-08 15:13:39 -07005101 mAvailableOutputDevices.getDeviceFromId(patch->sinks[i].id);
François Gaffie11d30102018-11-02 16:09:09 +01005102 if (sinkDevice == 0) {
Eric Laurent874c42872014-08-08 15:13:39 -07005103 return BAD_VALUE;
5104 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005105 audio_port_config sinkPortConfig = {};
5106 sinkDevice->toAudioPortConfig(&sinkPortConfig, &patch->sinks[i]);
5107 patchBuilder.addSink(sinkPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005108
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005109 // Whatever Sw or Hw bridge, we do attach an SwOutput to an Audio Source for
5110 // volume management purpose (tracking activity)
5111 // In case of Hw bridge, it is a Work Around. The mixPort used is the one declared
5112 // in config XML to reach the sink so that is can be declared as available.
5113 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurent78b07302022-10-07 16:20:34 +02005114 sp<SwAudioOutputDescriptor> outputDesc;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005115 if (!sourceDesc->isInternal()) {
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005116 // take care of dynamic routing for SwOutput selection,
5117 audio_attributes_t attributes = sourceDesc->attributes();
5118 audio_stream_type_t stream = sourceDesc->stream();
5119 audio_attributes_t resultAttr;
5120 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
5121 config.sample_rate = sourceDesc->config().sample_rate;
François Gaffie2a24db42022-04-04 16:45:02 +02005122 audio_channel_mask_t sourceMask = sourceDesc->config().channel_mask;
5123 config.channel_mask =
5124 (audio_channel_mask_get_representation(sourceMask)
5125 == AUDIO_CHANNEL_REPRESENTATION_INDEX) ? sourceMask
5126 : audio_channel_mask_in_to_out(sourceMask);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005127 config.format = sourceDesc->config().format;
5128 audio_output_flags_t flags = AUDIO_OUTPUT_FLAG_NONE;
5129 audio_port_handle_t selectedDeviceId = AUDIO_PORT_HANDLE_NONE;
5130 bool isRequestedDeviceForExclusiveUse = false;
5131 output_type_t outputType;
Eric Laurentb0a7bc92022-04-05 15:06:08 +02005132 bool isSpatialized;
jiabinc658e452022-10-21 20:52:21 +00005133 bool isBitPerfect;
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005134 getOutputForAttrInt(&resultAttr, &output, AUDIO_SESSION_NONE, &attributes,
5135 &stream, sourceDesc->uid(), &config, &flags,
5136 &selectedDeviceId, &isRequestedDeviceForExclusiveUse,
jiabinc658e452022-10-21 20:52:21 +00005137 nullptr, &outputType, &isSpatialized, &isBitPerfect);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005138 if (output == AUDIO_IO_HANDLE_NONE) {
5139 ALOGV("%s no output for device %s",
5140 __FUNCTION__, sinkDevice->toString().c_str());
5141 return INVALID_OPERATION;
5142 }
5143 outputDesc = mOutputs.valueFor(output);
5144 if (outputDesc->isDuplicated()) {
5145 ALOGE("%s output is duplicated", __func__);
5146 return INVALID_OPERATION;
5147 }
François Gaffie7e39df22022-04-26 12:48:49 +02005148 bool closeOutput = outputDesc->mDirectOpenCount != 0;
5149 sourceDesc->setSwOutput(outputDesc, closeOutput);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005150 } else {
5151 // Same for "raw patches" aka created from createAudioPatch API
5152 SortedVector<audio_io_handle_t> outputs =
5153 getOutputsForDevices(DeviceVector(sinkDevice), mOutputs);
5154 // if the sink device is reachable via an opened output stream, request to
5155 // go via this output stream by adding a second source to the patch
5156 // description
5157 output = selectOutput(outputs);
5158 if (output == AUDIO_IO_HANDLE_NONE) {
5159 ALOGE("%s no output available for internal patch sink", __func__);
5160 return INVALID_OPERATION;
5161 }
5162 outputDesc = mOutputs.valueFor(output);
5163 if (outputDesc->isDuplicated()) {
5164 ALOGV("%s output for device %s is duplicated",
5165 __func__, sinkDevice->toString().c_str());
5166 return INVALID_OPERATION;
5167 }
François Gaffie7e39df22022-04-26 12:48:49 +02005168 sourceDesc->setSwOutput(outputDesc, /* closeOutput= */ false);
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005169 }
Eric Laurent3bcf8592015-04-03 12:13:24 -07005170 // create a software bridge in PatchPanel if:
Scott Randolphf3172402018-01-23 17:06:53 -08005171 // - source and sink devices are on different HW modules OR
Eric Laurent3bcf8592015-04-03 12:13:24 -07005172 // - audio HAL version is < 3.0
Francois Gaffie99896da2018-04-09 11:05:33 +02005173 // - audio HAL version is >= 3.0 but no route has been declared between devices
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005174 // - called from startAudioSource (aka sourceDesc is not internal) and source device
5175 // does not have a gain controller
François Gaffie11d30102018-11-02 16:09:09 +01005176 if (!srcDevice->hasSameHwModuleAs(sinkDevice) ||
5177 (srcDevice->getModuleVersionMajor() < 3) ||
François Gaffieafd4cea2019-11-18 15:50:22 +01005178 !srcDevice->getModule()->supportsPatch(srcDevice, sinkDevice) ||
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005179 (!sourceDesc->isInternal() &&
François Gaffieafd4cea2019-11-18 15:50:22 +01005180 srcDevice->getAudioPort()->getGains().size() == 0)) {
Eric Laurent3bcf8592015-04-03 12:13:24 -07005181 // support only one sink device for now to simplify output selection logic
Eric Laurent874c42872014-08-08 15:13:39 -07005182 if (patch->num_sinks > 1) {
Eric Laurent83b88082014-06-20 18:31:16 -07005183 return INVALID_OPERATION;
5184 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005185 sourceDesc->setUseSwBridge();
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02005186 if (outputDesc != nullptr) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005187 audio_port_config srcMixPortConfig = {};
Ytai Ben-Tsvic9d2a912021-11-22 16:43:09 -08005188 outputDesc->toAudioPortConfig(&srcMixPortConfig, nullptr);
François Gaffieafd4cea2019-11-18 15:50:22 +01005189 // for volume control, we may need a valid stream
Eric Laurent78b07302022-10-07 16:20:34 +02005190 srcMixPortConfig.ext.mix.usecase.stream =
5191 (!sourceDesc->isInternal() || isCallTxAudioSource(sourceDesc)) ?
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005192 mEngine->getStreamTypeForAttributes(sourceDesc->attributes()) :
5193 AUDIO_STREAM_PATCH;
François Gaffieafd4cea2019-11-18 15:50:22 +01005194 patchBuilder.addSource(srcMixPortConfig);
Eric Laurent874c42872014-08-08 15:13:39 -07005195 }
Eric Laurent83b88082014-06-20 18:31:16 -07005196 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005197 }
5198 // TODO: check from routing capabilities in config file and other conflicting patches
5199
Dean Wheatley8bee85a2021-02-10 16:02:23 +11005200installPatch:
François Gaffieafd4cea2019-11-18 15:50:22 +01005201 status_t status = installPatch(
5202 __func__, index, handle, patchBuilder.patch(), delayMs, uid, &patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07005203 if (status != NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005204 ALOGW("%s patch panel could not connect device patch, error %d", __func__, status);
Eric Laurent6a94d692014-05-20 11:18:06 -07005205 return INVALID_OPERATION;
5206 }
5207 } else {
5208 return BAD_VALUE;
5209 }
5210 } else {
5211 return BAD_VALUE;
5212 }
5213 return NO_ERROR;
5214}
5215
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005216status_t AudioPolicyManager::releaseAudioPatch(audio_patch_handle_t handle, uid_t uid)
Eric Laurent6a94d692014-05-20 11:18:06 -07005217{
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005218 ALOGV("%s patch %d", __func__, handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005219 ssize_t index = mAudioPatches.indexOfKey(handle);
5220
5221 if (index < 0) {
5222 return BAD_VALUE;
5223 }
5224 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01005225 ALOGV("%s() mUidCached %d patchDesc->mUid %d uid %d",
5226 __func__, mUidCached, patchDesc->getUid(), uid);
5227 if (patchDesc->getUid() != mUidCached && uid != patchDesc->getUid()) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005228 return INVALID_OPERATION;
5229 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005230 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5231 for (size_t i = 0; i < mAudioSources.size(); i++) {
5232 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5233 if (sourceDesc != nullptr && sourceDesc->getPatchHandle() == handle) {
5234 portId = sourceDesc->portId();
5235 break;
5236 }
5237 }
5238 return portId != AUDIO_PORT_HANDLE_NONE ?
5239 stopAudioSource(portId) : releaseAudioPatchInternal(handle);
François Gaffieafd4cea2019-11-18 15:50:22 +01005240}
Eric Laurent6a94d692014-05-20 11:18:06 -07005241
François Gaffieafd4cea2019-11-18 15:50:22 +01005242status_t AudioPolicyManager::releaseAudioPatchInternal(audio_patch_handle_t handle,
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005243 uint32_t delayMs,
5244 const sp<SourceClientDescriptor>& sourceDesc)
François Gaffieafd4cea2019-11-18 15:50:22 +01005245{
5246 ALOGV("%s patch %d", __func__, handle);
5247 if (mAudioPatches.indexOfKey(handle) < 0) {
5248 ALOGE("%s: no patch found with handle=%d", __func__, handle);
5249 return BAD_VALUE;
5250 }
5251 sp<AudioPatch> patchDesc = mAudioPatches.valueFor(handle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005252 struct audio_patch *patch = &patchDesc->mPatch;
François Gaffieafd4cea2019-11-18 15:50:22 +01005253 patchDesc->setUid(mUidCached);
Eric Laurent6a94d692014-05-20 11:18:06 -07005254 if (patch->sources[0].type == AUDIO_PORT_TYPE_MIX) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005255 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005256 if (outputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005257 ALOGV("%s output not found for id %d", __func__, patch->sources[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005258 return BAD_VALUE;
5259 }
5260
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305261 setOutputDevices(__func__, outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01005262 getNewOutputDevices(outputDesc, true /*fromCache*/),
5263 true,
5264 0,
5265 NULL);
Eric Laurent6a94d692014-05-20 11:18:06 -07005266 } else if (patch->sources[0].type == AUDIO_PORT_TYPE_DEVICE) {
5267 if (patch->sinks[0].type == AUDIO_PORT_TYPE_MIX) {
François Gaffie53615e22015-03-19 09:24:12 +01005268 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005269 if (inputDesc == NULL) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005270 ALOGV("%s input not found for id %d", __func__, patch->sinks[0].id);
Eric Laurent6a94d692014-05-20 11:18:06 -07005271 return BAD_VALUE;
5272 }
5273 setInputDevice(inputDesc->mIoHandle,
Eric Laurentfb66dd92016-01-28 18:32:03 -08005274 getNewInputDevice(inputDesc),
Eric Laurent6a94d692014-05-20 11:18:06 -07005275 true,
5276 NULL);
5277 } else if (patch->sinks[0].type == AUDIO_PORT_TYPE_DEVICE) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005278 status_t status =
5279 mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
5280 ALOGV("%s patch panel returned %d patchHandle %d",
5281 __func__, status, patchDesc->getAfHandle());
5282 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07005283 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07005284 mpClientInterface->onAudioPatchListUpdate();
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005285 // SW or HW Bridge
5286 sp<SwAudioOutputDescriptor> outputDesc = nullptr;
5287 audio_patch_handle_t patchHandle = AUDIO_PATCH_HANDLE_NONE;
Francois Gaffie7feb8542020-04-06 17:39:47 +02005288 if (patch->num_sources > 1 && patch->sources[1].type == AUDIO_PORT_TYPE_MIX) {
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005289 outputDesc = mOutputs.getOutputFromId(patch->sources[1].id);
5290 } else if (patch->num_sources == 1 && sourceDesc != nullptr) {
5291 outputDesc = sourceDesc->swOutput().promote();
5292 }
5293 if (outputDesc == nullptr) {
5294 ALOGW("%s no output for id %d", __func__, patch->sources[0].id);
5295 // releaseOutput has already called closeOutput in case of direct output
5296 return NO_ERROR;
5297 }
François Gaffie7e39df22022-04-26 12:48:49 +02005298 patchHandle = outputDesc->getPatchHandle();
François Gaffie7e39df22022-04-26 12:48:49 +02005299 // While using a HwBridge, force reconsidering device only if not reusing an existing
5300 // output and no more activity on output (will force to close).
François Gaffie150fcc62023-09-15 11:02:39 +02005301 const bool force = sourceDesc->canCloseOutput() && !outputDesc->isActive();
François Gaffie7e39df22022-04-26 12:48:49 +02005302 // APM pattern is to have always outputs opened / patch realized for reachable devices.
5303 // Update device may result to NONE (empty), coupled with force, it releases the patch.
5304 // Reconsider device only for cases:
5305 // 1 / Active Output
5306 // 2 / Inactive Output previously hosting HwBridge
5307 // 3 / Inactive Output previously hosting SwBridge that can be closed.
5308 bool updateDevice = outputDesc->isActive() || !sourceDesc->useSwBridge() ||
5309 sourceDesc->canCloseOutput();
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305310 setOutputDevices(__func__, outputDesc,
François Gaffie7e39df22022-04-26 12:48:49 +02005311 updateDevice ? getNewOutputDevices(outputDesc, true /*fromCache*/) :
5312 outputDesc->devices(),
5313 force,
5314 0,
5315 patchHandle == AUDIO_PATCH_HANDLE_NONE ? nullptr : &patchHandle);
Eric Laurent6a94d692014-05-20 11:18:06 -07005316 } else {
5317 return BAD_VALUE;
5318 }
5319 } else {
5320 return BAD_VALUE;
5321 }
5322 return NO_ERROR;
5323}
5324
5325status_t AudioPolicyManager::listAudioPatches(unsigned int *num_patches,
5326 struct audio_patch *patches,
5327 unsigned int *generation)
5328{
François Gaffie53615e22015-03-19 09:24:12 +01005329 if (generation == NULL) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005330 return BAD_VALUE;
5331 }
Eric Laurent6a94d692014-05-20 11:18:06 -07005332 *generation = curAudioPortGeneration();
François Gaffie53615e22015-03-19 09:24:12 +01005333 return mAudioPatches.listAudioPatches(num_patches, patches);
Eric Laurent6a94d692014-05-20 11:18:06 -07005334}
5335
Eric Laurente1715a42014-05-20 11:30:42 -07005336status_t AudioPolicyManager::setAudioPortConfig(const struct audio_port_config *config)
Eric Laurent6a94d692014-05-20 11:18:06 -07005337{
Eric Laurente1715a42014-05-20 11:30:42 -07005338 ALOGV("setAudioPortConfig()");
5339
5340 if (config == NULL) {
5341 return BAD_VALUE;
5342 }
5343 ALOGV("setAudioPortConfig() on port handle %d", config->id);
5344 // Only support gain configuration for now
Eric Laurenta121f902014-06-03 13:32:54 -07005345 if (config->config_mask != AUDIO_PORT_CONFIG_GAIN) {
5346 return INVALID_OPERATION;
Eric Laurente1715a42014-05-20 11:30:42 -07005347 }
5348
Eric Laurenta121f902014-06-03 13:32:54 -07005349 sp<AudioPortConfig> audioPortConfig;
Eric Laurente1715a42014-05-20 11:30:42 -07005350 if (config->type == AUDIO_PORT_TYPE_MIX) {
5351 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
Eric Laurentc75307b2015-03-17 15:29:32 -07005352 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.getOutputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005353 if (outputDesc == NULL) {
5354 return BAD_VALUE;
5355 }
Eric Laurent84c70242014-06-23 08:46:27 -07005356 ALOG_ASSERT(!outputDesc->isDuplicated(),
5357 "setAudioPortConfig() called on duplicated output %d",
5358 outputDesc->mIoHandle);
Eric Laurenta121f902014-06-03 13:32:54 -07005359 audioPortConfig = outputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005360 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
François Gaffie53615e22015-03-19 09:24:12 +01005361 sp<AudioInputDescriptor> inputDesc = mInputs.getInputFromId(config->id);
Eric Laurente1715a42014-05-20 11:30:42 -07005362 if (inputDesc == NULL) {
5363 return BAD_VALUE;
5364 }
Eric Laurenta121f902014-06-03 13:32:54 -07005365 audioPortConfig = inputDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005366 } else {
5367 return BAD_VALUE;
5368 }
5369 } else if (config->type == AUDIO_PORT_TYPE_DEVICE) {
5370 sp<DeviceDescriptor> deviceDesc;
5371 if (config->role == AUDIO_PORT_ROLE_SOURCE) {
5372 deviceDesc = mAvailableInputDevices.getDeviceFromId(config->id);
5373 } else if (config->role == AUDIO_PORT_ROLE_SINK) {
5374 deviceDesc = mAvailableOutputDevices.getDeviceFromId(config->id);
5375 } else {
5376 return BAD_VALUE;
5377 }
5378 if (deviceDesc == NULL) {
5379 return BAD_VALUE;
5380 }
Eric Laurenta121f902014-06-03 13:32:54 -07005381 audioPortConfig = deviceDesc;
Eric Laurente1715a42014-05-20 11:30:42 -07005382 } else {
5383 return BAD_VALUE;
5384 }
5385
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005386 struct audio_port_config backupConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005387 status_t status = audioPortConfig->applyAudioPortConfig(config, &backupConfig);
5388 if (status == NO_ERROR) {
Mikhail Naganov7be71d22018-05-23 16:51:46 -07005389 struct audio_port_config newConfig = {};
Eric Laurenta121f902014-06-03 13:32:54 -07005390 audioPortConfig->toAudioPortConfig(&newConfig, config);
5391 status = mpClientInterface->setAudioPortConfig(&newConfig, 0);
Eric Laurente1715a42014-05-20 11:30:42 -07005392 }
Eric Laurenta121f902014-06-03 13:32:54 -07005393 if (status != NO_ERROR) {
5394 audioPortConfig->applyAudioPortConfig(&backupConfig);
Eric Laurente1715a42014-05-20 11:30:42 -07005395 }
Eric Laurente1715a42014-05-20 11:30:42 -07005396
5397 return status;
Eric Laurent6a94d692014-05-20 11:18:06 -07005398}
5399
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005400void AudioPolicyManager::releaseResourcesForUid(uid_t uid)
5401{
Eric Laurentd60560a2015-04-10 11:31:20 -07005402 clearAudioSources(uid);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005403 clearAudioPatches(uid);
5404 clearSessionRoutes(uid);
5405}
5406
Eric Laurent6a94d692014-05-20 11:18:06 -07005407void AudioPolicyManager::clearAudioPatches(uid_t uid)
5408{
Eric Laurent0add0fd2014-12-04 18:58:14 -08005409 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
Eric Laurent6a94d692014-05-20 11:18:06 -07005410 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
François Gaffieafd4cea2019-11-18 15:50:22 +01005411 if (patchDesc->getUid() == uid) {
Eric Laurent0add0fd2014-12-04 18:58:14 -08005412 releaseAudioPatch(mAudioPatches.keyAt(i), uid);
Eric Laurent6a94d692014-05-20 11:18:06 -07005413 }
5414 }
5415}
5416
François Gaffiec005e562018-11-06 15:04:49 +01005417void AudioPolicyManager::checkStrategyRoute(product_strategy_t ps, audio_io_handle_t ouptutToSkip)
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005418{
François Gaffiec005e562018-11-06 15:04:49 +01005419 // Take the first attributes following the product strategy as it is used to retrieve the routed
5420 // device. All attributes wihin a strategy follows the same "routing strategy"
5421 auto attributes = mEngine->getAllAttributesForProductStrategy(ps).front();
5422 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attributes, nullptr, false);
François Gaffie11d30102018-11-02 16:09:09 +01005423 SortedVector<audio_io_handle_t> outputs = getOutputsForDevices(devices, mOutputs);
jiabin3ff8d7d2022-12-13 06:27:44 +00005424 std::map<audio_io_handle_t, DeviceVector> outputsToReopen;
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005425 for (size_t j = 0; j < mOutputs.size(); j++) {
5426 if (mOutputs.keyAt(j) == ouptutToSkip) {
5427 continue;
5428 }
5429 sp<SwAudioOutputDescriptor> outputDesc = mOutputs.valueAt(j);
François Gaffiec005e562018-11-06 15:04:49 +01005430 if (!outputDesc->isStrategyActive(ps)) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005431 continue;
5432 }
5433 // If the default device for this strategy is on another output mix,
5434 // invalidate all tracks in this strategy to force re connection.
5435 // Otherwise select new device on the output mix.
5436 if (outputs.indexOf(mOutputs.keyAt(j)) < 0) {
jiabinc44b3462022-12-08 12:52:31 -08005437 invalidateStreams(mEngine->getStreamTypesForProductStrategy(ps));
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005438 } else {
jiabin3ff8d7d2022-12-13 06:27:44 +00005439 DeviceVector newDevices = getNewOutputDevices(outputDesc, false /*fromCache*/);
5440 if (outputDesc->mUsePreferredMixerAttributes && outputDesc->devices() != newDevices) {
5441 // If the device is using preferred mixer attributes, the output need to reopen
5442 // with default configuration when the new selected devices are different from
5443 // current routing devices.
5444 outputsToReopen.emplace(mOutputs.keyAt(j), newDevices);
5445 continue;
5446 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05305447 setOutputDevices(__func__, outputDesc, newDevices, false);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005448 }
5449 }
jiabin3ff8d7d2022-12-13 06:27:44 +00005450 reopenOutputsWithDevices(outputsToReopen);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005451}
5452
5453void AudioPolicyManager::clearSessionRoutes(uid_t uid)
5454{
5455 // remove output routes associated with this uid
François Gaffiec005e562018-11-06 15:04:49 +01005456 std::vector<product_strategy_t> affectedStrategies;
Eric Laurent97ac8712018-07-27 18:59:02 -07005457 for (size_t i = 0; i < mOutputs.size(); i++) {
5458 sp<AudioOutputDescriptor> outputDesc = mOutputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005459 for (const auto& client : outputDesc->getClientIterable()) {
5460 if (client->hasPreferredDevice() && client->uid() == uid) {
5461 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
François Gaffiec005e562018-11-06 15:04:49 +01005462 auto clientStrategy = client->strategy();
5463 if (std::find(begin(affectedStrategies), end(affectedStrategies), clientStrategy) !=
5464 end(affectedStrategies)) {
5465 continue;
5466 }
5467 affectedStrategies.push_back(client->strategy());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005468 }
5469 }
5470 }
5471 // reroute outputs if necessary
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005472 for (const auto& strategy : affectedStrategies) {
5473 checkStrategyRoute(strategy, AUDIO_IO_HANDLE_NONE);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005474 }
5475
5476 // remove input routes associated with this uid
5477 SortedVector<audio_source_t> affectedSources;
Eric Laurent97ac8712018-07-27 18:59:02 -07005478 for (size_t i = 0; i < mInputs.size(); i++) {
5479 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Andy Hung39efb7a2018-09-26 15:39:28 -07005480 for (const auto& client : inputDesc->getClientIterable()) {
5481 if (client->hasPreferredDevice() && client->uid() == uid) {
5482 client->setPreferredDeviceId(AUDIO_PORT_HANDLE_NONE);
5483 affectedSources.add(client->source());
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005484 }
5485 }
5486 }
5487 // reroute inputs if necessary
5488 SortedVector<audio_io_handle_t> inputsToClose;
5489 for (size_t i = 0; i < mInputs.size(); i++) {
5490 sp<AudioInputDescriptor> inputDesc = mInputs.valueAt(i);
Eric Laurent4eb58f12018-12-07 16:41:02 -08005491 if (affectedSources.indexOf(inputDesc->source()) >= 0) {
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005492 inputsToClose.add(inputDesc->mIoHandle);
5493 }
5494 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005495 for (const auto& input : inputsToClose) {
5496 closeInput(input);
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005497 }
5498}
5499
Eric Laurentd60560a2015-04-10 11:31:20 -07005500void AudioPolicyManager::clearAudioSources(uid_t uid)
5501{
5502 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005503 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
5504 if (sourceDesc->uid() == uid) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005505 stopAudioSource(mAudioSources.keyAt(i));
5506 }
5507 }
5508}
Eric Laurent8c7e6da2015-04-21 17:37:00 -07005509
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005510status_t AudioPolicyManager::acquireSoundTriggerSession(audio_session_t *session,
5511 audio_io_handle_t *ioHandle,
5512 audio_devices_t *device)
5513{
Glenn Kastenf0c6d7d2016-02-26 10:44:04 -08005514 *session = (audio_session_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_SESSION);
5515 *ioHandle = (audio_io_handle_t)mpClientInterface->newAudioUniqueId(AUDIO_UNIQUE_ID_USE_INPUT);
Francois Gaffie716e1432019-01-14 16:58:59 +01005516 audio_attributes_t attr = { .source = AUDIO_SOURCE_HOTWORD };
Eric Laurentcedd5b52023-03-22 00:03:31 +00005517 sp<DeviceDescriptor> deviceDesc = mEngine->getInputDeviceForAttributes(attr);
5518 if (deviceDesc == nullptr) {
5519 return INVALID_OPERATION;
5520 }
5521 *device = deviceDesc->type();
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005522
François Gaffiedf372692015-03-19 10:43:27 +01005523 return mSoundTriggerSessions.acquireSession(*session, *ioHandle);
Eric Laurentdf3dc7e2014-07-27 18:39:40 -07005524}
5525
Eric Laurentd60560a2015-04-10 11:31:20 -07005526status_t AudioPolicyManager::startAudioSource(const struct audio_port_config *source,
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005527 const audio_attributes_t *attributes,
5528 audio_port_handle_t *portId,
5529 uid_t uid)
Eric Laurent554a2772015-04-10 11:29:24 -07005530{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005531 ALOGV("%s", __FUNCTION__);
5532 *portId = AUDIO_PORT_HANDLE_NONE;
5533
5534 if (source == NULL || attributes == NULL || portId == NULL) {
5535 ALOGW("%s invalid argument: source %p attributes %p handle %p",
5536 __FUNCTION__, source, attributes, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005537 return BAD_VALUE;
5538 }
5539
Eric Laurentd60560a2015-04-10 11:31:20 -07005540 if (source->role != AUDIO_PORT_ROLE_SOURCE ||
5541 source->type != AUDIO_PORT_TYPE_DEVICE) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005542 ALOGW("%s INVALID_OPERATION source->role %d source->type %d",
5543 __FUNCTION__, source->role, source->type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005544 return INVALID_OPERATION;
5545 }
5546
François Gaffie11d30102018-11-02 16:09:09 +01005547 sp<DeviceDescriptor> srcDevice =
Eric Laurentd60560a2015-04-10 11:31:20 -07005548 mAvailableInputDevices.getDevice(source->ext.device.type,
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005549 String8(source->ext.device.address),
5550 AUDIO_FORMAT_DEFAULT);
François Gaffie11d30102018-11-02 16:09:09 +01005551 if (srcDevice == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005552 ALOGW("%s source->ext.device.type %08x not found", __FUNCTION__, source->ext.device.type);
Eric Laurentd60560a2015-04-10 11:31:20 -07005553 return BAD_VALUE;
5554 }
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005555
jiabin4ef93452019-09-10 14:29:54 -07005556 *portId = PolicyAudioPort::getNextUniqueId();
Eric Laurentd60560a2015-04-10 11:31:20 -07005557
François Gaffieaaac0fd2018-11-22 17:56:39 +01005558 sp<SourceClientDescriptor> sourceDesc =
François Gaffieafd4cea2019-11-18 15:50:22 +01005559 new SourceClientDescriptor(*portId, uid, *attributes, *source, srcDevice,
François Gaffieaaac0fd2018-11-22 17:56:39 +01005560 mEngine->getStreamTypeForAttributes(*attributes),
5561 mEngine->getProductStrategyForAttributes(*attributes),
5562 toVolumeSource(*attributes));
Eric Laurentd60560a2015-04-10 11:31:20 -07005563
5564 status_t status = connectAudioSource(sourceDesc);
5565 if (status == NO_ERROR) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005566 mAudioSources.add(*portId, sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07005567 }
5568 return status;
5569}
5570
Francois Gaffie601801d2021-06-22 13:27:39 +02005571sp<SourceClientDescriptor> AudioPolicyManager::startAudioSourceInternal(
5572 const struct audio_port_config *source, const audio_attributes_t *attributes, uid_t uid)
5573{
5574 ALOGV("%s", __FUNCTION__);
5575 audio_port_handle_t portId = AUDIO_PORT_HANDLE_NONE;
5576
5577 status_t status = startAudioSource(source, attributes, &portId, uid);
5578 ALOGE_IF(status != OK, "%s: failed to start audio source (%d)", __func__, status);
5579 return mAudioSources.valueFor(portId);
5580}
5581
5582
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005583status_t AudioPolicyManager::connectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005584{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005585 ALOGV("%s handle %d", __FUNCTION__, sourceDesc->portId());
Eric Laurentd60560a2015-04-10 11:31:20 -07005586
5587 // make sure we only have one patch per source.
5588 disconnectAudioSource(sourceDesc);
5589
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005590 audio_attributes_t attributes = sourceDesc->attributes();
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005591 // May the device (dynamic) have been disconnected/reconnected, id has changed.
5592 sp<DeviceDescriptor> srcDevice = mAvailableInputDevices.getDevice(
5593 sourceDesc->srcDevice()->type(),
5594 String8(sourceDesc->srcDevice()->address().c_str()),
5595 AUDIO_FORMAT_DEFAULT);
François Gaffiec005e562018-11-06 15:04:49 +01005596 DeviceVector sinkDevices =
Francois Gaffieff1eb522020-05-06 18:37:04 +02005597 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false /*fromCache*/);
François Gaffiec005e562018-11-06 15:04:49 +01005598 ALOG_ASSERT(!sinkDevices.isEmpty(), "connectAudioSource(): no device found for attributes");
François Gaffie11d30102018-11-02 16:09:09 +01005599 sp<DeviceDescriptor> sinkDevice = sinkDevices.itemAt(0);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005600 if (!mAvailableOutputDevices.contains(sinkDevice)) {
5601 ALOGE("%s Device %s not available", __func__, sinkDevice->toString().c_str());
5602 return INVALID_OPERATION;
5603 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005604 PatchBuilder patchBuilder;
5605 patchBuilder.addSink(sinkDevice).addSource(srcDevice);
5606 audio_patch_handle_t handle = AUDIO_PATCH_HANDLE_NONE;
François Gaffieafd4cea2019-11-18 15:50:22 +01005607
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005608 return connectAudioSourceToSink(
5609 sourceDesc, sinkDevice, patchBuilder.patch(), handle, mUidCached, 0 /*delayMs*/);
Eric Laurent554a2772015-04-10 11:29:24 -07005610}
5611
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005612status_t AudioPolicyManager::stopAudioSource(audio_port_handle_t portId)
Eric Laurent554a2772015-04-10 11:29:24 -07005613{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005614 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueFor(portId);
5615 ALOGV("%s port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005616 if (sourceDesc == 0) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005617 ALOGW("%s unknown source for port ID %d", __FUNCTION__, portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005618 return BAD_VALUE;
5619 }
5620 status_t status = disconnectAudioSource(sourceDesc);
5621
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005622 mAudioSources.removeItem(portId);
Eric Laurentd60560a2015-04-10 11:31:20 -07005623 return status;
5624}
5625
Andy Hung2ddee192015-12-18 17:34:44 -08005626status_t AudioPolicyManager::setMasterMono(bool mono)
5627{
5628 if (mMasterMono == mono) {
5629 return NO_ERROR;
5630 }
5631 mMasterMono = mono;
5632 // if enabling mono we close all offloaded devices, which will invalidate the
5633 // corresponding AudioTrack. The AudioTrack client/MediaPlayer is responsible
5634 // for recreating the new AudioTrack as non-offloaded PCM.
5635 //
5636 // If disabling mono, we leave all tracks as is: we don't know which clients
5637 // and tracks are able to be recreated as offloaded. The next "song" should
5638 // play back offloaded.
5639 if (mMasterMono) {
5640 Vector<audio_io_handle_t> offloaded;
5641 for (size_t i = 0; i < mOutputs.size(); ++i) {
5642 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
5643 if (desc->mFlags & AUDIO_OUTPUT_FLAG_COMPRESS_OFFLOAD) {
5644 offloaded.push(desc->mIoHandle);
5645 }
5646 }
Mikhail Naganovcf84e592017-12-07 11:25:11 -08005647 for (const auto& handle : offloaded) {
5648 closeOutput(handle);
Andy Hung2ddee192015-12-18 17:34:44 -08005649 }
5650 }
5651 // update master mono for all remaining outputs
5652 for (size_t i = 0; i < mOutputs.size(); ++i) {
5653 updateMono(mOutputs.keyAt(i));
5654 }
5655 return NO_ERROR;
5656}
5657
5658status_t AudioPolicyManager::getMasterMono(bool *mono)
5659{
5660 *mono = mMasterMono;
5661 return NO_ERROR;
5662}
5663
Eric Laurentac9cef52017-06-09 15:46:26 -07005664float AudioPolicyManager::getStreamVolumeDB(
5665 audio_stream_type_t stream, int index, audio_devices_t device)
5666{
jiabin9a3361e2019-10-01 09:38:30 -07005667 return computeVolume(getVolumeCurves(stream), toVolumeSource(stream), index, {device});
Eric Laurentac9cef52017-06-09 15:46:26 -07005668}
5669
jiabin81772902018-04-02 17:52:27 -07005670status_t AudioPolicyManager::getSurroundFormats(unsigned int *numSurroundFormats,
5671 audio_format_t *surroundFormats,
Kriti Dang6537def2021-03-02 13:46:59 +01005672 bool *surroundFormatsEnabled)
jiabin81772902018-04-02 17:52:27 -07005673{
Kriti Dang6537def2021-03-02 13:46:59 +01005674 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 &&
5675 (surroundFormats == nullptr || surroundFormatsEnabled == nullptr))) {
jiabin81772902018-04-02 17:52:27 -07005676 return BAD_VALUE;
5677 }
Kriti Dang6537def2021-03-02 13:46:59 +01005678 ALOGV("%s() numSurroundFormats %d surroundFormats %p surroundFormatsEnabled %p",
5679 __func__, *numSurroundFormats, surroundFormats, surroundFormatsEnabled);
jiabin81772902018-04-02 17:52:27 -07005680
5681 size_t formatsWritten = 0;
5682 size_t formatsMax = *numSurroundFormats;
Kriti Dangef6be8f2020-11-05 11:58:19 +01005683
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005684 *numSurroundFormats = mConfig->getSurroundFormats().size();
Mikhail Naganov100f0122018-11-29 11:22:16 -08005685 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
5686 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005687 for (const auto& format: mConfig->getSurroundFormats()) {
jiabin81772902018-04-02 17:52:27 -07005688 if (formatsWritten < formatsMax) {
Kriti Dang6537def2021-03-02 13:46:59 +01005689 surroundFormats[formatsWritten] = format.first;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005690 bool formatEnabled = true;
5691 switch (forceUse) {
5692 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL:
Kriti Dang6537def2021-03-02 13:46:59 +01005693 formatEnabled = mManualSurroundFormats.count(format.first) != 0;
Mikhail Naganov100f0122018-11-29 11:22:16 -08005694 break;
5695 case AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER:
5696 formatEnabled = false;
5697 break;
5698 default: // AUTO or ALWAYS => true
5699 break;
jiabin81772902018-04-02 17:52:27 -07005700 }
5701 surroundFormatsEnabled[formatsWritten++] = formatEnabled;
5702 }
jiabin81772902018-04-02 17:52:27 -07005703 }
5704 return NO_ERROR;
5705}
5706
Kriti Dang6537def2021-03-02 13:46:59 +01005707status_t AudioPolicyManager::getReportedSurroundFormats(unsigned int *numSurroundFormats,
5708 audio_format_t *surroundFormats) {
5709 if (numSurroundFormats == nullptr || (*numSurroundFormats != 0 && surroundFormats == nullptr)) {
5710 return BAD_VALUE;
5711 }
5712 ALOGV("%s() numSurroundFormats %d surroundFormats %p",
5713 __func__, *numSurroundFormats, surroundFormats);
5714
5715 size_t formatsWritten = 0;
5716 size_t formatsMax = *numSurroundFormats;
5717 std::unordered_set<audio_format_t> formats; // Uses primary surround formats only
5718
5719 // Return formats from all device profiles that have already been resolved by
5720 // checkOutputsForDevice().
5721 for (size_t i = 0; i < mAvailableOutputDevices.size(); i++) {
5722 sp<DeviceDescriptor> device = mAvailableOutputDevices[i];
5723 audio_devices_t deviceType = device->type();
5724 // Enabling/disabling formats are applied to only HDMI devices. So, this function
5725 // returns formats reported by HDMI devices.
5726 if (deviceType != AUDIO_DEVICE_OUT_HDMI) {
5727 continue;
5728 }
5729 // Formats reported by sink devices
5730 std::unordered_set<audio_format_t> formatset;
5731 if (auto it = mReportedFormatsMap.find(device); it != mReportedFormatsMap.end()) {
5732 formatset.insert(it->second.begin(), it->second.end());
5733 }
5734
5735 // Formats hard-coded in the in policy configuration file (if any).
5736 FormatVector encodedFormats = device->encodedFormats();
5737 formatset.insert(encodedFormats.begin(), encodedFormats.end());
5738 // Filter the formats which are supported by the vendor hardware.
5739 for (auto it = formatset.begin(); it != formatset.end(); ++it) {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005740 if (mConfig->getSurroundFormats().count(*it) != 0) {
Kriti Dang6537def2021-03-02 13:46:59 +01005741 formats.insert(*it);
5742 } else {
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005743 for (const auto& pair : mConfig->getSurroundFormats()) {
Kriti Dang6537def2021-03-02 13:46:59 +01005744 if (pair.second.count(*it) != 0) {
5745 formats.insert(pair.first);
5746 break;
5747 }
5748 }
5749 }
5750 }
5751 }
5752 *numSurroundFormats = formats.size();
5753 for (const auto& format: formats) {
5754 if (formatsWritten < formatsMax) {
5755 surroundFormats[formatsWritten++] = format;
5756 }
5757 }
5758 return NO_ERROR;
5759}
5760
jiabin81772902018-04-02 17:52:27 -07005761status_t AudioPolicyManager::setSurroundFormatEnabled(audio_format_t audioFormat, bool enabled)
5762{
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005763 ALOGV("%s() format 0x%X enabled %d", __func__, audioFormat, enabled);
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005764 const auto& formatIter = mConfig->getSurroundFormats().find(audioFormat);
5765 if (formatIter == mConfig->getSurroundFormats().end()) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005766 ALOGW("%s() format 0x%X is not a known surround format", __func__, audioFormat);
jiabin81772902018-04-02 17:52:27 -07005767 return BAD_VALUE;
5768 }
5769
Mikhail Naganov100f0122018-11-29 11:22:16 -08005770 if (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND) !=
5771 AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005772 ALOGW("%s() not in manual mode for surround sound format selection", __func__);
jiabin81772902018-04-02 17:52:27 -07005773 return INVALID_OPERATION;
5774 }
5775
Mikhail Naganov100f0122018-11-29 11:22:16 -08005776 if ((mManualSurroundFormats.count(audioFormat) != 0) == enabled) {
jiabin81772902018-04-02 17:52:27 -07005777 return NO_ERROR;
5778 }
5779
Mikhail Naganov100f0122018-11-29 11:22:16 -08005780 std::unordered_set<audio_format_t> surroundFormatsBackup(mManualSurroundFormats);
jiabin81772902018-04-02 17:52:27 -07005781 if (enabled) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005782 mManualSurroundFormats.insert(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005783 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005784 mManualSurroundFormats.insert(subFormat);
jiabin81772902018-04-02 17:52:27 -07005785 }
5786 } else {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005787 mManualSurroundFormats.erase(audioFormat);
Mikhail Naganov778bc1f2018-09-14 16:28:52 -07005788 for (const auto& subFormat : formatIter->second) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08005789 mManualSurroundFormats.erase(subFormat);
jiabin81772902018-04-02 17:52:27 -07005790 }
5791 }
5792
5793 sp<SwAudioOutputDescriptor> outputDesc;
5794 bool profileUpdated = false;
jiabin9a3361e2019-10-01 09:38:30 -07005795 DeviceVector hdmiOutputDevices = mAvailableOutputDevices.getDevicesFromType(
5796 AUDIO_DEVICE_OUT_HDMI);
jiabin81772902018-04-02 17:52:27 -07005797 for (size_t i = 0; i < hdmiOutputDevices.size(); i++) {
5798 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005799 String8 address = String8(hdmiOutputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005800 std::string name = hdmiOutputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005801 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5802 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5803 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005804 name.c_str(),
5805 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005806 if (status != NO_ERROR) {
5807 continue;
5808 }
5809 status = setDeviceConnectionStateInt(AUDIO_DEVICE_OUT_HDMI,
5810 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5811 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005812 name.c_str(),
5813 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005814 profileUpdated |= (status == NO_ERROR);
5815 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08005816 // FIXME: Why doing this for input HDMI devices if we don't augment their reported formats?
jiabin9a3361e2019-10-01 09:38:30 -07005817 DeviceVector hdmiInputDevices = mAvailableInputDevices.getDevicesFromType(
jiabin81772902018-04-02 17:52:27 -07005818 AUDIO_DEVICE_IN_HDMI);
5819 for (size_t i = 0; i < hdmiInputDevices.size(); i++) {
5820 // Simulate reconnection to update enabled surround sound formats.
jiabince9f20e2019-09-12 16:29:15 -07005821 String8 address = String8(hdmiInputDevices[i]->address().c_str());
jiabin5740f082019-08-19 15:08:30 -07005822 std::string name = hdmiInputDevices[i]->getName();
jiabin81772902018-04-02 17:52:27 -07005823 status_t status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5824 AUDIO_POLICY_DEVICE_STATE_UNAVAILABLE,
5825 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005826 name.c_str(),
5827 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005828 if (status != NO_ERROR) {
5829 continue;
5830 }
5831 status = setDeviceConnectionStateInt(AUDIO_DEVICE_IN_HDMI,
5832 AUDIO_POLICY_DEVICE_STATE_AVAILABLE,
5833 address.c_str(),
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08005834 name.c_str(),
5835 AUDIO_FORMAT_DEFAULT);
jiabin81772902018-04-02 17:52:27 -07005836 profileUpdated |= (status == NO_ERROR);
5837 }
5838
jiabin81772902018-04-02 17:52:27 -07005839 if (!profileUpdated) {
Mikhail Naganov5dddbfd2018-09-11 14:15:05 -07005840 ALOGW("%s() no audio profiles updated, undoing surround formats change", __func__);
Mikhail Naganov100f0122018-11-29 11:22:16 -08005841 mManualSurroundFormats = std::move(surroundFormatsBackup);
jiabin81772902018-04-02 17:52:27 -07005842 }
5843
5844 return profileUpdated ? NO_ERROR : INVALID_OPERATION;
5845}
5846
Eric Laurent5ada82e2019-08-29 17:53:54 -07005847void AudioPolicyManager::setAppState(audio_port_handle_t portId, app_state_t state)
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005848{
Eric Laurent5ada82e2019-08-29 17:53:54 -07005849 ALOGV("%s(portId:%d, state:%d)", __func__, portId, state);
Eric Laurenta9f86652018-11-28 17:23:11 -08005850 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurent5ada82e2019-08-29 17:53:54 -07005851 mInputs.valueAt(i)->setAppState(portId, state);
Svet Ganovf4ddfef2018-01-16 07:37:58 -08005852 }
5853}
5854
jiabin6012f912018-11-02 17:06:30 -07005855bool AudioPolicyManager::isHapticPlaybackSupported()
5856{
5857 for (const auto& hwModule : mHwModules) {
5858 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5859 for (const auto &outProfile : outputProfiles) {
5860 struct audio_port audioPort;
5861 outProfile->toAudioPort(&audioPort);
5862 for (size_t i = 0; i < audioPort.num_channel_masks; i++) {
5863 if (audioPort.channel_masks[i] & AUDIO_CHANNEL_HAPTIC_ALL) {
5864 return true;
5865 }
5866 }
5867 }
5868 }
5869 return false;
5870}
5871
Carter Hsu325a8eb2022-01-19 19:56:51 +08005872bool AudioPolicyManager::isUltrasoundSupported()
5873{
5874 bool hasUltrasoundOutput = false;
5875 bool hasUltrasoundInput = false;
5876 for (const auto& hwModule : mHwModules) {
5877 const OutputProfileCollection &outputProfiles = hwModule->getOutputProfiles();
5878 if (!hasUltrasoundOutput) {
5879 for (const auto &outProfile : outputProfiles) {
5880 if (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) {
5881 hasUltrasoundOutput = true;
5882 break;
5883 }
5884 }
5885 }
5886
5887 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5888 if (!hasUltrasoundInput) {
5889 for (const auto &inputProfile : inputProfiles) {
5890 if (inputProfile->getFlags() & AUDIO_INPUT_FLAG_ULTRASOUND) {
5891 hasUltrasoundInput = true;
5892 break;
5893 }
5894 }
5895 }
5896
5897 if (hasUltrasoundOutput && hasUltrasoundInput)
5898 return true;
5899 }
5900 return false;
5901}
5902
Atneya Nair698f5ef2022-12-15 16:15:09 -08005903bool AudioPolicyManager::isHotwordStreamSupported(bool lookbackAudio)
5904{
5905 const auto mask = AUDIO_INPUT_FLAG_HOTWORD_TAP |
5906 (lookbackAudio ? AUDIO_INPUT_FLAG_HW_LOOKBACK : 0);
5907 for (const auto& hwModule : mHwModules) {
5908 const InputProfileCollection &inputProfiles = hwModule->getInputProfiles();
5909 for (const auto &inputProfile : inputProfiles) {
5910 if ((inputProfile->getFlags() & mask) == mask) {
5911 return true;
5912 }
5913 }
5914 }
5915 return false;
5916}
5917
Eric Laurent8340e672019-11-06 11:01:08 -08005918bool AudioPolicyManager::isCallScreenModeSupported()
5919{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07005920 return mConfig->isCallScreenModeSupported();
Eric Laurent8340e672019-11-06 11:01:08 -08005921}
5922
5923
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005924status_t AudioPolicyManager::disconnectAudioSource(const sp<SourceClientDescriptor>& sourceDesc)
Eric Laurentd60560a2015-04-10 11:31:20 -07005925{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005926 ALOGV("%s port Id %d", __FUNCTION__, sourceDesc->portId());
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005927 if (!sourceDesc->isConnected()) {
5928 ALOGV("%s port Id %d already disconnected", __FUNCTION__, sourceDesc->portId());
5929 return NO_ERROR;
5930 }
François Gaffieafd4cea2019-11-18 15:50:22 +01005931 sp<SwAudioOutputDescriptor> swOutput = sourceDesc->swOutput().promote();
5932 if (swOutput != 0) {
5933 status_t status = stopSource(swOutput, sourceDesc);
Eric Laurent733ce942017-12-07 12:18:25 -08005934 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01005935 swOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08005936 }
jiabinbce0c1d2020-10-05 11:20:18 -07005937 if (releaseOutput(sourceDesc->portId())) {
5938 // The output descriptor is reopened to query dynamic profiles. In that case, there is
5939 // no need to release audio patch here but just return NO_ERROR.
5940 return NO_ERROR;
5941 }
Eric Laurentd60560a2015-04-10 11:31:20 -07005942 } else {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005943 sp<HwAudioOutputDescriptor> hwOutputDesc = sourceDesc->hwOutput().promote();
Eric Laurentd60560a2015-04-10 11:31:20 -07005944 if (hwOutputDesc != 0) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005945 // close Hwoutput and remove from mHwOutputs
5946 } else {
5947 ALOGW("%s source has neither SW nor HW output", __FUNCTION__);
5948 }
5949 }
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02005950 status_t status = releaseAudioPatchInternal(sourceDesc->getPatchHandle(), 0, sourceDesc);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02005951 sourceDesc->disconnect();
5952 return status;
Eric Laurentd60560a2015-04-10 11:31:20 -07005953}
5954
François Gaffiec005e562018-11-06 15:04:49 +01005955sp<SourceClientDescriptor> AudioPolicyManager::getSourceForAttributesOnOutput(
5956 audio_io_handle_t output, const audio_attributes_t &attr)
Eric Laurentd60560a2015-04-10 11:31:20 -07005957{
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005958 sp<SourceClientDescriptor> source;
Eric Laurentd60560a2015-04-10 11:31:20 -07005959 for (size_t i = 0; i < mAudioSources.size(); i++) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005960 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Eric Laurent3e6c7e12018-07-27 17:09:23 -07005961 sp<SwAudioOutputDescriptor> outputDesc = sourceDesc->swOutput().promote();
François Gaffiec005e562018-11-06 15:04:49 +01005962 if (followsSameRouting(attr, sourceDesc->attributes()) &&
5963 outputDesc != 0 && outputDesc->mIoHandle == output) {
Eric Laurentd60560a2015-04-10 11:31:20 -07005964 source = sourceDesc;
5965 break;
5966 }
5967 }
5968 return source;
Eric Laurent554a2772015-04-10 11:29:24 -07005969}
5970
Eric Laurentb4f42a92022-01-17 17:37:31 +01005971bool AudioPolicyManager::canBeSpatializedInt(const audio_attributes_t *attr,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005972 const audio_config_t *config,
Andy Hung9dd1a5b2022-05-10 15:39:39 -07005973 const AudioDeviceTypeAddrVector &devices) const
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005974{
5975 // The caller can have the audio attributes criteria ignored by either passing a null ptr or
5976 // the AUDIO_ATTRIBUTES_INITIALIZER value.
Eric Laurentfa0f6742021-08-17 18:39:44 +02005977 // If attributes are specified, current policy is to only allow spatialization for media
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005978 // and game usages.
Eric Laurent39095982021-08-24 18:29:27 +02005979 if (attr != nullptr && *attr != AUDIO_ATTRIBUTES_INITIALIZER) {
5980 if (attr->usage != AUDIO_USAGE_MEDIA && attr->usage != AUDIO_USAGE_GAME) {
5981 return false;
5982 }
5983 if ((attr->flags & (AUDIO_FLAG_CONTENT_SPATIALIZED | AUDIO_FLAG_NEVER_SPATIALIZE)) != 0) {
5984 return false;
5985 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02005986 }
5987
Eric Laurentd332bc82023-08-04 11:45:23 +02005988 // The caller can have the audio config criteria ignored by either passing a null ptr or
5989 // the AUDIO_CONFIG_INITIALIZER value.
5990 // If an audio config is specified, current policy is to only allow spatialization for
5991 // some positional channel masks and PCM format
5992
5993 if (config != nullptr && *config != AUDIO_CONFIG_INITIALIZER) {
Andy Hung481bfe32023-12-18 14:00:29 -08005994 const bool channel_mask_spatialized =
5995 com_android_media_audio_stereo_spatialization()
5996 ? audio_channel_mask_contains_stereo(config->channel_mask)
5997 : audio_is_channel_mask_spatialized(config->channel_mask);
5998 if (!channel_mask_spatialized) {
Eric Laurentd332bc82023-08-04 11:45:23 +02005999 return false;
6000 }
6001 if (!audio_is_linear_pcm(config->format)) {
6002 return false;
6003 }
6004 }
6005
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006006 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006007 getSpatializerOutputProfile(config, devices);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006008 if (profile == nullptr) {
6009 return false;
6010 }
6011
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006012 return true;
6013}
6014
6015void AudioPolicyManager::checkVirtualizerClientRoutes() {
6016 std::set<audio_stream_type_t> streamsToInvalidate;
6017 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurent39095982021-08-24 18:29:27 +02006018 const sp<SwAudioOutputDescriptor>& desc = mOutputs[i];
6019 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006020 audio_attributes_t attr = client->attributes();
6021 DeviceVector devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, false);
6022 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6023 audio_config_base_t clientConfig = client->config();
6024 audio_config_t config = audio_config_initializer(&clientConfig);
Eric Laurent39095982021-08-24 18:29:27 +02006025 if (desc != mSpatializerOutput
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006026 && canBeSpatializedInt(&attr, &config, devicesTypeAddress)) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006027 streamsToInvalidate.insert(client->stream());
6028 }
6029 }
6030 }
6031
jiabinc44b3462022-12-08 12:52:31 -08006032 invalidateStreams(StreamTypeVector(streamsToInvalidate.begin(), streamsToInvalidate.end()));
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006033}
6034
Eric Laurente191d1b2022-04-15 11:59:25 +02006035
6036bool AudioPolicyManager::isOutputOnlyAvailableRouteToSomeDevice(
6037 const sp<SwAudioOutputDescriptor>& outputDesc) {
6038 if (outputDesc->isDuplicated()) {
6039 return false;
6040 }
6041 DeviceVector devices = outputDesc->supportedDevices();
6042 for (size_t i = 0; i < mOutputs.size(); i++) {
6043 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6044 if (desc == outputDesc || desc->isDuplicated()) {
6045 continue;
6046 }
6047 DeviceVector sharedDevices = desc->filterSupportedDevices(devices);
6048 if (!sharedDevices.isEmpty()
6049 && (desc->devicesSupportEncodedFormats(sharedDevices.types())
6050 == outputDesc->devicesSupportEncodedFormats(sharedDevices.types()))) {
6051 return false;
6052 }
6053 }
6054 return true;
6055}
6056
6057
Eric Laurentfa0f6742021-08-17 18:39:44 +02006058status_t AudioPolicyManager::getSpatializerOutput(const audio_config_base_t *mixerConfig,
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006059 const audio_attributes_t *attr,
6060 audio_io_handle_t *output) {
6061 *output = AUDIO_IO_HANDLE_NONE;
6062
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006063 DeviceVector devices = mEngine->getOutputDevicesForAttributes(*attr, nullptr, false);
6064 AudioDeviceTypeAddrVector devicesTypeAddress = devices.toTypeAddrVector();
6065 audio_config_t *configPtr = nullptr;
6066 audio_config_t config;
6067 if (mixerConfig != nullptr) {
6068 config = audio_config_initializer(mixerConfig);
6069 configPtr = &config;
6070 }
Andy Hung9dd1a5b2022-05-10 15:39:39 -07006071 if (!canBeSpatializedInt(attr, configPtr, devicesTypeAddress)) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006072 ALOGV("%s provided attributes or mixer config cannot be spatialized", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006073 return BAD_VALUE;
6074 }
6075
6076 sp<IOProfile> profile =
Eric Laurent39095982021-08-24 18:29:27 +02006077 getSpatializerOutputProfile(configPtr, devicesTypeAddress);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006078 if (profile == nullptr) {
Eric Laurente191d1b2022-04-15 11:59:25 +02006079 ALOGV("%s no suitable output profile for provided attributes or mixer config", __func__);
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006080 return BAD_VALUE;
6081 }
6082
Eric Laurente191d1b2022-04-15 11:59:25 +02006083 std::vector<sp<SwAudioOutputDescriptor>> spatializerOutputs;
Eric Laurent39095982021-08-24 18:29:27 +02006084 for (size_t i = 0; i < mOutputs.size(); i++) {
6085 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
Eric Laurente191d1b2022-04-15 11:59:25 +02006086 if (!desc->isDuplicated()
6087 && (desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0) {
6088 spatializerOutputs.push_back(desc);
6089 ALOGV("%s adding opened spatializer Output %d", __func__, desc->mIoHandle);
Eric Laurent39095982021-08-24 18:29:27 +02006090 }
6091 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006092 mSpatializerOutput.clear();
6093 bool outputsChanged = false;
6094 for (const auto& desc : spatializerOutputs) {
6095 if (desc->mProfile == profile
6096 && (configPtr == nullptr
6097 || configPtr->channel_mask == desc->mMixerChannelMask)) {
6098 mSpatializerOutput = desc;
6099 ALOGV("%s reusing current spatializer output %d", __func__, desc->mIoHandle);
6100 } else {
6101 ALOGV("%s closing spatializerOutput output %d to match channel mask %#x"
6102 " and devices %s", __func__, desc->mIoHandle,
6103 configPtr != nullptr ? configPtr->channel_mask : 0,
6104 devices.toString().c_str());
6105 closeOutput(desc->mIoHandle);
6106 outputsChanged = true;
6107 }
Eric Laurent39095982021-08-24 18:29:27 +02006108 }
6109
Eric Laurente191d1b2022-04-15 11:59:25 +02006110 if (mSpatializerOutput == nullptr) {
Eric Laurentb4f42a92022-01-17 17:37:31 +01006111 sp<SwAudioOutputDescriptor> desc =
6112 openOutputWithProfileAndDevice(profile, devices, mixerConfig);
Eric Laurente191d1b2022-04-15 11:59:25 +02006113 if (desc != nullptr) {
6114 mSpatializerOutput = desc;
6115 outputsChanged = true;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006116 }
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006117 }
6118
6119 checkVirtualizerClientRoutes();
6120
Eric Laurente191d1b2022-04-15 11:59:25 +02006121 if (outputsChanged) {
6122 mPreviousOutputs = mOutputs;
6123 mpClientInterface->onAudioPortListUpdate();
6124 }
6125
6126 if (mSpatializerOutput == nullptr) {
6127 ALOGV("%s could not open spatializer output with requested config", __func__);
6128 return BAD_VALUE;
6129 }
Eric Laurent39095982021-08-24 18:29:27 +02006130 *output = mSpatializerOutput->mIoHandle;
Eric Laurente191d1b2022-04-15 11:59:25 +02006131 ALOGV("%s returning new spatializer output %d", __func__, *output);
6132 return OK;
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006133}
6134
Eric Laurentfa0f6742021-08-17 18:39:44 +02006135status_t AudioPolicyManager::releaseSpatializerOutput(audio_io_handle_t output) {
6136 if (mSpatializerOutput == nullptr) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006137 return INVALID_OPERATION;
6138 }
Eric Laurentfa0f6742021-08-17 18:39:44 +02006139 if (mSpatializerOutput->mIoHandle != output) {
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006140 return BAD_VALUE;
6141 }
Eric Laurent39095982021-08-24 18:29:27 +02006142
Eric Laurente191d1b2022-04-15 11:59:25 +02006143 if (!isOutputOnlyAvailableRouteToSomeDevice(mSpatializerOutput)) {
6144 ALOGV("%s closing spatializer output %d", __func__, mSpatializerOutput->mIoHandle);
6145 closeOutput(mSpatializerOutput->mIoHandle);
6146 //from now on mSpatializerOutput is null
6147 checkVirtualizerClientRoutes();
6148 }
Eric Laurent39095982021-08-24 18:29:27 +02006149
Eric Laurentcad6c0d2021-07-13 15:12:39 +02006150 return NO_ERROR;
6151}
6152
Eric Laurente552edb2014-03-10 17:42:56 -07006153// ----------------------------------------------------------------------------
Eric Laurente0720872014-03-11 09:30:41 -07006154// AudioPolicyManager
Eric Laurente552edb2014-03-10 17:42:56 -07006155// ----------------------------------------------------------------------------
Eric Laurent6a94d692014-05-20 11:18:06 -07006156uint32_t AudioPolicyManager::nextAudioPortGeneration()
6157{
Mikhail Naganov2773dd72017-12-08 10:12:11 -08006158 return mAudioPortGeneration++;
Eric Laurent6a94d692014-05-20 11:18:06 -07006159}
6160
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006161AudioPolicyManager::AudioPolicyManager(const sp<const AudioPolicyConfig>& config,
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006162 EngineInstance&& engine,
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006163 AudioPolicyClientInterface *clientInterface)
Eric Laurente552edb2014-03-10 17:42:56 -07006164 :
Andy Hung4ef19fa2018-05-15 19:35:29 -07006165 mUidCached(AID_AUDIOSERVER), // no need to call getuid(), there's only one of us running.
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006166 mConfig(config),
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006167 mEngine(std::move(engine)),
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006168 mpClientInterface(clientInterface),
Eric Laurente552edb2014-03-10 17:42:56 -07006169 mLimitRingtoneVolume(false), mLastVoiceVolume(-1.0f),
Eric Laurent3a4311c2014-03-17 12:00:47 -07006170 mA2dpSuspended(false),
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07006171 mAudioPortGeneration(1),
6172 mBeaconMuteRefCount(0),
6173 mBeaconPlayingRefCount(0),
Eric Laurent9459fb02015-08-12 18:36:32 -07006174 mBeaconMuted(false),
Andy Hung2ddee192015-12-18 17:34:44 -08006175 mTtsOutputAvailable(false),
Eric Laurent36829f92017-04-07 19:04:42 -07006176 mMasterMono(false),
Eric Laurent4eb58f12018-12-07 16:41:02 -08006177 mMusicEffectOutput(AUDIO_IO_HANDLE_NONE)
Eric Laurente552edb2014-03-10 17:42:56 -07006178{
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006179}
François Gaffied1ab2bd2015-12-02 18:20:06 +01006180
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006181status_t AudioPolicyManager::initialize() {
Mikhail Naganovf1b6d972023-05-02 13:56:01 -07006182 if (mEngine == nullptr) {
6183 return NO_INIT;
François Gaffie2110e042015-03-24 08:41:51 +01006184 }
6185 mEngine->setObserver(this);
6186 status_t status = mEngine->initCheck();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006187 if (status != NO_ERROR) {
6188 LOG_FATAL("Policy engine not initialized(err=%d)", status);
6189 return status;
6190 }
François Gaffie2110e042015-03-24 08:41:51 +01006191
jiabin29230182023-04-04 21:02:36 +00006192 // The actual device selection cache will be updated when calling `updateDevicesAndOutputs`
6193 // at the end of this function.
6194 mEngine->initializeDeviceSelectionCache();
Eric Laurent1d69c872021-01-11 18:53:01 +01006195 mCommunnicationStrategy = mEngine->getProductStrategyForAttributes(
6196 mEngine->getAttributesForStreamType(AUDIO_STREAM_VOICE_CALL));
6197
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006198 // after parsing the config, mConfig contain all known devices;
Eric Laurente552edb2014-03-10 17:42:56 -07006199 // open all output streams needed to access attached devices
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006200 onNewAudioModulesAvailableInt(nullptr /*newDevices*/);
François Gaffie11d30102018-11-02 16:09:09 +01006201
Eric Laurent3a4311c2014-03-17 12:00:47 -07006202 // make sure default device is reachable
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006203 if (const auto defaultOutputDevice = mConfig->getDefaultOutputDevice();
6204 defaultOutputDevice == nullptr ||
6205 !mAvailableOutputDevices.contains(defaultOutputDevice)) {
6206 ALOGE_IF(defaultOutputDevice != nullptr, "Default device %s is unreachable",
6207 defaultOutputDevice->toString().c_str());
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006208 status = NO_INIT;
Eric Laurent3a4311c2014-03-17 12:00:47 -07006209 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006210 ALOGW_IF(mPrimaryOutput == nullptr, "The policy configuration does not declare a primary output");
Eric Laurente552edb2014-03-10 17:42:56 -07006211
Tomoharu Kasahara71c90912018-10-31 09:10:12 +09006212 // Silence ALOGV statements
6213 property_set("log.tag." LOG_TAG, "D");
6214
Eric Laurente552edb2014-03-10 17:42:56 -07006215 updateDevicesAndOutputs();
Mikhail Naganovad3f8a12017-12-12 13:24:23 -08006216 return status;
Eric Laurente552edb2014-03-10 17:42:56 -07006217}
6218
Eric Laurente0720872014-03-11 09:30:41 -07006219AudioPolicyManager::~AudioPolicyManager()
Eric Laurente552edb2014-03-10 17:42:56 -07006220{
Eric Laurente552edb2014-03-10 17:42:56 -07006221 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006222 mOutputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006223 }
6224 for (size_t i = 0; i < mInputs.size(); i++) {
Eric Laurentfe231122017-11-17 17:48:06 -08006225 mInputs.valueAt(i)->close();
Eric Laurente552edb2014-03-10 17:42:56 -07006226 }
Eric Laurent3a4311c2014-03-17 12:00:47 -07006227 mAvailableOutputDevices.clear();
6228 mAvailableInputDevices.clear();
Eric Laurent1f2f2232014-06-02 12:01:23 -07006229 mOutputs.clear();
6230 mInputs.clear();
6231 mHwModules.clear();
Mikhail Naganov100f0122018-11-29 11:22:16 -08006232 mManualSurroundFormats.clear();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006233 mConfig.clear();
Eric Laurente552edb2014-03-10 17:42:56 -07006234}
6235
Eric Laurente0720872014-03-11 09:30:41 -07006236status_t AudioPolicyManager::initCheck()
Eric Laurente552edb2014-03-10 17:42:56 -07006237{
Eric Laurent87ffa392015-05-22 10:32:38 -07006238 return hasPrimaryOutput() ? NO_ERROR : NO_INIT;
Eric Laurente552edb2014-03-10 17:42:56 -07006239}
6240
Eric Laurente552edb2014-03-10 17:42:56 -07006241// ---
6242
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006243void AudioPolicyManager::onNewAudioModulesAvailable()
6244{
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006245 DeviceVector newDevices;
6246 onNewAudioModulesAvailableInt(&newDevices);
6247 if (!newDevices.empty()) {
6248 nextAudioPortGeneration();
6249 mpClientInterface->onAudioPortListUpdate();
6250 }
6251}
6252
6253void AudioPolicyManager::onNewAudioModulesAvailableInt(DeviceVector *newDevices)
6254{
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006255 for (const auto& hwModule : mConfig->getHwModules()) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006256 if (std::find(mHwModules.begin(), mHwModules.end(), hwModule) != mHwModules.end()) {
6257 continue;
6258 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006259 if (hwModule->getHandle() == AUDIO_MODULE_HANDLE_NONE) {
Mikhail Naganovffd97712023-05-03 17:45:36 -07006260 if (audio_module_handle_t handle = mpClientInterface->loadHwModule(hwModule->getName());
6261 handle != AUDIO_MODULE_HANDLE_NONE) {
6262 hwModule->setHandle(handle);
6263 } else {
6264 ALOGW("could not load HW module %s", hwModule->getName());
6265 continue;
6266 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006267 }
6268 mHwModules.push_back(hwModule);
Dean Wheatley12a87132021-04-16 10:08:49 +10006269 // open all output streams needed to access attached devices.
6270 // direct outputs are closed immediately after checking the availability of attached devices
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006271 // This also validates mAvailableOutputDevices list
6272 for (const auto& outProfile : hwModule->getOutputProfiles()) {
6273 if (!outProfile->canOpenNewIo()) {
6274 ALOGE("Invalid Output profile max open count %u for profile %s",
6275 outProfile->maxOpenCount, outProfile->getTagName().c_str());
6276 continue;
6277 }
6278 if (!outProfile->hasSupportedDevices()) {
6279 ALOGW("Output profile contains no device on module %s", hwModule->getName());
6280 continue;
6281 }
Carter Hsu1a3364a2022-01-21 15:32:56 +08006282 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_TTS) != 0 ||
6283 (outProfile->getFlags() & AUDIO_OUTPUT_FLAG_ULTRASOUND) != 0) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006284 mTtsOutputAvailable = true;
6285 }
6286
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006287 const DeviceVector &supportedDevices = outProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006288 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getOutputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006289 sp<DeviceDescriptor> supportedDevice = 0;
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006290 if (supportedDevices.contains(mConfig->getDefaultOutputDevice())) {
6291 supportedDevice = mConfig->getDefaultOutputDevice();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006292 } else {
6293 // choose first device present in profile's SupportedDevices also part of
6294 // mAvailableOutputDevices.
6295 if (availProfileDevices.isEmpty()) {
6296 continue;
6297 }
6298 supportedDevice = availProfileDevices.itemAt(0);
6299 }
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006300 if (!mConfig->getOutputDevices().contains(supportedDevice)) {
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006301 continue;
6302 }
6303 sp<SwAudioOutputDescriptor> outputDesc = new SwAudioOutputDescriptor(outProfile,
6304 mpClientInterface);
6305 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
Eric Laurentf1f22e72021-07-13 14:04:14 +02006306 status_t status = outputDesc->open(nullptr /* halConfig */, nullptr /* mixerConfig */,
6307 DeviceVector(supportedDevice),
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006308 AUDIO_STREAM_DEFAULT,
6309 AUDIO_OUTPUT_FLAG_NONE, &output);
6310 if (status != NO_ERROR) {
6311 ALOGW("Cannot open output stream for devices %s on hw module %s",
6312 supportedDevice->toString().c_str(), hwModule->getName());
6313 continue;
6314 }
6315 for (const auto &device : availProfileDevices) {
6316 // give a valid ID to an attached device once confirmed it is reachable
6317 if (!device->isAttached()) {
6318 device->attach(hwModule);
6319 mAvailableOutputDevices.add(device);
jiabin1c4794b2020-05-05 10:08:05 -07006320 device->setEncapsulationInfoFromHal(mpClientInterface);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006321 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006322 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6323 }
6324 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006325 if (mPrimaryOutput == nullptr &&
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006326 outProfile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
6327 mPrimaryOutput = outputDesc;
François Gaffiedb1755b2023-09-01 11:50:35 +02006328 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006329 }
Eric Laurent39095982021-08-24 18:29:27 +02006330 if ((outProfile->getFlags() & AUDIO_OUTPUT_FLAG_DIRECT) != 0) {
Eric Laurentc529cf62020-04-17 18:19:10 -07006331 outputDesc->close();
6332 } else {
6333 addOutput(output, outputDesc);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306334 setOutputDevices(__func__, outputDesc,
Eric Laurentc529cf62020-04-17 18:19:10 -07006335 DeviceVector(supportedDevice),
6336 true,
6337 0,
6338 NULL);
6339 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006340 }
6341 // open input streams needed to access attached devices to validate
6342 // mAvailableInputDevices list
6343 for (const auto& inProfile : hwModule->getInputProfiles()) {
6344 if (!inProfile->canOpenNewIo()) {
6345 ALOGE("Invalid Input profile max open count %u for profile %s",
6346 inProfile->maxOpenCount, inProfile->getTagName().c_str());
6347 continue;
6348 }
6349 if (!inProfile->hasSupportedDevices()) {
6350 ALOGW("Input profile contains no device on module %s", hwModule->getName());
6351 continue;
6352 }
6353 // chose first device present in profile's SupportedDevices also part of
6354 // available input devices
6355 const DeviceVector &supportedDevices = inProfile->getSupportedDevices();
Mikhail Naganov68e3f642023-04-28 13:06:32 -07006356 DeviceVector availProfileDevices = supportedDevices.filter(mConfig->getInputDevices());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006357 if (availProfileDevices.isEmpty()) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01006358 ALOGV("%s: Input device list is empty! for profile %s",
6359 __func__, inProfile->getTagName().c_str());
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006360 continue;
6361 }
6362 sp<AudioInputDescriptor> inputDesc =
6363 new AudioInputDescriptor(inProfile, mpClientInterface);
6364
6365 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
6366 status_t status = inputDesc->open(nullptr,
6367 availProfileDevices.itemAt(0),
6368 AUDIO_SOURCE_MIC,
6369 AUDIO_INPUT_FLAG_NONE,
6370 &input);
6371 if (status != NO_ERROR) {
6372 ALOGW("Cannot open input stream for device %s on hw module %s",
6373 availProfileDevices.toString().c_str(),
6374 hwModule->getName());
6375 continue;
6376 }
6377 for (const auto &device : availProfileDevices) {
6378 // give a valid ID to an attached device once confirmed it is reachable
6379 if (!device->isAttached()) {
6380 device->attach(hwModule);
6381 device->importAudioPortAndPickAudioProfile(inProfile, true);
6382 mAvailableInputDevices.add(device);
Mikhail Naganovd0e2c742020-03-25 15:59:59 -07006383 if (newDevices) newDevices->add(device);
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006384 setEngineDeviceConnectionState(device, AUDIO_POLICY_DEVICE_STATE_AVAILABLE);
6385 }
6386 }
6387 inputDesc->close();
6388 }
6389 }
Eric Laurente191d1b2022-04-15 11:59:25 +02006390
6391 // Check if spatializer outputs can be closed until used.
6392 // mOutputs vector never contains duplicated outputs at this point.
6393 std::vector<audio_io_handle_t> outputsClosed;
6394 for (size_t i = 0; i < mOutputs.size(); i++) {
6395 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
6396 if ((desc->mFlags & AUDIO_OUTPUT_FLAG_SPATIALIZER) != 0
6397 && !isOutputOnlyAvailableRouteToSomeDevice(desc)) {
6398 outputsClosed.push_back(desc->mIoHandle);
6399 desc->close();
6400 }
6401 }
6402 for (auto output : outputsClosed) {
6403 removeOutput(output);
6404 }
Mikhail Naganovc0d04982020-03-02 21:02:28 +00006405}
6406
Eric Laurent98e38192018-02-15 18:31:53 -08006407void AudioPolicyManager::addOutput(audio_io_handle_t output,
6408 const sp<SwAudioOutputDescriptor>& outputDesc)
Eric Laurente552edb2014-03-10 17:42:56 -07006409{
Eric Laurent1c333e22014-05-20 10:48:17 -07006410 mOutputs.add(output, outputDesc);
jiabin9a3361e2019-10-01 09:38:30 -07006411 applyStreamVolumes(outputDesc, DeviceTypeSet(), 0 /* delayMs */, true /* force */);
Andy Hung2ddee192015-12-18 17:34:44 -08006412 updateMono(output); // update mono status when adding to output list
Eric Laurent36829f92017-04-07 19:04:42 -07006413 selectOutputForMusicEffects();
Eric Laurent6a94d692014-05-20 11:18:06 -07006414 nextAudioPortGeneration();
Eric Laurente552edb2014-03-10 17:42:56 -07006415}
6416
François Gaffie53615e22015-03-19 09:24:12 +01006417void AudioPolicyManager::removeOutput(audio_io_handle_t output)
6418{
Francois Gaffiebce7cd42020-10-14 16:13:20 +02006419 if (mPrimaryOutput != 0 && mPrimaryOutput == mOutputs.valueFor(output)) {
6420 ALOGV("%s: removing primary output", __func__);
6421 mPrimaryOutput = nullptr;
6422 }
François Gaffie53615e22015-03-19 09:24:12 +01006423 mOutputs.removeItem(output);
Eric Laurent36829f92017-04-07 19:04:42 -07006424 selectOutputForMusicEffects();
François Gaffie53615e22015-03-19 09:24:12 +01006425}
6426
Eric Laurent98e38192018-02-15 18:31:53 -08006427void AudioPolicyManager::addInput(audio_io_handle_t input,
6428 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurentd4692962014-05-05 18:13:44 -07006429{
Eric Laurent1c333e22014-05-20 10:48:17 -07006430 mInputs.add(input, inputDesc);
Eric Laurent6a94d692014-05-20 11:18:06 -07006431 nextAudioPortGeneration();
Eric Laurentd4692962014-05-05 18:13:44 -07006432}
Eric Laurente552edb2014-03-10 17:42:56 -07006433
François Gaffie11d30102018-11-02 16:09:09 +01006434status_t AudioPolicyManager::checkOutputsForDevice(const sp<DeviceDescriptor>& device,
François Gaffie53615e22015-03-19 09:24:12 +01006435 audio_policy_dev_state_t state,
François Gaffie11d30102018-11-02 16:09:09 +01006436 SortedVector<audio_io_handle_t>& outputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006437{
François Gaffie11d30102018-11-02 16:09:09 +01006438 audio_devices_t deviceType = device->type();
jiabince9f20e2019-09-12 16:29:15 -07006439 const String8 &address = String8(device->address().c_str());
Eric Laurentc75307b2015-03-17 15:29:32 -07006440 sp<SwAudioOutputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006441
François Gaffie11d30102018-11-02 16:09:09 +01006442 if (audio_device_is_digital(deviceType)) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006443 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006444 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006445 }
Eric Laurente552edb2014-03-10 17:42:56 -07006446
Eric Laurent3b73df72014-03-11 09:06:29 -07006447 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinb4fed192020-09-22 14:45:40 -07006448 // first call getAudioPort to get the supported attributes from the HAL
6449 struct audio_port_v7 port = {};
6450 device->toAudioPort(&port);
6451 status_t status = mpClientInterface->getAudioPort(&port);
6452 if (status == NO_ERROR) {
6453 device->importAudioPort(port);
6454 }
6455
6456 // then list already open outputs that can be routed to this device
Eric Laurente552edb2014-03-10 17:42:56 -07006457 for (size_t i = 0; i < mOutputs.size(); i++) {
6458 desc = mOutputs.valueAt(i);
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006459 if (!desc->isDuplicated() && desc->supportsDevice(device)
jiabin9a3361e2019-10-01 09:38:30 -07006460 && desc->devicesSupportEncodedFormats({deviceType})) {
François Gaffie11d30102018-11-02 16:09:09 +01006461 ALOGV("checkOutputsForDevice(): adding opened output %d on device %s",
6462 mOutputs.keyAt(i), device->toString().c_str());
6463 outputs.add(mOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006464 }
6465 }
6466 // then look for output profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006467 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006468 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006469 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6470 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
François Gaffie11d30102018-11-02 16:09:09 +01006471 if (profile->supportsDevice(device)) {
6472 profiles.add(profile);
6473 ALOGV("checkOutputsForDevice(): adding profile %zu from module %s",
6474 j, hwModule->getName());
Eric Laurente552edb2014-03-10 17:42:56 -07006475 }
6476 }
6477 }
6478
Eric Laurent7b279bb2015-12-14 10:18:23 -08006479 ALOGV(" found %zu profiles, %zu outputs", profiles.size(), outputs.size());
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006480
Eric Laurente552edb2014-03-10 17:42:56 -07006481 if (profiles.isEmpty() && outputs.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006482 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006483 return BAD_VALUE;
6484 }
6485
6486 // open outputs for matching profiles if needed. Direct outputs are also opened to
6487 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6488 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
Eric Laurent1c333e22014-05-20 10:48:17 -07006489 sp<IOProfile> profile = profiles[profile_index];
Eric Laurente552edb2014-03-10 17:42:56 -07006490
6491 // nothing to do if one output is already opened for this profile
6492 size_t j;
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006493 for (j = 0; j < outputs.size(); j++) {
6494 desc = mOutputs.valueFor(outputs.itemAt(j));
Eric Laurente552edb2014-03-10 17:42:56 -07006495 if (!desc->isDuplicated() && desc->mProfile == profile) {
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006496 // matching profile: save the sample rates, format and channel masks supported
6497 // by the profile in our device descriptor
François Gaffie11d30102018-11-02 16:09:09 +01006498 if (audio_device_is_digital(deviceType)) {
jiabin4ef93452019-09-10 14:29:54 -07006499 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006500 }
Eric Laurente552edb2014-03-10 17:42:56 -07006501 break;
6502 }
6503 }
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006504 if (j != outputs.size()) {
Eric Laurente552edb2014-03-10 17:42:56 -07006505 continue;
6506 }
6507
Eric Laurent3974e3b2017-12-07 17:58:43 -08006508 if (!profile->canOpenNewIo()) {
6509 ALOGW("Max Output number %u already opened for this profile %s",
6510 profile->maxOpenCount, profile->getTagName().c_str());
6511 continue;
6512 }
6513
Eric Laurent83efe1c2017-07-09 16:51:08 -07006514 ALOGV("opening output for device %08x with params %s profile %p name %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00006515 deviceType, address.c_str(), profile.get(), profile->getName().c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07006516 desc = openOutputWithProfileAndDevice(profile, DeviceVector(device));
6517 audio_io_handle_t output = desc == nullptr ? AUDIO_IO_HANDLE_NONE : desc->mIoHandle;
Eric Laurentcf2c0212014-07-25 16:20:43 -07006518 if (output == AUDIO_IO_HANDLE_NONE) {
François Gaffie11d30102018-11-02 16:09:09 +01006519 ALOGW("checkOutputsForDevice() could not open output for device %x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006520 profiles.removeAt(profile_index);
6521 profile_index--;
6522 } else {
6523 outputs.add(output);
Paul McLean9080a4c2015-06-18 08:24:02 -07006524 // Load digital format info only for digital devices
François Gaffie11d30102018-11-02 16:09:09 +01006525 if (audio_device_is_digital(deviceType)) {
jiabinbce0c1d2020-10-05 11:20:18 -07006526 // TODO: when getAudioPort is ready, it may not be needed to import the audio
6527 // port but just pick audio profile
jiabin4ef93452019-09-10 14:29:54 -07006528 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006529 }
Jean-Michel Trivif17026d2014-08-10 14:30:48 -07006530
François Gaffie11d30102018-11-02 16:09:09 +01006531 if (device_distinguishes_on_address(deviceType)) {
6532 ALOGV("checkOutputsForDevice(): setOutputDevices %s",
6533 device->toString().c_str());
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05306534 setOutputDevices(__func__, desc, DeviceVector(device), true/*force*/,
6535 0/*delay*/, NULL/*patch handle*/);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006536 }
Eric Laurente552edb2014-03-10 17:42:56 -07006537 ALOGV("checkOutputsForDevice(): adding output %d", output);
6538 }
6539 }
6540
6541 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006542 ALOGW("checkOutputsForDevice(): No output available for device %04x", deviceType);
Eric Laurente552edb2014-03-10 17:42:56 -07006543 return BAD_VALUE;
6544 }
Eric Laurentd4692962014-05-05 18:13:44 -07006545 } else { // Disconnect
Eric Laurente552edb2014-03-10 17:42:56 -07006546 // check if one opened output is not needed any more after disconnecting one device
6547 for (size_t i = 0; i < mOutputs.size(); i++) {
6548 desc = mOutputs.valueAt(i);
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006549 if (!desc->isDuplicated()) {
Eric Laurent275e8e92014-11-30 15:14:47 -08006550 // exact match on device
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006551 if (device_distinguishes_on_address(deviceType) && desc->supportsDevice(device)
Francois Gaffiec7d4c222021-12-02 11:12:52 +01006552 && desc->containsSingleDeviceSupportingEncodedFormats(device)) {
François Gaffie11d30102018-11-02 16:09:09 +01006553 outputs.add(mOutputs.keyAt(i));
Francois Gaffie716e1432019-01-14 16:58:59 +01006554 } else if (!mAvailableOutputDevices.containsAtLeastOne(desc->supportedDevices())) {
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006555 ALOGV("checkOutputsForDevice(): disconnecting adding output %d",
6556 mOutputs.keyAt(i));
6557 outputs.add(mOutputs.keyAt(i));
Jean-Michel Trivi0fb47752014-07-22 16:19:14 -07006558 }
Eric Laurente552edb2014-03-10 17:42:56 -07006559 }
6560 }
Eric Laurentd4692962014-05-05 18:13:44 -07006561 // Clear any profiles associated with the disconnected device.
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006562 for (const auto& hwModule : mHwModules) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006563 for (size_t j = 0; j < hwModule->getOutputProfiles().size(); j++) {
6564 sp<IOProfile> profile = hwModule->getOutputProfiles()[j];
jiabinbce0c1d2020-10-05 11:20:18 -07006565 if (!profile->supportsDevice(device)) {
6566 continue;
6567 }
6568 ALOGV("checkOutputsForDevice(): "
6569 "clearing direct output profile %zu on module %s",
6570 j, hwModule->getName());
6571 profile->clearAudioProfiles();
6572 if (!profile->hasDynamicAudioProfile()) {
6573 continue;
6574 }
6575 // When a device is disconnected, if there is an IOProfile that contains dynamic
6576 // profiles and supports the disconnected device, call getAudioPort to repopulate
6577 // the capabilities of the devices that is supported by the IOProfile.
6578 for (const auto& supportedDevice : profile->getSupportedDevices()) {
6579 if (supportedDevice == device ||
6580 !mAvailableOutputDevices.contains(supportedDevice)) {
6581 continue;
6582 }
6583 struct audio_port_v7 port;
6584 supportedDevice->toAudioPort(&port);
6585 status_t status = mpClientInterface->getAudioPort(&port);
6586 if (status == NO_ERROR) {
6587 supportedDevice->importAudioPort(port);
6588 }
Eric Laurente552edb2014-03-10 17:42:56 -07006589 }
6590 }
6591 }
6592 }
6593 return NO_ERROR;
6594}
6595
François Gaffie11d30102018-11-02 16:09:09 +01006596status_t AudioPolicyManager::checkInputsForDevice(const sp<DeviceDescriptor>& device,
Eric Laurent0dd51852019-04-19 18:18:58 -07006597 audio_policy_dev_state_t state)
Eric Laurentd4692962014-05-05 18:13:44 -07006598{
Eric Laurent1f2f2232014-06-02 12:01:23 -07006599 sp<AudioInputDescriptor> desc;
Eric Laurentcc750d32015-06-25 11:48:20 -07006600
François Gaffie11d30102018-11-02 16:09:09 +01006601 if (audio_device_is_digital(device->type())) {
Eric Laurentcc750d32015-06-25 11:48:20 -07006602 // erase all current sample rates, formats and channel masks
François Gaffie11d30102018-11-02 16:09:09 +01006603 device->clearAudioProfiles();
Eric Laurentcc750d32015-06-25 11:48:20 -07006604 }
6605
Eric Laurentd4692962014-05-05 18:13:44 -07006606 if (state == AUDIO_POLICY_DEVICE_STATE_AVAILABLE) {
jiabinbf5f4262023-04-12 21:48:34 +00006607 // first call getAudioPort to get the supported attributes from the HAL
6608 struct audio_port_v7 port = {};
6609 device->toAudioPort(&port);
6610 status_t status = mpClientInterface->getAudioPort(&port);
6611 if (status == NO_ERROR) {
6612 device->importAudioPort(port);
6613 }
6614
Eric Laurent0dd51852019-04-19 18:18:58 -07006615 // look for input profiles that can be routed to this device
Eric Laurent1c333e22014-05-20 10:48:17 -07006616 SortedVector< sp<IOProfile> > profiles;
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006617 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006618 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006619 profile_index < hwModule->getInputProfiles().size();
Mikhail Naganov7e22e942017-12-07 10:04:29 -08006620 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006621 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Eric Laurent275e8e92014-11-30 15:14:47 -08006622
François Gaffie11d30102018-11-02 16:09:09 +01006623 if (profile->supportsDevice(device)) {
6624 profiles.add(profile);
6625 ALOGV("checkInputsForDevice(): adding profile %zu from module %s",
6626 profile_index, hwModule->getName());
Eric Laurentd4692962014-05-05 18:13:44 -07006627 }
6628 }
6629 }
6630
Eric Laurent0dd51852019-04-19 18:18:58 -07006631 if (profiles.isEmpty()) {
6632 ALOGW("%s: No input profile available for device %s",
6633 __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006634 return BAD_VALUE;
6635 }
6636
6637 // open inputs for matching profiles if needed. Direct inputs are also opened to
6638 // query for dynamic parameters and will be closed later by setDeviceConnectionState()
6639 for (ssize_t profile_index = 0; profile_index < (ssize_t)profiles.size(); profile_index++) {
6640
Eric Laurent1c333e22014-05-20 10:48:17 -07006641 sp<IOProfile> profile = profiles[profile_index];
Eric Laurent3974e3b2017-12-07 17:58:43 -08006642
Eric Laurentd4692962014-05-05 18:13:44 -07006643 // nothing to do if one input is already opened for this profile
6644 size_t input_index;
6645 for (input_index = 0; input_index < mInputs.size(); input_index++) {
6646 desc = mInputs.valueAt(input_index);
6647 if (desc->mProfile == profile) {
François Gaffie11d30102018-11-02 16:09:09 +01006648 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006649 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006650 }
Eric Laurentd4692962014-05-05 18:13:44 -07006651 break;
6652 }
6653 }
6654 if (input_index != mInputs.size()) {
6655 continue;
6656 }
6657
Eric Laurent3974e3b2017-12-07 17:58:43 -08006658 if (!profile->canOpenNewIo()) {
6659 ALOGW("Max Input number %u already opened for this profile %s",
6660 profile->maxOpenCount, profile->getTagName().c_str());
6661 continue;
6662 }
6663
Eric Laurentfe231122017-11-17 17:48:06 -08006664 desc = new AudioInputDescriptor(profile, mpClientInterface);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006665 audio_io_handle_t input = AUDIO_IO_HANDLE_NONE;
jiabinbf5f4262023-04-12 21:48:34 +00006666 status = desc->open(nullptr, device, AUDIO_SOURCE_MIC, AUDIO_INPUT_FLAG_NONE, &input);
Eric Laurentd4692962014-05-05 18:13:44 -07006667
Eric Laurentcf2c0212014-07-25 16:20:43 -07006668 if (status == NO_ERROR) {
jiabince9f20e2019-09-12 16:29:15 -07006669 const String8& address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00006670 if (!address.empty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006671 char *param = audio_device_address_to_parameter(device->type(), address);
Eric Laurentcf2c0212014-07-25 16:20:43 -07006672 mpClientInterface->setParameters(input, String8(param));
6673 free(param);
Eric Laurentd4692962014-05-05 18:13:44 -07006674 }
jiabin12537fc2023-10-12 17:56:08 +00006675 updateAudioProfiles(device, input, profile);
François Gaffie112b0af2015-11-19 16:13:25 +01006676 if (!profile->hasValidAudioProfile()) {
Eric Laurentd4692962014-05-05 18:13:44 -07006677 ALOGW("checkInputsForDevice() direct input missing param");
Eric Laurentfe231122017-11-17 17:48:06 -08006678 desc->close();
Eric Laurentcf2c0212014-07-25 16:20:43 -07006679 input = AUDIO_IO_HANDLE_NONE;
Eric Laurentd4692962014-05-05 18:13:44 -07006680 }
6681
Eric Laurent0dd51852019-04-19 18:18:58 -07006682 if (input != AUDIO_IO_HANDLE_NONE) {
Eric Laurentd4692962014-05-05 18:13:44 -07006683 addInput(input, desc);
6684 }
6685 } // endif input != 0
6686
Eric Laurentcf2c0212014-07-25 16:20:43 -07006687 if (input == AUDIO_IO_HANDLE_NONE) {
Pattydd807582021-11-04 21:01:03 +08006688 ALOGW("%s could not open input for device %s", __func__,
François Gaffie11d30102018-11-02 16:09:09 +01006689 device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006690 profiles.removeAt(profile_index);
6691 profile_index--;
6692 } else {
François Gaffie11d30102018-11-02 16:09:09 +01006693 if (audio_device_is_digital(device->type())) {
jiabin4ef93452019-09-10 14:29:54 -07006694 device->importAudioPortAndPickAudioProfile(profile);
Paul McLean9080a4c2015-06-18 08:24:02 -07006695 }
Eric Laurentd4692962014-05-05 18:13:44 -07006696 ALOGV("checkInputsForDevice(): adding input %d", input);
6697 }
6698 } // end scan profiles
6699
6700 if (profiles.isEmpty()) {
François Gaffie11d30102018-11-02 16:09:09 +01006701 ALOGW("%s: No input available for device %s", __func__, device->toString().c_str());
Eric Laurentd4692962014-05-05 18:13:44 -07006702 return BAD_VALUE;
6703 }
6704 } else {
6705 // Disconnect
Eric Laurentd4692962014-05-05 18:13:44 -07006706 // Clear any profiles associated with the disconnected device.
Mikhail Naganovd4120142017-12-06 15:49:22 -08006707 for (const auto& hwModule : mHwModules) {
Eric Laurentd4692962014-05-05 18:13:44 -07006708 for (size_t profile_index = 0;
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006709 profile_index < hwModule->getInputProfiles().size();
Eric Laurentd4692962014-05-05 18:13:44 -07006710 profile_index++) {
Mikhail Naganova5e165d2017-12-07 17:08:02 -08006711 sp<IOProfile> profile = hwModule->getInputProfiles()[profile_index];
Francois Gaffie716e1432019-01-14 16:58:59 +01006712 if (profile->supportsDevice(device)) {
Mikhail Naganovd4120142017-12-06 15:49:22 -08006713 ALOGV("checkInputsForDevice(): clearing direct input profile %zu on module %s",
6714 profile_index, hwModule->getName());
François Gaffie112b0af2015-11-19 16:13:25 +01006715 profile->clearAudioProfiles();
Eric Laurentd4692962014-05-05 18:13:44 -07006716 }
6717 }
6718 }
6719 } // end disconnect
6720
6721 return NO_ERROR;
6722}
6723
6724
Eric Laurente0720872014-03-11 09:30:41 -07006725void AudioPolicyManager::closeOutput(audio_io_handle_t output)
Eric Laurente552edb2014-03-10 17:42:56 -07006726{
6727 ALOGV("closeOutput(%d)", output);
6728
François Gaffie1c878552018-11-22 16:53:21 +01006729 sp<SwAudioOutputDescriptor> closingOutput = mOutputs.valueFor(output);
6730 if (closingOutput == NULL) {
Eric Laurente552edb2014-03-10 17:42:56 -07006731 ALOGW("closeOutput() unknown output %d", output);
6732 return;
6733 }
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006734 const bool closingOutputWasActive = closingOutput->isActive();
jiabin24ff57a2023-11-27 21:06:51 +00006735 mPolicyMixes.closeOutput(closingOutput, mOutputs);
Eric Laurent275e8e92014-11-30 15:14:47 -08006736
Eric Laurente552edb2014-03-10 17:42:56 -07006737 // look for duplicated outputs connected to the output being removed.
6738 for (size_t i = 0; i < mOutputs.size(); i++) {
François Gaffie1c878552018-11-22 16:53:21 +01006739 sp<SwAudioOutputDescriptor> dupOutput = mOutputs.valueAt(i);
6740 if (dupOutput->isDuplicated() &&
6741 (dupOutput->mOutput1 == closingOutput || dupOutput->mOutput2 == closingOutput)) {
6742 sp<SwAudioOutputDescriptor> remainingOutput =
6743 dupOutput->mOutput1 == closingOutput ? dupOutput->mOutput2 : dupOutput->mOutput1;
Eric Laurente552edb2014-03-10 17:42:56 -07006744 // As all active tracks on duplicated output will be deleted,
6745 // and as they were also referenced on the other output, the reference
6746 // count for their stream type must be adjusted accordingly on
6747 // the other output.
François Gaffie1c878552018-11-22 16:53:21 +01006748 const bool wasActive = remainingOutput->isActive();
6749 // Note: no-op on the closing output where all clients has already been set inactive
6750 dupOutput->setAllClientsInactive();
Eric Laurent733ce942017-12-07 12:18:25 -08006751 // stop() will be a no op if the output is still active but is needed in case all
6752 // active streams refcounts where cleared above
6753 if (wasActive) {
François Gaffie1c878552018-11-22 16:53:21 +01006754 remainingOutput->stop();
Eric Laurent733ce942017-12-07 12:18:25 -08006755 }
Eric Laurente552edb2014-03-10 17:42:56 -07006756 audio_io_handle_t duplicatedOutput = mOutputs.keyAt(i);
6757 ALOGV("closeOutput() closing also duplicated output %d", duplicatedOutput);
6758
6759 mpClientInterface->closeOutput(duplicatedOutput);
François Gaffie53615e22015-03-19 09:24:12 +01006760 removeOutput(duplicatedOutput);
Eric Laurente552edb2014-03-10 17:42:56 -07006761 }
6762 }
6763
Eric Laurent05b90f82014-08-27 15:32:29 -07006764 nextAudioPortGeneration();
6765
François Gaffie1c878552018-11-22 16:53:21 +01006766 ssize_t index = mAudioPatches.indexOfKey(closingOutput->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006767 if (index >= 0) {
6768 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006769 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6770 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006771 mAudioPatches.removeItemsAt(index);
6772 mpClientInterface->onAudioPatchListUpdate();
6773 }
6774
Mikhail Naganov32ebca32019-03-22 15:42:52 -07006775 if (closingOutputWasActive) {
6776 closingOutput->stop();
6777 }
François Gaffie1c878552018-11-22 16:53:21 +01006778 closingOutput->close();
jiabin14b50cc2023-12-13 19:01:52 +00006779 if ((closingOutput->getFlags().output & AUDIO_OUTPUT_FLAG_BIT_PERFECT)
6780 == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
6781 for (const auto device : closingOutput->devices()) {
6782 device->setPreferredConfig(nullptr);
6783 }
6784 }
Eric Laurente552edb2014-03-10 17:42:56 -07006785
François Gaffie53615e22015-03-19 09:24:12 +01006786 removeOutput(output);
Eric Laurente552edb2014-03-10 17:42:56 -07006787 mPreviousOutputs = mOutputs;
Eric Laurentb4f42a92022-01-17 17:37:31 +01006788 if (closingOutput == mSpatializerOutput) {
6789 mSpatializerOutput.clear();
6790 }
Dean Wheatley3023b382018-08-09 07:42:40 +10006791
6792 // MSD patches may have been released to support a non-MSD direct output. Reset MSD patch if
6793 // no direct outputs are open.
François Gaffie11d30102018-11-02 16:09:09 +01006794 if (!getMsdAudioOutDevices().isEmpty()) {
Dean Wheatley3023b382018-08-09 07:42:40 +10006795 bool directOutputOpen = false;
6796 for (size_t i = 0; i < mOutputs.size(); i++) {
6797 if (mOutputs[i]->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) {
6798 directOutputOpen = true;
6799 break;
6800 }
6801 }
6802 if (!directOutputOpen) {
Michael Chan6fb34492020-12-08 15:44:49 +11006803 ALOGV("no direct outputs open, reset MSD patches");
6804 // TODO: The MSD patches to be established here may differ to current MSD patches due to
6805 // how output devices for patching are resolved. Avoid by caching and reusing the
6806 // arguments to mEngine->getOutputDevicesForAttributes() when resolving which output
6807 // devices to patch to. This may be complicated by the fact that devices may become
6808 // unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006809 setMsdOutputPatches();
Dean Wheatley3023b382018-08-09 07:42:40 +10006810 }
6811 }
Eric Laurent05b90f82014-08-27 15:32:29 -07006812}
6813
6814void AudioPolicyManager::closeInput(audio_io_handle_t input)
6815{
6816 ALOGV("closeInput(%d)", input);
6817
6818 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
6819 if (inputDesc == NULL) {
6820 ALOGW("closeInput() unknown input %d", input);
6821 return;
6822 }
6823
Eric Laurent6a94d692014-05-20 11:18:06 -07006824 nextAudioPortGeneration();
Eric Laurent05b90f82014-08-27 15:32:29 -07006825
François Gaffie11d30102018-11-02 16:09:09 +01006826 sp<DeviceDescriptor> device = inputDesc->getDevice();
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08006827 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent05b90f82014-08-27 15:32:29 -07006828 if (index >= 0) {
6829 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01006830 (void) /*status_t status*/ mpClientInterface->releaseAudioPatch(
6831 patchDesc->getAfHandle(), 0);
Eric Laurent05b90f82014-08-27 15:32:29 -07006832 mAudioPatches.removeItemsAt(index);
6833 mpClientInterface->onAudioPatchListUpdate();
6834 }
6835
François Gaffie6ebbce02023-07-19 13:27:53 +02006836 mEffects.putOrphanEffectsForIo(input);
Eric Laurentfe231122017-11-17 17:48:06 -08006837 inputDesc->close();
Eric Laurent05b90f82014-08-27 15:32:29 -07006838 mInputs.removeItem(input);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006839
François Gaffie11d30102018-11-02 16:09:09 +01006840 DeviceVector primaryInputDevices = availablePrimaryModuleInputDevices();
6841 if (primaryInputDevices.contains(device) &&
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006842 mInputs.activeInputsCountOnDevices(primaryInputDevices) == 0) {
Ytai Ben-Tsvi74cd6b02019-10-25 10:06:40 -07006843 mpClientInterface->setSoundTriggerCaptureState(false);
Haynes Mathew George1d539d92018-03-16 11:40:49 -07006844 }
Eric Laurente552edb2014-03-10 17:42:56 -07006845}
6846
François Gaffie11d30102018-11-02 16:09:09 +01006847SortedVector<audio_io_handle_t> AudioPolicyManager::getOutputsForDevices(
6848 const DeviceVector &devices,
6849 const SwAudioOutputCollection& openOutputs)
Eric Laurente552edb2014-03-10 17:42:56 -07006850{
6851 SortedVector<audio_io_handle_t> outputs;
6852
François Gaffie11d30102018-11-02 16:09:09 +01006853 ALOGVV("%s() devices %s", __func__, devices.toString().c_str());
Eric Laurente552edb2014-03-10 17:42:56 -07006854 for (size_t i = 0; i < openOutputs.size(); i++) {
François Gaffie11d30102018-11-02 16:09:09 +01006855 ALOGVV("output %zu isDuplicated=%d device=%s",
Eric Laurent8c7e6da2015-04-21 17:37:00 -07006856 i, openOutputs.valueAt(i)->isDuplicated(),
François Gaffie11d30102018-11-02 16:09:09 +01006857 openOutputs.valueAt(i)->supportedDevices().toString().c_str());
Aniket Kumar Lata4e464702019-01-10 23:38:46 -08006858 if (openOutputs.valueAt(i)->supportsAllDevices(devices)
jiabin9a3361e2019-10-01 09:38:30 -07006859 && openOutputs.valueAt(i)->devicesSupportEncodedFormats(devices.types())) {
François Gaffie11d30102018-11-02 16:09:09 +01006860 ALOGVV("%s() found output %d", __func__, openOutputs.keyAt(i));
Eric Laurente552edb2014-03-10 17:42:56 -07006861 outputs.add(openOutputs.keyAt(i));
6862 }
6863 }
6864 return outputs;
6865}
6866
Mikhail Naganov37977152018-07-11 15:54:44 -07006867void AudioPolicyManager::checkForDeviceAndOutputChanges(std::function<bool()> onOutputsChecked)
6868{
6869 // checkA2dpSuspend must run before checkOutputForAllStrategies so that A2DP
6870 // output is suspended before any tracks are moved to it
6871 checkA2dpSuspend();
6872 checkOutputForAllStrategies();
Kevin Rocard153f92d2018-12-18 18:33:28 -08006873 checkSecondaryOutputs();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006874 if (onOutputsChecked != nullptr && onOutputsChecked()) checkA2dpSuspend();
Mikhail Naganov37977152018-07-11 15:54:44 -07006875 updateDevicesAndOutputs();
Mikhail Naganov7bd9b8d2018-11-15 02:09:03 +00006876 if (mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD) != 0) {
Michael Chan6fb34492020-12-08 15:44:49 +11006877 // TODO: The MSD patches to be established here may differ to current MSD patches due to how
6878 // output devices for patching are resolved. Nevertheless, AudioTracks affected by device
6879 // configuration changes will ultimately be rerouted correctly. We can still avoid
6880 // unnecessary rerouting by caching and reusing the arguments to
6881 // mEngine->getOutputDevicesForAttributes() when resolving which output devices to patch to.
6882 // This may be complicated by the fact that devices may become unavailable.
Dean Wheatley8bee85a2021-02-10 16:02:23 +11006883 setMsdOutputPatches();
Mikhail Naganov15be9d22017-11-08 14:18:13 +11006884 }
Jean-Michel Trivi9a6b9ad2020-10-22 16:46:43 -07006885 // an event that changed routing likely occurred, inform upper layers
6886 mpClientInterface->onRoutingUpdated();
Mikhail Naganov37977152018-07-11 15:54:44 -07006887}
6888
François Gaffiec005e562018-11-06 15:04:49 +01006889bool AudioPolicyManager::followsSameRouting(const audio_attributes_t &lAttr,
6890 const audio_attributes_t &rAttr) const
Eric Laurente552edb2014-03-10 17:42:56 -07006891{
François Gaffiec005e562018-11-06 15:04:49 +01006892 return mEngine->getProductStrategyForAttributes(lAttr) ==
6893 mEngine->getProductStrategyForAttributes(rAttr);
6894}
6895
Francois Gaffieff1eb522020-05-06 18:37:04 +02006896void AudioPolicyManager::checkAudioSourceForAttributes(const audio_attributes_t &attr)
6897{
6898 for (size_t i = 0; i < mAudioSources.size(); i++) {
6899 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6900 if (sourceDesc != nullptr && followsSameRouting(attr, sourceDesc->attributes())
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02006901 && sourceDesc->getPatchHandle() == AUDIO_PATCH_HANDLE_NONE
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02006902 && !isCallRxAudioSource(sourceDesc) && !sourceDesc->isInternal()) {
Francois Gaffieff1eb522020-05-06 18:37:04 +02006903 connectAudioSource(sourceDesc);
6904 }
6905 }
6906}
6907
6908void AudioPolicyManager::clearAudioSourcesForOutput(audio_io_handle_t output)
6909{
6910 for (size_t i = 0; i < mAudioSources.size(); i++) {
6911 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
6912 if (sourceDesc != nullptr && sourceDesc->swOutput().promote() != nullptr
6913 && sourceDesc->swOutput().promote()->mIoHandle == output) {
6914 disconnectAudioSource(sourceDesc);
6915 }
6916 }
6917}
6918
François Gaffiec005e562018-11-06 15:04:49 +01006919void AudioPolicyManager::checkOutputForAttributes(const audio_attributes_t &attr)
6920{
6921 auto psId = mEngine->getProductStrategyForAttributes(attr);
6922
6923 DeviceVector oldDevices = mEngine->getOutputDevicesForAttributes(attr, 0, true /*fromCache*/);
6924 DeviceVector newDevices = mEngine->getOutputDevicesForAttributes(attr, 0, false /*fromCache*/);
Jean-Michel Trivi30857152019-11-01 11:04:15 -07006925
François Gaffie11d30102018-11-02 16:09:09 +01006926 SortedVector<audio_io_handle_t> srcOutputs = getOutputsForDevices(oldDevices, mPreviousOutputs);
6927 SortedVector<audio_io_handle_t> dstOutputs = getOutputsForDevices(newDevices, mOutputs);
Eric Laurente552edb2014-03-10 17:42:56 -07006928
Eric Laurentc209fe42020-06-05 18:11:23 -07006929 uint32_t maxLatency = 0;
Oscar Azucena873d10f2023-01-12 18:34:42 -08006930 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Eric Laurent56ed8842022-11-15 16:04:41 +01006931 std::vector<sp<SwAudioOutputDescriptor>> invalidatedOutputs;
Eric Laurentc209fe42020-06-05 18:11:23 -07006932 // take into account dynamic audio policies related changes: if a client is now associated
6933 // to a different policy mix than at creation time, invalidate corresponding stream
Eric Laurent56ed8842022-11-15 16:04:41 +01006934 for (size_t i = 0; i < mPreviousOutputs.size(); i++) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006935 const sp<SwAudioOutputDescriptor>& desc = mPreviousOutputs.valueAt(i);
6936 if (desc->isDuplicated()) {
6937 continue;
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006938 }
Eric Laurentc209fe42020-06-05 18:11:23 -07006939 for (const sp<TrackClientDescriptor>& client : desc->getClientIterable()) {
6940 if (mEngine->getProductStrategyForAttributes(client->attributes()) != psId) {
6941 continue;
6942 }
6943 sp<AudioPolicyMix> primaryMix;
Dean Wheatleyd082f472022-02-04 11:10:48 +11006944 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08006945 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
6946 nullptr /* requestedDevice */, primaryMix, nullptr /* secondaryMixes */,
6947 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc209fe42020-06-05 18:11:23 -07006948 if (status != OK) {
6949 continue;
6950 }
yucliuf4de36d2020-09-14 14:57:56 -07006951 if (client->getPrimaryMix() != primaryMix || client->hasLostPrimaryMix()) {
Eric Laurent56ed8842022-11-15 16:04:41 +01006952 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentc209fe42020-06-05 18:11:23 -07006953 maxLatency = desc->latency();
6954 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006955 invalidatedOutputs.push_back(desc);
Eric Laurentc209fe42020-06-05 18:11:23 -07006956 }
Jean-Michel Trivife472e22014-12-16 14:23:13 -08006957 }
6958 }
6959
Eric Laurent56ed8842022-11-15 16:04:41 +01006960 if (srcOutputs != dstOutputs || !invalidatedOutputs.empty()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006961 // get maximum latency of all source outputs to determine the minimum mute time guaranteeing
6962 // audio from invalidated tracks will be rendered when unmuting
Eric Laurentac3a6902018-05-11 16:39:10 -07006963 for (audio_io_handle_t srcOut : srcOutputs) {
6964 sp<SwAudioOutputDescriptor> desc = mPreviousOutputs.valueFor(srcOut);
Eric Laurentaa02db82019-09-05 17:31:49 -07006965 if (desc == nullptr) continue;
6966
6967 if (desc->isStrategyActive(psId) && maxLatency < desc->latency()) {
Eric Laurentac3a6902018-05-11 16:39:10 -07006968 maxLatency = desc->latency();
6969 }
Eric Laurentaa02db82019-09-05 17:31:49 -07006970
Eric Laurent56ed8842022-11-15 16:04:41 +01006971 bool invalidate = false;
Eric Laurentaa02db82019-09-05 17:31:49 -07006972 for (auto client : desc->clientsList(false /*activeOnly*/)) {
Eric Laurent78aade82019-09-13 18:55:08 -07006973 if (desc->isDuplicated() || !desc->mProfile->isDirectOutput()) {
Eric Laurentaa02db82019-09-05 17:31:49 -07006974 // a client on a non direct outputs has necessarily a linear PCM format
6975 // so we can call selectOutput() safely
6976 const audio_io_handle_t newOutput = selectOutput(dstOutputs,
6977 client->flags(),
6978 client->config().format,
6979 client->config().channel_mask,
jiabinebb6af42020-06-09 17:31:17 -07006980 client->config().sample_rate,
6981 client->session());
Eric Laurentaa02db82019-09-05 17:31:49 -07006982 if (newOutput != srcOut) {
6983 invalidate = true;
6984 break;
6985 }
6986 } else {
6987 sp<IOProfile> profile = getProfileForOutput(newDevices,
6988 client->config().sample_rate,
6989 client->config().format,
6990 client->config().channel_mask,
6991 client->flags(),
6992 true /* directOnly */);
6993 if (profile != desc->mProfile) {
6994 invalidate = true;
6995 break;
6996 }
6997 }
6998 }
Eric Laurent56ed8842022-11-15 16:04:41 +01006999 // mute strategy while moving tracks from one output to another
7000 if (invalidate) {
7001 invalidatedOutputs.push_back(desc);
7002 if (desc->isStrategyActive(psId)) {
7003 setStrategyMute(psId, true, desc);
7004 setStrategyMute(psId, false, desc, maxLatency * LATENCY_MUTE_FACTOR,
7005 newDevices.types());
7006 }
Eric Laurente552edb2014-03-10 17:42:56 -07007007 }
François Gaffiec005e562018-11-06 15:04:49 +01007008 sp<SourceClientDescriptor> source = getSourceForAttributesOnOutput(srcOut, attr);
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007009 if (source != nullptr && !isCallRxAudioSource(source) && !source->isInternal()) {
Eric Laurentd60560a2015-04-10 11:31:20 -07007010 connectAudioSource(source);
7011 }
Eric Laurente552edb2014-03-10 17:42:56 -07007012 }
7013
Eric Laurent56ed8842022-11-15 16:04:41 +01007014 ALOGV_IF(!(srcOutputs.isEmpty() || dstOutputs.isEmpty()),
7015 "%s: strategy %d, moving from output %s to output %s", __func__, psId,
7016 std::to_string(srcOutputs[0]).c_str(),
7017 std::to_string(dstOutputs[0]).c_str());
7018
François Gaffiec005e562018-11-06 15:04:49 +01007019 // Move effects associated to this stream from previous output to new output
7020 if (followsSameRouting(attr, attributes_initializer(AUDIO_USAGE_MEDIA))) {
Eric Laurent36829f92017-04-07 19:04:42 -07007021 selectOutputForMusicEffects();
Eric Laurente552edb2014-03-10 17:42:56 -07007022 }
François Gaffiec005e562018-11-06 15:04:49 +01007023 // Move tracks associated to this stream (and linked) from previous output to new output
Eric Laurent56ed8842022-11-15 16:04:41 +01007024 if (!invalidatedOutputs.empty()) {
jiabinc44b3462022-12-08 12:52:31 -08007025 invalidateStreams(mEngine->getStreamTypesForProductStrategy(psId));
Eric Laurent56ed8842022-11-15 16:04:41 +01007026 for (sp<SwAudioOutputDescriptor> desc : invalidatedOutputs) {
jiabin49256852022-03-09 11:21:35 -08007027 desc->setTracksInvalidatedStatusByStrategy(psId);
7028 }
Eric Laurente552edb2014-03-10 17:42:56 -07007029 }
7030 }
7031}
7032
Eric Laurente0720872014-03-11 09:30:41 -07007033void AudioPolicyManager::checkOutputForAllStrategies()
Eric Laurente552edb2014-03-10 17:42:56 -07007034{
François Gaffiec005e562018-11-06 15:04:49 +01007035 for (const auto &strategy : mEngine->getOrderedProductStrategies()) {
7036 auto attributes = mEngine->getAllAttributesForProductStrategy(strategy).front();
7037 checkOutputForAttributes(attributes);
Francois Gaffieff1eb522020-05-06 18:37:04 +02007038 checkAudioSourceForAttributes(attributes);
François Gaffiec005e562018-11-06 15:04:49 +01007039 }
Eric Laurente552edb2014-03-10 17:42:56 -07007040}
7041
Kevin Rocard153f92d2018-12-18 18:33:28 -08007042void AudioPolicyManager::checkSecondaryOutputs() {
jiabinc44b3462022-12-08 12:52:31 -08007043 PortHandleVector clientsToInvalidate;
jiabin10a03f12021-05-07 23:46:28 +00007044 TrackSecondaryOutputsMap trackSecondaryOutputs;
Oscar Azucena873d10f2023-01-12 18:34:42 -08007045 bool unneededUsePrimaryOutputFromPolicyMixes = false;
Kevin Rocard153f92d2018-12-18 18:33:28 -08007046 for (size_t i = 0; i < mOutputs.size(); i++) {
7047 const sp<SwAudioOutputDescriptor>& outputDescriptor = mOutputs[i];
7048 for (const sp<TrackClientDescriptor>& client : outputDescriptor->getClientIterable()) {
Eric Laurentc529cf62020-04-17 18:19:10 -07007049 sp<AudioPolicyMix> primaryMix;
7050 std::vector<sp<AudioPolicyMix>> secondaryMixes;
Dean Wheatleyd082f472022-02-04 11:10:48 +11007051 status_t status = mPolicyMixes.getOutputForAttr(client->attributes(), client->config(),
Oscar Azucena873d10f2023-01-12 18:34:42 -08007052 client->uid(), client->session(), client->flags(), mAvailableOutputDevices,
7053 nullptr /* requestedDevice */, primaryMix, &secondaryMixes,
7054 unneededUsePrimaryOutputFromPolicyMixes);
Eric Laurentc529cf62020-04-17 18:19:10 -07007055 std::vector<sp<SwAudioOutputDescriptor>> secondaryDescs;
7056 for (auto &secondaryMix : secondaryMixes) {
7057 sp<SwAudioOutputDescriptor> outputDesc = secondaryMix->getOutput();
7058 if (outputDesc != nullptr &&
7059 outputDesc->mIoHandle != AUDIO_IO_HANDLE_NONE) {
7060 secondaryDescs.push_back(outputDesc);
7061 }
7062 }
7063
jiabinc44b3462022-12-08 12:52:31 -08007064 if (status != OK &&
7065 (client->flags() & AUDIO_OUTPUT_FLAG_MMAP_NOIRQ) == AUDIO_OUTPUT_FLAG_NONE) {
7066 // When it failed to query secondary output, only invalidate the client that is not
7067 // MMAP. The reason is that MMAP stream will not support secondary output.
7068 clientsToInvalidate.push_back(client->portId());
jiabin10a03f12021-05-07 23:46:28 +00007069 } else if (!std::equal(
7070 client->getSecondaryOutputs().begin(),
7071 client->getSecondaryOutputs().end(),
7072 secondaryDescs.begin(), secondaryDescs.end())) {
jiabina5281062021-11-23 00:10:23 +00007073 if (!audio_is_linear_pcm(client->config().format)) {
7074 // If the format is not PCM, the tracks should be invalidated to get correct
7075 // behavior when the secondary output is changed.
jiabinc44b3462022-12-08 12:52:31 -08007076 clientsToInvalidate.push_back(client->portId());
jiabina5281062021-11-23 00:10:23 +00007077 } else {
7078 std::vector<wp<SwAudioOutputDescriptor>> weakSecondaryDescs;
7079 std::vector<audio_io_handle_t> secondaryOutputIds;
7080 for (const auto &secondaryDesc: secondaryDescs) {
7081 secondaryOutputIds.push_back(secondaryDesc->mIoHandle);
7082 weakSecondaryDescs.push_back(secondaryDesc);
7083 }
7084 trackSecondaryOutputs.emplace(client->portId(), secondaryOutputIds);
7085 client->setSecondaryOutputs(std::move(weakSecondaryDescs));
jiabin10a03f12021-05-07 23:46:28 +00007086 }
Kevin Rocard153f92d2018-12-18 18:33:28 -08007087 }
7088 }
7089 }
jiabin10a03f12021-05-07 23:46:28 +00007090 if (!trackSecondaryOutputs.empty()) {
7091 mpClientInterface->updateSecondaryOutputs(trackSecondaryOutputs);
7092 }
jiabinc44b3462022-12-08 12:52:31 -08007093 if (!clientsToInvalidate.empty()) {
7094 ALOGD("%s Invalidate clients due to fail getting output for attr", __func__);
7095 mpClientInterface->invalidateTracks(clientsToInvalidate);
Kevin Rocard153f92d2018-12-18 18:33:28 -08007096 }
7097}
7098
Eric Laurent2517af32020-11-25 15:31:27 +01007099bool AudioPolicyManager::isScoRequestedForComm() const {
7100 AudioDeviceTypeAddrVector devices;
7101 mEngine->getDevicesForRoleAndStrategy(mCommunnicationStrategy, DEVICE_ROLE_PREFERRED, devices);
7102 for (const auto &device : devices) {
7103 if (audio_is_bluetooth_out_sco_device(device.mType)) {
7104 return true;
7105 }
7106 }
7107 return false;
7108}
7109
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007110bool AudioPolicyManager::isHearingAidUsedForComm() const {
7111 DeviceVector devices = mEngine->getOutputDevicesForStream(AUDIO_STREAM_VOICE_CALL,
7112 true /*fromCache*/);
7113 for (const auto &device : devices) {
7114 if (device->type() == AUDIO_DEVICE_OUT_HEARING_AID) {
7115 return true;
7116 }
7117 }
7118 return false;
7119}
7120
7121
Eric Laurente0720872014-03-11 09:30:41 -07007122void AudioPolicyManager::checkA2dpSuspend()
Eric Laurente552edb2014-03-10 17:42:56 -07007123{
François Gaffie53615e22015-03-19 09:24:12 +01007124 audio_io_handle_t a2dpOutput = mOutputs.getA2dpOutput();
Aniket Kumar Lataa8ee9962018-01-31 20:24:23 -08007125 if (a2dpOutput == 0 || mOutputs.isA2dpOffloadedOnPrimary()) {
Eric Laurent3a4311c2014-03-17 12:00:47 -07007126 mA2dpSuspended = false;
Eric Laurente552edb2014-03-10 17:42:56 -07007127 return;
7128 }
7129
Eric Laurent3a4311c2014-03-17 12:00:47 -07007130 bool isScoConnected =
jiabin9a3361e2019-10-01 09:38:30 -07007131 (mAvailableInputDevices.types().count(AUDIO_DEVICE_IN_BLUETOOTH_SCO_HEADSET) != 0 ||
7132 !Intersection(mAvailableOutputDevices.types(), getAudioDeviceOutAllScoSet()).empty());
Eric Laurent2517af32020-11-25 15:31:27 +01007133 bool isScoRequested = isScoRequestedForComm();
Eric Laurentf732e072016-08-03 19:30:28 -07007134
7135 // if suspended, restore A2DP output if:
7136 // ((SCO device is NOT connected) ||
Eric Laurent2517af32020-11-25 15:31:27 +01007137 // ((SCO is not requested) &&
Eric Laurentf732e072016-08-03 19:30:28 -07007138 // (phone state is NOT in call) && (phone state is NOT ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007139 //
Eric Laurentf732e072016-08-03 19:30:28 -07007140 // if not suspended, suspend A2DP output if:
7141 // (SCO device is connected) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007142 // ((SCO is requested) ||
Eric Laurentf732e072016-08-03 19:30:28 -07007143 // ((phone state is in call) || (phone state is ringing)))
Eric Laurente552edb2014-03-10 17:42:56 -07007144 //
7145 if (mA2dpSuspended) {
Eric Laurentf732e072016-08-03 19:30:28 -07007146 if (!isScoConnected ||
Eric Laurent2517af32020-11-25 15:31:27 +01007147 (!isScoRequested &&
Eric Laurentf732e072016-08-03 19:30:28 -07007148 (mEngine->getPhoneState() != AUDIO_MODE_IN_CALL) &&
François Gaffie2110e042015-03-24 08:41:51 +01007149 (mEngine->getPhoneState() != AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007150
7151 mpClientInterface->restoreOutput(a2dpOutput);
7152 mA2dpSuspended = false;
7153 }
7154 } else {
Eric Laurentf732e072016-08-03 19:30:28 -07007155 if (isScoConnected &&
Eric Laurent2517af32020-11-25 15:31:27 +01007156 (isScoRequested ||
Eric Laurentf732e072016-08-03 19:30:28 -07007157 (mEngine->getPhoneState() == AUDIO_MODE_IN_CALL) ||
François Gaffie2110e042015-03-24 08:41:51 +01007158 (mEngine->getPhoneState() == AUDIO_MODE_RINGTONE))) {
Eric Laurente552edb2014-03-10 17:42:56 -07007159
7160 mpClientInterface->suspendOutput(a2dpOutput);
7161 mA2dpSuspended = true;
7162 }
7163 }
7164}
7165
François Gaffie11d30102018-11-02 16:09:09 +01007166DeviceVector AudioPolicyManager::getNewOutputDevices(const sp<SwAudioOutputDescriptor>& outputDesc,
7167 bool fromCache)
Eric Laurente552edb2014-03-10 17:42:56 -07007168{
François Gaffiedb1755b2023-09-01 11:50:35 +02007169 if (outputDesc == nullptr) {
7170 return DeviceVector{};
7171 }
François Gaffie11d30102018-11-02 16:09:09 +01007172
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007173 ssize_t index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007174 if (index >= 0) {
7175 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007176 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007177 ALOGV("%s device %s forced by patch %d", __func__,
7178 outputDesc->devices().toString().c_str(), outputDesc->getPatchHandle());
7179 return outputDesc->devices();
Eric Laurent6a94d692014-05-20 11:18:06 -07007180 }
7181 }
7182
Dean Wheatley514b4312020-06-17 21:45:00 +10007183 // Do not retrieve engine device for outputs through MSD
7184 // TODO: support explicit routing requests by resetting MSD patch to engine device.
7185 if (outputDesc->devices() == getMsdAudioOutDevices()) {
7186 return outputDesc->devices();
7187 }
7188
Eric Laurent97ac8712018-07-27 18:59:02 -07007189 // Honor explicit routing requests only if no client using default routing is active on this
7190 // input: a specific app can not force routing for other apps by setting a preferred device.
7191 bool active; // unused
François Gaffie11d30102018-11-02 16:09:09 +01007192 sp<DeviceDescriptor> device =
François Gaffiec005e562018-11-06 15:04:49 +01007193 findPreferredDevice(outputDesc, PRODUCT_STRATEGY_NONE, active, mAvailableOutputDevices);
François Gaffie11d30102018-11-02 16:09:09 +01007194 if (device != nullptr) {
7195 return DeviceVector(device);
Eric Laurentf3a5a602018-05-22 18:42:55 -07007196 }
7197
François Gaffiea807ef92018-11-05 10:44:33 +01007198 // Legacy Engine cannot take care of bus devices and mix, so we need to handle the conflict
7199 // of setForceUse / Default Bus device here
7200 device = mPolicyMixes.getDeviceAndMixForOutput(outputDesc, mAvailableOutputDevices);
7201 if (device != nullptr) {
7202 return DeviceVector(device);
7203 }
7204
François Gaffiedb1755b2023-09-01 11:50:35 +02007205 DeviceVector devices;
François Gaffiec005e562018-11-06 15:04:49 +01007206 for (const auto &productStrategy : mEngine->getOrderedProductStrategies()) {
7207 StreamTypeVector streams = mEngine->getStreamTypesForProductStrategy(productStrategy);
7208 auto attr = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307209 auto hasStreamActive = [&](auto stream) {
7210 return hasStream(streams, stream) && isStreamActive(stream, 0);
7211 };
Eric Laurent484e9272018-06-07 17:29:23 -07007212
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307213 auto doGetOutputDevicesForVoice = [&]() {
7214 return hasVoiceStream(streams) && (outputDesc == mPrimaryOutput ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007215 outputDesc->isActive(toVolumeSource(AUDIO_STREAM_VOICE_CALL, false))) &&
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307216 (isInCall() ||
Henrik Backlund07c654a2021-10-14 15:57:10 +02007217 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc)) &&
7218 !isStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE, 0);
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307219 };
7220
7221 // With low-latency playing on speaker, music on WFD, when the first low-latency
7222 // output is stopped, getNewOutputDevices checks for a product strategy
7223 // from the list, as STRATEGY_SONIFICATION comes prior to STRATEGY_MEDIA.
Carter Hsucc58a6b2021-07-20 08:44:50 +00007224 // If an ALARM or ENFORCED_AUDIBLE stream is supported by the product strategy,
Jaideep Sharmae4d123a2020-11-24 15:14:03 +05307225 // devices are returned for STRATEGY_SONIFICATION without checking whether the
7226 // stream is associated to the output descriptor.
7227 if (doGetOutputDevicesForVoice() || outputDesc->isStrategyActive(productStrategy) ||
7228 ((hasStreamActive(AUDIO_STREAM_ALARM) ||
7229 hasStreamActive(AUDIO_STREAM_ENFORCED_AUDIBLE)) &&
7230 mOutputs.isStrategyActiveOnSameModule(productStrategy, outputDesc))) {
François Gaffiec005e562018-11-06 15:04:49 +01007231 // Retrieval of devices for voice DL is done on primary output profile, cannot
7232 // check the route (would force modifying configuration file for this profile)
7233 devices = mEngine->getOutputDevicesForAttributes(attr, nullptr, fromCache);
7234 break;
7235 }
Eric Laurente552edb2014-03-10 17:42:56 -07007236 }
François Gaffiec005e562018-11-06 15:04:49 +01007237 ALOGV("%s selected devices %s", __func__, devices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007238 return devices;
Eric Laurent1c333e22014-05-20 10:48:17 -07007239}
7240
François Gaffie11d30102018-11-02 16:09:09 +01007241sp<DeviceDescriptor> AudioPolicyManager::getNewInputDevice(
7242 const sp<AudioInputDescriptor>& inputDesc)
Eric Laurent1c333e22014-05-20 10:48:17 -07007243{
François Gaffie11d30102018-11-02 16:09:09 +01007244 sp<DeviceDescriptor> device;
Eric Laurent6a94d692014-05-20 11:18:06 -07007245
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007246 ssize_t index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007247 if (index >= 0) {
7248 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007249 if (patchDesc->getUid() != mUidCached) {
François Gaffie11d30102018-11-02 16:09:09 +01007250 ALOGV("getNewInputDevice() device %s forced by patch %d",
7251 inputDesc->getDevice()->toString().c_str(), inputDesc->getPatchHandle());
7252 return inputDesc->getDevice();
Eric Laurent6a94d692014-05-20 11:18:06 -07007253 }
7254 }
7255
Eric Laurent97ac8712018-07-27 18:59:02 -07007256 // Honor explicit routing requests only if no client using default routing is active on this
7257 // input: a specific app can not force routing for other apps by setting a preferred device.
7258 bool active;
François Gaffie11d30102018-11-02 16:09:09 +01007259 device = findPreferredDevice(inputDesc, AUDIO_SOURCE_DEFAULT, active, mAvailableInputDevices);
7260 if (device != nullptr) {
7261 return device;
Eric Laurent97ac8712018-07-27 18:59:02 -07007262 }
7263
Eric Laurentdc95a252018-04-12 12:46:56 -07007264 // If we are not in call and no client is active on this input, this methods returns
Andy Hungf024a9e2019-01-30 16:01:02 -08007265 // a null sp<>, causing the patch on the input stream to be released.
yuanjiahsu0735bf32021-03-18 08:12:54 +08007266 audio_attributes_t attributes;
7267 uid_t uid;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007268 audio_session_t session;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007269 sp<RecordClientDescriptor> topClient = inputDesc->getHighestPriorityClient();
7270 if (topClient != nullptr) {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007271 attributes = topClient->attributes();
7272 uid = topClient->uid();
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007273 session = topClient->session();
yuanjiahsu0735bf32021-03-18 08:12:54 +08007274 } else {
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01007275 attributes = { .source = AUDIO_SOURCE_DEFAULT };
7276 uid = 0;
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007277 session = AUDIO_SESSION_NONE;
yuanjiahsu0735bf32021-03-18 08:12:54 +08007278 }
7279
Francois Gaffie716e1432019-01-14 16:58:59 +01007280 if (attributes.source == AUDIO_SOURCE_DEFAULT && isInCall()) {
7281 attributes.source = AUDIO_SOURCE_VOICE_COMMUNICATION;
Eric Laurentdc95a252018-04-12 12:46:56 -07007282 }
Francois Gaffie716e1432019-01-14 16:58:59 +01007283 if (attributes.source != AUDIO_SOURCE_DEFAULT) {
Jan Sebechlebsky1a80c062022-08-09 15:21:18 +02007284 device = mEngine->getInputDeviceForAttributes(attributes, uid, session);
Eric Laurentfb66dd92016-01-28 18:32:03 -08007285 }
Eric Laurent1c333e22014-05-20 10:48:17 -07007286
Eric Laurente552edb2014-03-10 17:42:56 -07007287 return device;
7288}
7289
Eric Laurent794fde22016-03-11 09:50:45 -08007290bool AudioPolicyManager::streamsMatchForvolume(audio_stream_type_t stream1,
7291 audio_stream_type_t stream2) {
Jean-Michel Trivi99bb2f92016-11-23 15:52:07 -08007292 return (stream1 == stream2);
Eric Laurent28d09f02016-03-08 10:43:05 -08007293}
7294
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007295status_t AudioPolicyManager::getDevicesForAttributes(
Andy Hung6d23c0f2022-02-16 09:37:15 -08007296 const audio_attributes_t &attr, AudioDeviceTypeAddrVector *devices, bool forVolume) {
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007297 if (devices == nullptr) {
7298 return BAD_VALUE;
7299 }
Andy Hung6d23c0f2022-02-16 09:37:15 -08007300
Andy Hung6d23c0f2022-02-16 09:37:15 -08007301 DeviceVector curDevices;
jiabinf1c73972022-04-14 16:28:52 -07007302 if (status_t status = getDevicesForAttributes(attr, curDevices, forVolume); status != OK) {
7303 return status;
Andy Hung6d23c0f2022-02-16 09:37:15 -08007304 }
Jean-Michel Trivif41599b2020-01-07 14:22:08 -08007305 for (const auto& device : curDevices) {
7306 devices->push_back(device->getDeviceTypeAddr());
7307 }
7308 return NO_ERROR;
7309}
7310
Eric Laurente0720872014-03-11 09:30:41 -07007311void AudioPolicyManager::handleNotificationRoutingForStream(audio_stream_type_t stream) {
Eric Laurente552edb2014-03-10 17:42:56 -07007312 switch(stream) {
Eric Laurent3b73df72014-03-11 09:06:29 -07007313 case AUDIO_STREAM_MUSIC:
François Gaffiec005e562018-11-06 15:04:49 +01007314 checkOutputForAttributes(attributes_initializer(AUDIO_USAGE_NOTIFICATION));
Eric Laurente552edb2014-03-10 17:42:56 -07007315 updateDevicesAndOutputs();
7316 break;
7317 default:
7318 break;
7319 }
7320}
7321
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007322uint32_t AudioPolicyManager::handleEventForBeacon(int event) {
Eric Laurent9459fb02015-08-12 18:36:32 -07007323
7324 // skip beacon mute management if a dedicated TTS output is available
7325 if (mTtsOutputAvailable) {
7326 return 0;
7327 }
7328
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007329 switch(event) {
7330 case STARTING_OUTPUT:
7331 mBeaconMuteRefCount++;
7332 break;
7333 case STOPPING_OUTPUT:
7334 if (mBeaconMuteRefCount > 0) {
7335 mBeaconMuteRefCount--;
7336 }
7337 break;
7338 case STARTING_BEACON:
7339 mBeaconPlayingRefCount++;
7340 break;
7341 case STOPPING_BEACON:
7342 if (mBeaconPlayingRefCount > 0) {
7343 mBeaconPlayingRefCount--;
7344 }
7345 break;
7346 }
7347
7348 if (mBeaconMuteRefCount > 0) {
7349 // any playback causes beacon to be muted
7350 return setBeaconMute(true);
7351 } else {
7352 // no other playback: unmute when beacon starts playing, mute when it stops
7353 return setBeaconMute(mBeaconPlayingRefCount == 0);
7354 }
7355}
7356
7357uint32_t AudioPolicyManager::setBeaconMute(bool mute) {
7358 ALOGV("setBeaconMute(%d) mBeaconMuteRefCount=%d mBeaconPlayingRefCount=%d",
7359 mute, mBeaconMuteRefCount, mBeaconPlayingRefCount);
7360 // keep track of muted state to avoid repeating mute/unmute operations
7361 if (mBeaconMuted != mute) {
7362 // mute/unmute AUDIO_STREAM_TTS on all outputs
7363 ALOGV("\t muting %d", mute);
7364 uint32_t maxLatency = 0;
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007365 auto ttsVolumeSource = toVolumeSource(AUDIO_STREAM_TTS, false);
7366 if (ttsVolumeSource == VOLUME_SOURCE_NONE) {
7367 ALOGV("\t no tts volume source available");
7368 return 0;
7369 }
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007370 for (size_t i = 0; i < mOutputs.size(); i++) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007371 sp<SwAudioOutputDescriptor> desc = mOutputs.valueAt(i);
jiabin9a3361e2019-10-01 09:38:30 -07007372 setVolumeSourceMute(ttsVolumeSource, mute/*on*/, desc, 0 /*delay*/, DeviceTypeSet());
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007373 const uint32_t latency = desc->latency() * 2;
Eric Laurentcdb2b352020-07-23 10:57:02 -07007374 if (desc->isActive(latency * 2) && latency > maxLatency) {
Jean-Michel Trivid9cfeb42014-09-22 16:51:34 -07007375 maxLatency = latency;
7376 }
7377 }
7378 mBeaconMuted = mute;
7379 return maxLatency;
7380 }
7381 return 0;
7382}
7383
Eric Laurente0720872014-03-11 09:30:41 -07007384void AudioPolicyManager::updateDevicesAndOutputs()
Eric Laurente552edb2014-03-10 17:42:56 -07007385{
François Gaffiec005e562018-11-06 15:04:49 +01007386 mEngine->updateDeviceSelectionCache();
Eric Laurente552edb2014-03-10 17:42:56 -07007387 mPreviousOutputs = mOutputs;
7388}
7389
Chih-Hung Hsiehe964d4e2016-08-09 14:31:32 -07007390uint32_t AudioPolicyManager::checkDeviceMuteStrategies(const sp<AudioOutputDescriptor>& outputDesc,
François Gaffiec005e562018-11-06 15:04:49 +01007391 const DeviceVector &prevDevices,
Eric Laurente552edb2014-03-10 17:42:56 -07007392 uint32_t delayMs)
7393{
7394 // mute/unmute strategies using an incompatible device combination
7395 // if muting, wait for the audio in pcm buffer to be drained before proceeding
7396 // if unmuting, unmute only after the specified delay
7397 if (outputDesc->isDuplicated()) {
7398 return 0;
7399 }
7400
7401 uint32_t muteWaitMs = 0;
François Gaffiec005e562018-11-06 15:04:49 +01007402 DeviceVector devices = outputDesc->devices();
7403 bool shouldMute = outputDesc->isActive() && (devices.size() >= 2);
Eric Laurente552edb2014-03-10 17:42:56 -07007404
François Gaffiec005e562018-11-06 15:04:49 +01007405 auto productStrategies = mEngine->getOrderedProductStrategies();
7406 for (const auto &productStrategy : productStrategies) {
7407 auto attributes = mEngine->getAllAttributesForProductStrategy(productStrategy).front();
7408 DeviceVector curDevices =
7409 mEngine->getOutputDevicesForAttributes(attributes, nullptr, false/*fromCache*/);
7410 curDevices = curDevices.filter(outputDesc->supportedDevices());
7411 bool mute = shouldMute && curDevices.containsAtLeastOne(devices) && curDevices != devices;
Eric Laurente552edb2014-03-10 17:42:56 -07007412 bool doMute = false;
7413
François Gaffiec005e562018-11-06 15:04:49 +01007414 if (mute && !outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007415 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007416 outputDesc->setStrategyMutedByDevice(productStrategy, true);
7417 } else if (!mute && outputDesc->isStrategyMutedByDevice(productStrategy)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007418 doMute = true;
François Gaffiec005e562018-11-06 15:04:49 +01007419 outputDesc->setStrategyMutedByDevice(productStrategy, false);
Eric Laurente552edb2014-03-10 17:42:56 -07007420 }
Eric Laurent99401132014-05-07 19:48:15 -07007421 if (doMute) {
Eric Laurente552edb2014-03-10 17:42:56 -07007422 for (size_t j = 0; j < mOutputs.size(); j++) {
Eric Laurent1f2f2232014-06-02 12:01:23 -07007423 sp<AudioOutputDescriptor> desc = mOutputs.valueAt(j);
Eric Laurente552edb2014-03-10 17:42:56 -07007424 // skip output if it does not share any device with current output
François Gaffie11d30102018-11-02 16:09:09 +01007425 if (!desc->supportedDevices().containsAtLeastOne(outputDesc->supportedDevices())) {
Eric Laurente552edb2014-03-10 17:42:56 -07007426 continue;
7427 }
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307428 ALOGVV("%s() output %s %s (curDevice %s)", __func__, desc->info().c_str(),
François Gaffiec005e562018-11-06 15:04:49 +01007429 mute ? "muting" : "unmuting", curDevices.toString().c_str());
7430 setStrategyMute(productStrategy, mute, desc, mute ? 0 : delayMs);
7431 if (desc->isStrategyActive(productStrategy)) {
Eric Laurent99401132014-05-07 19:48:15 -07007432 if (mute) {
7433 // FIXME: should not need to double latency if volume could be applied
7434 // immediately by the audioflinger mixer. We must account for the delay
7435 // between now and the next time the audioflinger thread for this output
7436 // will process a buffer (which corresponds to one buffer size,
7437 // usually 1/2 or 1/4 of the latency).
7438 if (muteWaitMs < desc->latency() * 2) {
7439 muteWaitMs = desc->latency() * 2;
Eric Laurente552edb2014-03-10 17:42:56 -07007440 }
7441 }
7442 }
7443 }
7444 }
7445 }
7446
Eric Laurent99401132014-05-07 19:48:15 -07007447 // temporary mute output if device selection changes to avoid volume bursts due to
7448 // different per device volumes
François Gaffiec005e562018-11-06 15:04:49 +01007449 if (outputDesc->isActive() && (devices != prevDevices)) {
Eric Laurentdc462862016-07-19 12:29:53 -07007450 uint32_t tempMuteWaitMs = outputDesc->latency() * 2;
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007451
Eric Laurentdc462862016-07-19 12:29:53 -07007452 if (muteWaitMs < tempMuteWaitMs) {
7453 muteWaitMs = tempMuteWaitMs;
Eric Laurent99401132014-05-07 19:48:15 -07007454 }
Jasmine Chaf6074fe2021-08-17 13:44:31 +08007455
7456 // If recommended duration is defined, replace temporary mute duration to avoid
7457 // truncated notifications at beginning, which depends on duration of changing path in HAL.
7458 // Otherwise, temporary mute duration is conservatively set to 4 times the reported latency.
7459 uint32_t tempRecommendedMuteDuration = outputDesc->getRecommendedMuteDurationMs();
7460 uint32_t tempMuteDurationMs = tempRecommendedMuteDuration > 0 ?
7461 tempRecommendedMuteDuration : outputDesc->latency() * 4;
7462
François Gaffieaaac0fd2018-11-22 17:56:39 +01007463 for (const auto &activeVs : outputDesc->getActiveVolumeSources()) {
7464 // make sure that we do not start the temporary mute period too early in case of
7465 // delayed device change
7466 setVolumeSourceMute(activeVs, true, outputDesc, delayMs);
7467 setVolumeSourceMute(activeVs, false, outputDesc, delayMs + tempMuteDurationMs,
François Gaffiec005e562018-11-06 15:04:49 +01007468 devices.types());
Eric Laurent99401132014-05-07 19:48:15 -07007469 }
7470 }
7471
Eric Laurente552edb2014-03-10 17:42:56 -07007472 // wait for the PCM output buffers to empty before proceeding with the rest of the command
7473 if (muteWaitMs > delayMs) {
7474 muteWaitMs -= delayMs;
7475 usleep(muteWaitMs * 1000);
7476 return muteWaitMs;
7477 }
7478 return 0;
7479}
7480
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307481uint32_t AudioPolicyManager::setOutputDevices(const char *caller,
7482 const sp<SwAudioOutputDescriptor>& outputDesc,
François Gaffie11d30102018-11-02 16:09:09 +01007483 const DeviceVector &devices,
7484 bool force,
7485 int delayMs,
7486 audio_patch_handle_t *patchHandle,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007487 bool requiresMuteCheck, bool requiresVolumeCheck,
7488 bool skipMuteDelay)
Eric Laurente552edb2014-03-10 17:42:56 -07007489{
jiabin3ff8d7d2022-12-13 06:27:44 +00007490 // TODO(b/262404095): Consider if the output need to be reopened.
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307491 std::string logPrefix = std::string("caller ") + caller + outputDesc->info();
7492 ALOGV("%s %s device %s delayMs %d", __func__, logPrefix.c_str(),
7493 devices.toString().c_str(), delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07007494 uint32_t muteWaitMs;
7495
7496 if (outputDesc->isDuplicated()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307497 muteWaitMs = setOutputDevices(__func__, outputDesc->subOutput1(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007498 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307499 muteWaitMs += setOutputDevices(__func__, outputDesc->subOutput2(), devices, force, delayMs,
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007500 nullptr /* patchHandle */, requiresMuteCheck, skipMuteDelay);
Eric Laurente552edb2014-03-10 17:42:56 -07007501 return muteWaitMs;
7502 }
Eric Laurente552edb2014-03-10 17:42:56 -07007503
7504 // filter devices according to output selected
Francois Gaffie716e1432019-01-14 16:58:59 +01007505 DeviceVector filteredDevices = outputDesc->filterSupportedDevices(devices);
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01007506 DeviceVector prevDevices = outputDesc->devices();
Francois Gaffie3523ab32021-06-22 13:24:34 +02007507 DeviceVector availPrevDevices = mAvailableOutputDevices.filter(prevDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007508
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307509 ALOGV("%s %s prevDevice %s", __func__, logPrefix.c_str(),
7510 prevDevices.toString().c_str());
François Gaffie11d30102018-11-02 16:09:09 +01007511
7512 if (!filteredDevices.isEmpty()) {
7513 outputDesc->setDevices(filteredDevices);
Eric Laurente552edb2014-03-10 17:42:56 -07007514 }
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007515
7516 // if the outputs are not materially active, there is no need to mute.
7517 if (requiresMuteCheck) {
François Gaffiec005e562018-11-06 15:04:49 +01007518 muteWaitMs = checkDeviceMuteStrategies(outputDesc, prevDevices, delayMs);
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007519 } else {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307520 ALOGV("%s: %s suppressing checkDeviceMuteStrategies", __func__,
7521 logPrefix.c_str());
Jean-Michel Trivib3733cf2018-02-15 19:17:50 +00007522 muteWaitMs = 0;
7523 }
Eric Laurente552edb2014-03-10 17:42:56 -07007524
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007525 bool outputRouted = outputDesc->isRouted();
7526
Eric Laurent79ea9582020-06-11 18:49:24 -07007527 // no need to proceed if new device is not AUDIO_DEVICE_NONE and not supported by current
7528 // output profile or if new device is not supported AND previous device(s) is(are) still
7529 // available (otherwise reset device must be done on the output)
Francois Gaffie3523ab32021-06-22 13:24:34 +02007530 if (!devices.isEmpty() && filteredDevices.isEmpty() && !availPrevDevices.empty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307531 ALOGV("%s: %s unsupported device %s for output", __func__, logPrefix.c_str(),
7532 devices.toString().c_str());
Eric Laurent79ea9582020-06-11 18:49:24 -07007533 // restore previous device after evaluating strategy mute state
7534 outputDesc->setDevices(prevDevices);
7535 return muteWaitMs;
7536 }
7537
Eric Laurente552edb2014-03-10 17:42:56 -07007538 // Do not change the routing if:
Eric Laurentb80a2a82014-10-27 16:07:59 -07007539 // the requested device is AUDIO_DEVICE_NONE
7540 // OR the requested device is the same as current device
7541 // AND force is not specified
7542 // AND the output is connected by a valid audio patch.
François Gaffie11d30102018-11-02 16:09:09 +01007543 // Doing this check here allows the caller to call setOutputDevices() without conditions
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007544 if ((filteredDevices.isEmpty() || filteredDevices == prevDevices) && !force && outputRouted) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307545 ALOGV("%s %s setting same device %s or null device, force=%d, patch handle=%d",
7546 __func__, logPrefix.c_str(), filteredDevices.toString().c_str(), force,
7547 outputDesc->getPatchHandle());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007548 if (requiresVolumeCheck && !filteredDevices.isEmpty()) {
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307549 ALOGV("%s %s setting same device on routed output, force apply volumes",
7550 __func__, logPrefix.c_str());
Francois Gaffie3523ab32021-06-22 13:24:34 +02007551 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs, true /*force*/);
7552 }
Eric Laurente552edb2014-03-10 17:42:56 -07007553 return muteWaitMs;
7554 }
7555
Jaideep Sharma4b5c4252023-07-27 14:47:32 +05307556 ALOGV("%s %s changing device to %s", __func__, logPrefix.c_str(),
7557 filteredDevices.toString().c_str());
Eric Laurent1c333e22014-05-20 10:48:17 -07007558
Eric Laurente552edb2014-03-10 17:42:56 -07007559 // do the routing
Francois Gaffie3523ab32021-06-22 13:24:34 +02007560 if (filteredDevices.isEmpty() || mAvailableOutputDevices.filter(filteredDevices).empty()) {
Eric Laurentc75307b2015-03-17 15:29:32 -07007561 resetOutputDevice(outputDesc, delayMs, NULL);
Eric Laurent1c333e22014-05-20 10:48:17 -07007562 } else {
François Gaffie11d30102018-11-02 16:09:09 +01007563 PatchBuilder patchBuilder;
7564 patchBuilder.addSource(outputDesc);
7565 ALOG_ASSERT(filteredDevices.size() <= AUDIO_PATCH_PORTS_MAX, "Too many sink ports");
7566 for (const auto &filteredDevice : filteredDevices) {
7567 patchBuilder.addSink(filteredDevice);
Eric Laurentc40d9692016-04-13 19:14:13 -07007568 }
7569
Jasmine Cha7f82d1a2020-03-16 13:21:47 +08007570 // Add half reported latency to delayMs when muteWaitMs is null in order
7571 // to avoid disordered sequence of muting volume and changing devices.
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007572 int actualDelayMs = !skipMuteDelay && muteWaitMs == 0
7573 ? (delayMs + (outputDesc->latency() / 2)) : delayMs;
7574 installPatch(__func__, patchHandle, outputDesc.get(), patchBuilder.patch(), actualDelayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007575 }
Eric Laurente552edb2014-03-10 17:42:56 -07007576
Oscar Azucena6acf34b2023-04-27 16:32:09 -07007577 // Since the mute is skip, also skip the apply stream volume as that will be applied externally
7578 if (!skipMuteDelay) {
7579 // update stream volumes according to new device
7580 applyStreamVolumes(outputDesc, filteredDevices.types(), delayMs);
7581 }
Eric Laurente552edb2014-03-10 17:42:56 -07007582
7583 return muteWaitMs;
7584}
7585
Eric Laurentc75307b2015-03-17 15:29:32 -07007586status_t AudioPolicyManager::resetOutputDevice(const sp<AudioOutputDescriptor>& outputDesc,
Eric Laurent6a94d692014-05-20 11:18:06 -07007587 int delayMs,
7588 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007589{
Eric Laurent6a94d692014-05-20 11:18:06 -07007590 ssize_t index;
Francois Gaffieb2e5cb52021-06-22 13:16:09 +02007591 if (patchHandle == nullptr && !outputDesc->isRouted()) {
7592 return INVALID_OPERATION;
7593 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007594 if (patchHandle) {
7595 index = mAudioPatches.indexOfKey(*patchHandle);
7596 } else {
Jean-Michel Triviff155c62016-02-26 12:07:16 -08007597 index = mAudioPatches.indexOfKey(outputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007598 }
7599 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007600 return INVALID_OPERATION;
7601 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007602 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007603 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), delayMs);
Eric Laurent1c333e22014-05-20 10:48:17 -07007604 ALOGV("resetOutputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007605 outputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007606 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007607 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007608 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007609 return status;
7610}
7611
7612status_t AudioPolicyManager::setInputDevice(audio_io_handle_t input,
François Gaffie11d30102018-11-02 16:09:09 +01007613 const sp<DeviceDescriptor> &device,
Eric Laurent6a94d692014-05-20 11:18:06 -07007614 bool force,
7615 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007616{
7617 status_t status = NO_ERROR;
7618
Eric Laurent1f2f2232014-06-02 12:01:23 -07007619 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
François Gaffie11d30102018-11-02 16:09:09 +01007620 if ((device != nullptr) && ((device != inputDesc->getDevice()) || force)) {
7621 inputDesc->setDevice(device);
Eric Laurent1c333e22014-05-20 10:48:17 -07007622
François Gaffie11d30102018-11-02 16:09:09 +01007623 if (mAvailableInputDevices.contains(device)) {
Mikhail Naganovdc769682018-05-04 15:34:08 -07007624 PatchBuilder patchBuilder;
7625 patchBuilder.addSink(inputDesc,
Eric Laurentdaf92cc2014-07-22 15:36:10 -07007626 // AUDIO_SOURCE_HOTWORD is for internal use only:
7627 // handled as AUDIO_SOURCE_VOICE_RECOGNITION by the audio HAL
Mikhail Naganovdc769682018-05-04 15:34:08 -07007628 [inputDesc](const PatchBuilder::mix_usecase_t& usecase) {
7629 auto result = usecase;
7630 if (result.source == AUDIO_SOURCE_HOTWORD && !inputDesc->isSoundTrigger()) {
7631 result.source = AUDIO_SOURCE_VOICE_RECOGNITION;
7632 }
7633 return result; }).
Eric Laurent1c333e22014-05-20 10:48:17 -07007634 //only one input device for now
François Gaffie11d30102018-11-02 16:09:09 +01007635 addSource(device);
Mikhail Naganovdc769682018-05-04 15:34:08 -07007636 status = installPatch(__func__, patchHandle, inputDesc.get(), patchBuilder.patch(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007637 }
7638 }
7639 return status;
7640}
7641
Eric Laurent6a94d692014-05-20 11:18:06 -07007642status_t AudioPolicyManager::resetInputDevice(audio_io_handle_t input,
7643 audio_patch_handle_t *patchHandle)
Eric Laurent1c333e22014-05-20 10:48:17 -07007644{
Eric Laurent1f2f2232014-06-02 12:01:23 -07007645 sp<AudioInputDescriptor> inputDesc = mInputs.valueFor(input);
Eric Laurent6a94d692014-05-20 11:18:06 -07007646 ssize_t index;
7647 if (patchHandle) {
7648 index = mAudioPatches.indexOfKey(*patchHandle);
7649 } else {
Jean-Michel Trivi8c7cf3b2016-02-25 17:08:24 -08007650 index = mAudioPatches.indexOfKey(inputDesc->getPatchHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007651 }
7652 if (index < 0) {
Eric Laurent1c333e22014-05-20 10:48:17 -07007653 return INVALID_OPERATION;
7654 }
Eric Laurent6a94d692014-05-20 11:18:06 -07007655 sp< AudioPatch> patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01007656 status_t status = mpClientInterface->releaseAudioPatch(patchDesc->getAfHandle(), 0);
Eric Laurent1c333e22014-05-20 10:48:17 -07007657 ALOGV("resetInputDevice() releaseAudioPatch returned %d", status);
Glenn Kastena13cde92016-03-28 15:26:02 -07007658 inputDesc->setPatchHandle(AUDIO_PATCH_HANDLE_NONE);
François Gaffieafd4cea2019-11-18 15:50:22 +01007659 removeAudioPatch(patchDesc->getHandle());
Eric Laurent6a94d692014-05-20 11:18:06 -07007660 nextAudioPortGeneration();
Eric Laurentb52c1522014-05-20 11:27:36 -07007661 mpClientInterface->onAudioPatchListUpdate();
Eric Laurent1c333e22014-05-20 10:48:17 -07007662 return status;
7663}
7664
François Gaffie11d30102018-11-02 16:09:09 +01007665sp<IOProfile> AudioPolicyManager::getInputProfile(const sp<DeviceDescriptor> &device,
François Gaffie53615e22015-03-19 09:24:12 +01007666 uint32_t& samplingRate,
Andy Hungf129b032015-04-07 13:45:50 -07007667 audio_format_t& format,
7668 audio_channel_mask_t& channelMask,
François Gaffie53615e22015-03-19 09:24:12 +01007669 audio_input_flags_t flags)
Eric Laurente552edb2014-03-10 17:42:56 -07007670{
7671 // Choose an input profile based on the requested capture parameters: select the first available
7672 // profile supporting all requested parameters.
jiabin2fd710d2022-05-02 23:20:22 +00007673 // The flags can be ignored if it doesn't contain a much match flag.
Andy Hungf129b032015-04-07 13:45:50 -07007674 //
7675 // TODO: perhaps isCompatibleProfile should return a "matching" score so we can return
7676 // the best matching profile, not the first one.
Eric Laurente552edb2014-03-10 17:42:56 -07007677
Atneya Nair0f0a8032022-12-12 16:20:12 -08007678 using underlying_input_flag_t = std::underlying_type_t<audio_input_flags_t>;
7679 const underlying_input_flag_t mustMatchFlag = AUDIO_INPUT_FLAG_MMAP_NOIRQ |
7680 AUDIO_INPUT_FLAG_HOTWORD_TAP | AUDIO_INPUT_FLAG_HW_LOOKBACK;
7681
7682 const underlying_input_flag_t oriFlags = flags;
Glenn Kasten730b9262018-03-29 15:01:26 -07007683
jiabin2fd710d2022-05-02 23:20:22 +00007684 for (;;) {
7685 sp<IOProfile> firstInexact = nullptr;
7686 uint32_t updatedSamplingRate = 0;
7687 audio_format_t updatedFormat = AUDIO_FORMAT_INVALID;
7688 audio_channel_mask_t updatedChannelMask = AUDIO_CHANNEL_INVALID;
7689 for (const auto& hwModule : mHwModules) {
7690 for (const auto& profile : hwModule->getInputProfiles()) {
7691 // profile->log();
7692 //updatedFormat = format;
7693 if (profile->isCompatibleProfile(DeviceVector(device), samplingRate,
7694 &samplingRate /*updatedSamplingRate*/,
7695 format,
7696 &format, /*updatedFormat*/
7697 channelMask,
7698 &channelMask /*updatedChannelMask*/,
7699 // FIXME ugly cast
7700 (audio_output_flags_t) flags,
7701 true /*exactMatchRequiredForInputFlags*/)) {
7702 return profile;
7703 }
7704 if (firstInexact == nullptr && profile->isCompatibleProfile(DeviceVector(device),
7705 samplingRate,
7706 &updatedSamplingRate,
7707 format,
7708 &updatedFormat,
7709 channelMask,
7710 &updatedChannelMask,
7711 // FIXME ugly cast
7712 (audio_output_flags_t) flags,
7713 false /*exactMatchRequiredForInputFlags*/)) {
7714 firstInexact = profile;
7715 }
7716 }
7717 }
7718
7719 if (firstInexact != nullptr) {
7720 samplingRate = updatedSamplingRate;
7721 format = updatedFormat;
7722 channelMask = updatedChannelMask;
7723 return firstInexact;
7724 } else if (flags & AUDIO_INPUT_FLAG_RAW) {
7725 flags = (audio_input_flags_t) (flags & ~AUDIO_INPUT_FLAG_RAW); // retry
7726 } else if ((flags & mustMatchFlag) == AUDIO_INPUT_FLAG_NONE &&
7727 flags != AUDIO_INPUT_FLAG_NONE && audio_is_linear_pcm(format)) {
7728 flags = AUDIO_INPUT_FLAG_NONE;
7729 } else { // fail
7730 ALOGW("%s could not find profile for device %s, sampling rate %u, format %#x, "
7731 "channel mask 0x%X, flags %#x", __func__, device->toString().c_str(),
7732 samplingRate, format, channelMask, oriFlags);
7733 break;
Eric Laurente552edb2014-03-10 17:42:56 -07007734 }
7735 }
jiabin2fd710d2022-05-02 23:20:22 +00007736
7737 return nullptr;
Eric Laurente552edb2014-03-10 17:42:56 -07007738}
7739
François Gaffieaaac0fd2018-11-22 17:56:39 +01007740float AudioPolicyManager::computeVolume(IVolumeCurves &curves,
7741 VolumeSource volumeSource,
François Gaffied1ab2bd2015-12-02 18:20:06 +01007742 int index,
jiabin9a3361e2019-10-01 09:38:30 -07007743 const DeviceTypeSet& deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007744{
jiabin9a3361e2019-10-01 09:38:30 -07007745 float volumeDb = curves.volIndexToDb(Volume::getDeviceCategory(deviceTypes), index);
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007746
7747 // handle the case of accessibility active while a ringtone is playing: if the ringtone is much
7748 // louder than the accessibility prompt, the prompt cannot be heard, thus masking the touch
7749 // exploration of the dialer UI. In this situation, bring the accessibility volume closer to
7750 // the ringtone volume
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007751 const auto callVolumeSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7752 const auto ringVolumeSrc = toVolumeSource(AUDIO_STREAM_RING, false);
7753 const auto musicVolumeSrc = toVolumeSource(AUDIO_STREAM_MUSIC, false);
7754 const auto alarmVolumeSrc = toVolumeSource(AUDIO_STREAM_ALARM, false);
7755 const auto a11yVolumeSrc = toVolumeSource(AUDIO_STREAM_ACCESSIBILITY, false);
Oscar Azucena437ded52023-08-30 18:45:18 -07007756 // Verify that the current volume source is not the ringer volume to prevent recursively
7757 // calling to compute volume. This could happen in cases where a11y and ringer sounds belong
7758 // to the same volume group.
7759 if (volumeSource != ringVolumeSrc && volumeSource == a11yVolumeSrc
François Gaffieaaac0fd2018-11-22 17:56:39 +01007760 && (AUDIO_MODE_RINGTONE == mEngine->getPhoneState()) &&
7761 mOutputs.isActive(ringVolumeSrc, 0)) {
7762 auto &ringCurves = getVolumeCurves(AUDIO_STREAM_RING);
jiabin9a3361e2019-10-01 09:38:30 -07007763 const float ringVolumeDb = computeVolume(ringCurves, ringVolumeSrc, index, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007764 return ringVolumeDb - 4 > volumeDb ? ringVolumeDb - 4 : volumeDb;
Jean-Michel Trivi3d8b4a42016-09-14 18:37:46 -07007765 }
7766
Eric Laurentdcd4ab12018-06-29 17:45:13 -07007767 // in-call: always cap volume by voice volume + some low headroom
François Gaffieaaac0fd2018-11-22 17:56:39 +01007768 if ((volumeSource != callVolumeSrc && (isInCall() ||
7769 mOutputs.isActiveLocally(callVolumeSrc))) &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007770 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007771 volumeSource == ringVolumeSrc || volumeSource == musicVolumeSrc ||
7772 volumeSource == alarmVolumeSrc ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007773 volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false) ||
7774 volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
7775 volumeSource == toVolumeSource(AUDIO_STREAM_DTMF, false) ||
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007776 volumeSource == a11yVolumeSrc)) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007777 auto &voiceCurves = getVolumeCurves(callVolumeSrc);
jiabin9a3361e2019-10-01 09:38:30 -07007778 int voiceVolumeIndex = voiceCurves.getVolumeIndex(deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007779 const float maxVoiceVolDb =
jiabin9a3361e2019-10-01 09:38:30 -07007780 computeVolume(voiceCurves, callVolumeSrc, voiceVolumeIndex, deviceTypes)
Eric Laurent7731b5a2018-04-06 15:47:22 -07007781 + IN_CALL_EARPIECE_HEADROOM_DB;
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007782 // FIXME: Workaround for call screening applications until a proper audio mode is defined
7783 // to support this scenario : Exempt the RING stream from the audio cap if the audio was
7784 // programmatically muted.
7785 // VOICE_CALL stream has minVolumeIndex > 0 : Users cannot set the volume of voice calls to
7786 // 0. We don't want to cap volume when the system has programmatically muted the voice call
7787 // stream. See setVolumeCurveIndex() for more information.
Jean-Michel Trivi441ed652019-07-11 14:55:16 -07007788 bool exemptFromCapping =
7789 ((volumeSource == ringVolumeSrc) || (volumeSource == a11yVolumeSrc))
7790 && (voiceVolumeIndex == 0);
Abhijith Shastry329ddab2019-04-23 11:53:26 -07007791 ALOGV_IF(exemptFromCapping, "%s volume source %d at vol=%f not capped", __func__,
7792 volumeSource, volumeDb);
7793 if ((volumeDb > maxVoiceVolDb) && !exemptFromCapping) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007794 ALOGV("%s volume source %d at vol=%f overriden by volume group %d at vol=%f", __func__,
7795 volumeSource, volumeDb, callVolumeSrc, maxVoiceVolDb);
7796 volumeDb = maxVoiceVolDb;
Jean-Michel Trivi719a9872017-08-05 13:51:35 -07007797 }
7798 }
Eric Laurente552edb2014-03-10 17:42:56 -07007799 // if a headset is connected, apply the following rules to ring tones and notifications
7800 // to avoid sound level bursts in user's ears:
Eric Laurent6af1c1d2016-04-14 11:20:44 -07007801 // - always attenuate notifications volume by 6dB
7802 // - attenuate ring tones volume by 6dB unless music is not playing and
7803 // speaker is part of the select devices
Eric Laurente552edb2014-03-10 17:42:56 -07007804 // - if music is playing, always limit the volume to current music volume,
7805 // with a minimum threshold at -36dB so that notification is always perceived.
jiabin9a3361e2019-10-01 09:38:30 -07007806 if (!Intersection(deviceTypes,
7807 {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP, AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES,
7808 AUDIO_DEVICE_OUT_WIRED_HEADSET, AUDIO_DEVICE_OUT_WIRED_HEADPHONE,
Eric Laurentc42df452020-08-07 10:51:53 -07007809 AUDIO_DEVICE_OUT_USB_HEADSET, AUDIO_DEVICE_OUT_HEARING_AID,
7810 AUDIO_DEVICE_OUT_BLE_HEADSET}).empty() &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007811 ((volumeSource == alarmVolumeSrc ||
7812 volumeSource == ringVolumeSrc) ||
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007813 (volumeSource == toVolumeSource(AUDIO_STREAM_NOTIFICATION, false)) ||
7814 (volumeSource == toVolumeSource(AUDIO_STREAM_SYSTEM, false)) ||
7815 ((volumeSource == toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false)) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007816 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) == AUDIO_POLICY_FORCE_NONE))) &&
7817 curves.canBeMuted()) {
7818
Eric Laurente552edb2014-03-10 17:42:56 -07007819 // when the phone is ringing we must consider that music could have been paused just before
7820 // by the music application and behave as if music was active if the last music track was
7821 // just stopped
Oscar Azucena437ded52023-08-30 18:45:18 -07007822 // Verify that the current volume source is not the music volume to prevent recursively
7823 // calling to compute volume. This could happen in cases where music and
7824 // (alarm, ring, notification, system, etc.) sounds belong to the same volume group.
7825 if (volumeSource != musicVolumeSrc &&
7826 (isStreamActive(AUDIO_STREAM_MUSIC, SONIFICATION_HEADSET_MUSIC_DELAY)
7827 || mLimitRingtoneVolume)) {
François Gaffie43c73442018-11-08 08:21:55 +01007828 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
jiabin9a3361e2019-10-01 09:38:30 -07007829 DeviceTypeSet musicDevice =
François Gaffiec005e562018-11-06 15:04:49 +01007830 mEngine->getOutputDevicesForAttributes(attributes_initializer(AUDIO_USAGE_MEDIA),
7831 nullptr, true /*fromCache*/).types();
François Gaffieaaac0fd2018-11-22 17:56:39 +01007832 auto &musicCurves = getVolumeCurves(AUDIO_STREAM_MUSIC);
jiabin9a3361e2019-10-01 09:38:30 -07007833 float musicVolDb = computeVolume(musicCurves,
7834 musicVolumeSrc,
7835 musicCurves.getVolumeIndex(musicDevice),
7836 musicDevice);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007837 float minVolDb = (musicVolDb > SONIFICATION_HEADSET_VOLUME_MIN_DB) ?
7838 musicVolDb : SONIFICATION_HEADSET_VOLUME_MIN_DB;
7839 if (volumeDb > minVolDb) {
7840 volumeDb = minVolDb;
7841 ALOGV("computeVolume limiting volume to %f musicVol %f", minVolDb, musicVolDb);
Eric Laurente552edb2014-03-10 17:42:56 -07007842 }
Eric Laurent7b6385c2021-05-12 17:55:36 +02007843 if (Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER
7844 && !Intersection(deviceTypes, {AUDIO_DEVICE_OUT_BLUETOOTH_A2DP,
7845 AUDIO_DEVICE_OUT_BLUETOOTH_A2DP_HEADPHONES}).empty()) {
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007846 // on A2DP, also ensure notification volume is not too low compared to media when
7847 // intended to be played
François Gaffie43c73442018-11-08 08:21:55 +01007848 if ((volumeDb > -96.0f) &&
François Gaffieaaac0fd2018-11-22 17:56:39 +01007849 (musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB > volumeDb)) {
jiabin9a3361e2019-10-01 09:38:30 -07007850 ALOGV("%s increasing volume for volume source=%d device=%s from %f to %f",
7851 __func__, volumeSource, dumpDeviceTypes(deviceTypes).c_str(), volumeDb,
François Gaffieaaac0fd2018-11-22 17:56:39 +01007852 musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB);
7853 volumeDb = musicVolDb - SONIFICATION_A2DP_MAX_MEDIA_DIFF_DB;
Jean-Michel Trivi00a20962016-05-25 19:11:01 -07007854 }
7855 }
jiabin9a3361e2019-10-01 09:38:30 -07007856 } else if ((Volume::getDeviceForVolume(deviceTypes) != AUDIO_DEVICE_OUT_SPEAKER) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01007857 (!(volumeSource == alarmVolumeSrc || volumeSource == ringVolumeSrc))) {
François Gaffie43c73442018-11-08 08:21:55 +01007858 volumeDb += SONIFICATION_HEADSET_VOLUME_FACTOR_DB;
Eric Laurente552edb2014-03-10 17:42:56 -07007859 }
7860 }
7861
François Gaffie43c73442018-11-08 08:21:55 +01007862 return volumeDb;
Eric Laurente552edb2014-03-10 17:42:56 -07007863}
7864
Eric Laurent3839bc02018-07-10 18:33:34 -07007865int AudioPolicyManager::rescaleVolumeIndex(int srcIndex,
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007866 VolumeSource fromVolumeSource,
7867 VolumeSource toVolumeSource)
Eric Laurent3839bc02018-07-10 18:33:34 -07007868{
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007869 if (fromVolumeSource == toVolumeSource) {
Eric Laurent3839bc02018-07-10 18:33:34 -07007870 return srcIndex;
7871 }
Francois Gaffie2ffdfce2019-03-12 11:26:42 +01007872 auto &srcCurves = getVolumeCurves(fromVolumeSource);
7873 auto &dstCurves = getVolumeCurves(toVolumeSource);
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007874 float minSrc = (float)srcCurves.getVolumeIndexMin();
7875 float maxSrc = (float)srcCurves.getVolumeIndexMax();
7876 float minDst = (float)dstCurves.getVolumeIndexMin();
7877 float maxDst = (float)dstCurves.getVolumeIndexMax();
Eric Laurent3839bc02018-07-10 18:33:34 -07007878
Revathi Uddarajufe0fb8b2017-07-27 17:05:37 +08007879 // preserve mute request or correct range
7880 if (srcIndex < minSrc) {
7881 if (srcIndex == 0) {
7882 return 0;
7883 }
7884 srcIndex = minSrc;
7885 } else if (srcIndex > maxSrc) {
7886 srcIndex = maxSrc;
7887 }
Eric Laurent3839bc02018-07-10 18:33:34 -07007888 return (int)(minDst + ((srcIndex - minSrc) * (maxDst - minDst)) / (maxSrc - minSrc));
7889}
7890
François Gaffieaaac0fd2018-11-22 17:56:39 +01007891status_t AudioPolicyManager::checkAndSetVolume(IVolumeCurves &curves,
7892 VolumeSource volumeSource,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007893 int index,
7894 const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007895 DeviceTypeSet deviceTypes,
Eric Laurentf5aa58d2019-02-22 18:20:11 -08007896 int delayMs,
7897 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007898{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007899 // do not change actual attributes volume if the attributes is muted
7900 if (outputDesc->isMuted(volumeSource)) {
7901 ALOGVV("%s: volume source %d muted count %d active=%d", __func__, volumeSource,
7902 outputDesc->getMuteCount(volumeSource), outputDesc->isActive(volumeSource));
Eric Laurente552edb2014-03-10 17:42:56 -07007903 return NO_ERROR;
7904 }
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007905 VolumeSource callVolSrc = toVolumeSource(AUDIO_STREAM_VOICE_CALL, false);
7906 VolumeSource btScoVolSrc = toVolumeSource(AUDIO_STREAM_BLUETOOTH_SCO, false);
7907 bool isVoiceVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (callVolSrc == volumeSource);
7908 bool isBtScoVolSrc = (volumeSource != VOLUME_SOURCE_NONE) && (btScoVolSrc == volumeSource);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007909
Eric Laurent2517af32020-11-25 15:31:27 +01007910 bool isScoRequested = isScoRequestedForComm();
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007911 bool isHAUsed = isHearingAidUsedForComm();
7912
Eric Laurente552edb2014-03-10 17:42:56 -07007913 // do not change in call volume if bluetooth is connected and vice versa
François Gaffieaaac0fd2018-11-22 17:56:39 +01007914 // if sco and call follow same curves, bypass forceUseForComm
7915 if ((callVolSrc != btScoVolSrc) &&
Eric Laurent2517af32020-11-25 15:31:27 +01007916 ((isVoiceVolSrc && isScoRequested) ||
Beibeif660a512023-02-28 17:00:34 +08007917 (isBtScoVolSrc && !(isScoRequested || isHAUsed))) &&
7918 !isSingleDeviceType(deviceTypes, AUDIO_DEVICE_OUT_TELEPHONY_TX)) {
Eric Laurent2517af32020-11-25 15:31:27 +01007919 ALOGV("%s cannot set volume group %d volume when is%srequested for comm", __func__,
Eric Laurent1a8b45f2022-04-13 16:01:47 +02007920 volumeSource, isScoRequested ? " " : " not ");
Eric Laurent571ef962020-07-24 11:43:48 -07007921 // Do not return an error here as AudioService will always set both voice call
7922 // and bluetooth SCO volumes due to stream aliasing.
7923 return NO_ERROR;
Eric Laurente552edb2014-03-10 17:42:56 -07007924 }
jiabin9a3361e2019-10-01 09:38:30 -07007925 if (deviceTypes.empty()) {
7926 deviceTypes = outputDesc->devices().types();
chenxin2080986da2023-07-17 11:45:21 +08007927 index = curves.getVolumeIndex(deviceTypes);
7928 ALOGD("%s if deviceTypes is change from none to device %s, need get index %d",
7929 __func__, dumpDeviceTypes(deviceTypes).c_str(), index);
Eric Laurentc75307b2015-03-17 15:29:32 -07007930 }
Eric Laurent275e8e92014-11-30 15:14:47 -08007931
Jean-Michel Trivi78f2b302022-04-15 18:18:41 +00007932 if (curves.getVolumeIndexMin() < 0 || curves.getVolumeIndexMax() < 0) {
7933 ALOGE("invalid volume index range");
7934 return BAD_VALUE;
7935 }
7936
jiabin9a3361e2019-10-01 09:38:30 -07007937 float volumeDb = computeVolume(curves, volumeSource, index, deviceTypes);
7938 if (outputDesc->isFixedVolume(deviceTypes) ||
Eric Laurent9698a4c2020-10-12 17:10:23 -07007939 // Force VoIP volume to max for bluetooth SCO device except if muted
7940 (index != 0 && (isVoiceVolSrc || isBtScoVolSrc) &&
jiabin9a3361e2019-10-01 09:38:30 -07007941 isSingleDeviceType(deviceTypes, audio_is_bluetooth_out_sco_device))) {
Eric Laurentffbc80f2015-03-18 18:30:19 -07007942 volumeDb = 0.0f;
Eric Laurent275e8e92014-11-30 15:14:47 -08007943 }
Francois Gaffie593634d2021-06-22 13:31:31 +02007944 const bool muted = (index == 0) && (volumeDb != 0.0f);
Eric Laurent31a428a2023-08-11 12:16:28 +02007945 outputDesc->setVolume(volumeDb, muted, volumeSource, curves.getStreamTypes(),
7946 deviceTypes, delayMs, force, isVoiceVolSrc);
Eric Laurentc75307b2015-03-17 15:29:32 -07007947
Eric Laurente8f2c0f2021-08-17 11:17:19 +02007948 if (outputDesc == mPrimaryOutput && (isVoiceVolSrc || isBtScoVolSrc)) {
Eric Laurente552edb2014-03-10 17:42:56 -07007949 float voiceVolume;
Eric Laurentfad001d2019-06-11 19:17:57 -07007950 // Force voice volume to max or mute for Bluetooth SCO as other attenuations are managed by the headset
François Gaffieaaac0fd2018-11-22 17:56:39 +01007951 if (isVoiceVolSrc) {
7952 voiceVolume = (float)index/(float)curves.getVolumeIndexMax();
Eric Laurente552edb2014-03-10 17:42:56 -07007953 } else {
Eric Laurentfad001d2019-06-11 19:17:57 -07007954 voiceVolume = index == 0 ? 0.0 : 1.0;
Eric Laurente552edb2014-03-10 17:42:56 -07007955 }
Eric Laurent18fba842016-03-31 14:41:26 -07007956 if (voiceVolume != mLastVoiceVolume) {
Eric Laurente552edb2014-03-10 17:42:56 -07007957 mpClientInterface->setVoiceVolume(voiceVolume, delayMs);
7958 mLastVoiceVolume = voiceVolume;
7959 }
7960 }
Eric Laurente552edb2014-03-10 17:42:56 -07007961 return NO_ERROR;
7962}
7963
Eric Laurentc75307b2015-03-17 15:29:32 -07007964void AudioPolicyManager::applyStreamVolumes(const sp<AudioOutputDescriptor>& outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07007965 const DeviceTypeSet& deviceTypes,
7966 int delayMs,
7967 bool force)
Eric Laurente552edb2014-03-10 17:42:56 -07007968{
jiabincd510522020-01-22 09:40:55 -08007969 ALOGVV("applyStreamVolumes() for device %s", dumpDeviceTypes(deviceTypes).c_str());
François Gaffieaaac0fd2018-11-22 17:56:39 +01007970 for (const auto &volumeGroup : mEngine->getVolumeGroups()) {
7971 auto &curves = getVolumeCurves(toVolumeSource(volumeGroup));
7972 checkAndSetVolume(curves, toVolumeSource(volumeGroup),
jiabin9a3361e2019-10-01 09:38:30 -07007973 curves.getVolumeIndex(deviceTypes),
7974 outputDesc, deviceTypes, delayMs, force);
Eric Laurente552edb2014-03-10 17:42:56 -07007975 }
7976}
7977
François Gaffiec005e562018-11-06 15:04:49 +01007978void AudioPolicyManager::setStrategyMute(product_strategy_t strategy,
7979 bool on,
7980 const sp<AudioOutputDescriptor>& outputDesc,
7981 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07007982 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07007983{
François Gaffieaaac0fd2018-11-22 17:56:39 +01007984 std::vector<VolumeSource> sourcesToMute;
7985 for (auto attributes: mEngine->getAllAttributesForProductStrategy(strategy)) {
7986 ALOGVV("%s() attributes %s, mute %d, output ID %d", __func__,
7987 toString(attributes).c_str(), on, outputDesc->getId());
Francois Gaffie4404ddb2021-02-04 17:03:38 +01007988 VolumeSource source = toVolumeSource(attributes, false);
7989 if ((source != VOLUME_SOURCE_NONE) &&
7990 (std::find(begin(sourcesToMute), end(sourcesToMute), source)
7991 == end(sourcesToMute))) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01007992 sourcesToMute.push_back(source);
7993 }
Eric Laurente552edb2014-03-10 17:42:56 -07007994 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01007995 for (auto source : sourcesToMute) {
jiabin9a3361e2019-10-01 09:38:30 -07007996 setVolumeSourceMute(source, on, outputDesc, delayMs, deviceTypes);
François Gaffieaaac0fd2018-11-22 17:56:39 +01007997 }
7998
Eric Laurente552edb2014-03-10 17:42:56 -07007999}
8000
François Gaffieaaac0fd2018-11-22 17:56:39 +01008001void AudioPolicyManager::setVolumeSourceMute(VolumeSource volumeSource,
8002 bool on,
8003 const sp<AudioOutputDescriptor>& outputDesc,
8004 int delayMs,
jiabin9a3361e2019-10-01 09:38:30 -07008005 DeviceTypeSet deviceTypes)
Eric Laurente552edb2014-03-10 17:42:56 -07008006{
jiabin9a3361e2019-10-01 09:38:30 -07008007 if (deviceTypes.empty()) {
8008 deviceTypes = outputDesc->devices().types();
Eric Laurente552edb2014-03-10 17:42:56 -07008009 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008010 auto &curves = getVolumeCurves(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008011 if (on) {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008012 if (!outputDesc->isMuted(volumeSource)) {
Eric Laurentf5aa58d2019-02-22 18:20:11 -08008013 if (curves.canBeMuted() &&
Francois Gaffie4404ddb2021-02-04 17:03:38 +01008014 (volumeSource != toVolumeSource(AUDIO_STREAM_ENFORCED_AUDIBLE, false) ||
François Gaffieaaac0fd2018-11-22 17:56:39 +01008015 (mEngine->getForceUse(AUDIO_POLICY_FORCE_FOR_SYSTEM) ==
8016 AUDIO_POLICY_FORCE_NONE))) {
jiabin9a3361e2019-10-01 09:38:30 -07008017 checkAndSetVolume(curves, volumeSource, 0, outputDesc, deviceTypes, delayMs);
Eric Laurente552edb2014-03-10 17:42:56 -07008018 }
8019 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008020 // increment mMuteCount after calling checkAndSetVolume() so that volume change is not
8021 // ignored
8022 outputDesc->incMuteCount(volumeSource);
Eric Laurente552edb2014-03-10 17:42:56 -07008023 } else {
François Gaffieaaac0fd2018-11-22 17:56:39 +01008024 if (!outputDesc->isMuted(volumeSource)) {
8025 ALOGV("%s unmuting non muted attributes!", __func__);
Eric Laurente552edb2014-03-10 17:42:56 -07008026 return;
8027 }
François Gaffieaaac0fd2018-11-22 17:56:39 +01008028 if (outputDesc->decMuteCount(volumeSource) == 0) {
8029 checkAndSetVolume(curves, volumeSource,
jiabin9a3361e2019-10-01 09:38:30 -07008030 curves.getVolumeIndex(deviceTypes),
Eric Laurentc75307b2015-03-17 15:29:32 -07008031 outputDesc,
jiabin9a3361e2019-10-01 09:38:30 -07008032 deviceTypes,
Eric Laurente552edb2014-03-10 17:42:56 -07008033 delayMs);
8034 }
8035 }
8036}
8037
François Gaffie53615e22015-03-19 09:24:12 +01008038bool AudioPolicyManager::isValidAttributes(const audio_attributes_t *paa)
8039{
François Gaffiec005e562018-11-06 15:04:49 +01008040 // has flags that map to a stream type?
Eric Laurente83b55d2014-11-14 10:06:21 -08008041 if ((paa->flags & (AUDIO_FLAG_AUDIBILITY_ENFORCED | AUDIO_FLAG_SCO | AUDIO_FLAG_BEACON)) != 0) {
8042 return true;
8043 }
8044
8045 // has known usage?
8046 switch (paa->usage) {
8047 case AUDIO_USAGE_UNKNOWN:
8048 case AUDIO_USAGE_MEDIA:
8049 case AUDIO_USAGE_VOICE_COMMUNICATION:
8050 case AUDIO_USAGE_VOICE_COMMUNICATION_SIGNALLING:
8051 case AUDIO_USAGE_ALARM:
8052 case AUDIO_USAGE_NOTIFICATION:
8053 case AUDIO_USAGE_NOTIFICATION_TELEPHONY_RINGTONE:
8054 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_REQUEST:
8055 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_INSTANT:
8056 case AUDIO_USAGE_NOTIFICATION_COMMUNICATION_DELAYED:
8057 case AUDIO_USAGE_NOTIFICATION_EVENT:
8058 case AUDIO_USAGE_ASSISTANCE_ACCESSIBILITY:
8059 case AUDIO_USAGE_ASSISTANCE_NAVIGATION_GUIDANCE:
8060 case AUDIO_USAGE_ASSISTANCE_SONIFICATION:
8061 case AUDIO_USAGE_GAME:
Eric Laurent275e8e92014-11-30 15:14:47 -08008062 case AUDIO_USAGE_VIRTUAL_SOURCE:
Jean-Michel Trivi36867762016-12-29 12:03:28 -08008063 case AUDIO_USAGE_ASSISTANT:
Eric Laurent21777f82019-12-06 18:12:06 -08008064 case AUDIO_USAGE_CALL_ASSISTANT:
Hayden Gomes524159d2019-12-23 14:41:47 -08008065 case AUDIO_USAGE_EMERGENCY:
8066 case AUDIO_USAGE_SAFETY:
8067 case AUDIO_USAGE_VEHICLE_STATUS:
8068 case AUDIO_USAGE_ANNOUNCEMENT:
Eric Laurente83b55d2014-11-14 10:06:21 -08008069 break;
8070 default:
8071 return false;
8072 }
8073 return true;
8074}
8075
François Gaffie2110e042015-03-24 08:41:51 +01008076audio_policy_forced_cfg_t AudioPolicyManager::getForceUse(audio_policy_force_use_t usage)
8077{
8078 return mEngine->getForceUse(usage);
8079}
8080
Eric Laurent96d1dda2022-03-14 17:14:19 +01008081bool AudioPolicyManager::isInCall() const {
François Gaffie2110e042015-03-24 08:41:51 +01008082 return isStateInCall(mEngine->getPhoneState());
8083}
8084
Eric Laurent96d1dda2022-03-14 17:14:19 +01008085bool AudioPolicyManager::isStateInCall(int state) const {
François Gaffie2110e042015-03-24 08:41:51 +01008086 return is_state_in_call(state);
8087}
8088
Eric Laurentf9cccec2022-11-16 19:12:00 +01008089bool AudioPolicyManager::isCallAudioAccessible() const {
Eric Laurent74b71512019-11-06 17:21:57 -08008090 audio_mode_t mode = mEngine->getPhoneState();
8091 return (mode == AUDIO_MODE_IN_CALL)
Eric Laurentc8c4f1f2021-11-09 11:51:34 +01008092 || (mode == AUDIO_MODE_CALL_SCREEN)
8093 || (mode == AUDIO_MODE_CALL_REDIRECT);
Eric Laurent74b71512019-11-06 17:21:57 -08008094}
8095
Eric Laurentf9cccec2022-11-16 19:12:00 +01008096bool AudioPolicyManager::isInCallOrScreening() const {
8097 audio_mode_t mode = mEngine->getPhoneState();
8098 return isStateInCall(mode) || mode == AUDIO_MODE_CALL_SCREEN;
8099}
8100
Eric Laurentd60560a2015-04-10 11:31:20 -07008101void AudioPolicyManager::cleanUpForDevice(const sp<DeviceDescriptor>& deviceDesc)
8102{
8103 for (ssize_t i = (ssize_t)mAudioSources.size() - 1; i >= 0; i--) {
Eric Laurent3e6c7e12018-07-27 17:09:23 -07008104 sp<SourceClientDescriptor> sourceDesc = mAudioSources.valueAt(i);
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008105 if (sourceDesc->isConnected() && (sourceDesc->srcDevice()->equals(deviceDesc) ||
Francois Gaffie51c9ccd2020-10-14 18:02:07 +02008106 sourceDesc->sinkDevice()->equals(deviceDesc))
8107 && !isCallRxAudioSource(sourceDesc)) {
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008108 disconnectAudioSource(sourceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008109 }
8110 }
8111
8112 for (ssize_t i = (ssize_t)mAudioPatches.size() - 1; i >= 0; i--) {
8113 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(i);
8114 bool release = false;
8115 for (size_t j = 0; j < patchDesc->mPatch.num_sources && !release; j++) {
8116 const struct audio_port_config *source = &patchDesc->mPatch.sources[j];
8117 if (source->type == AUDIO_PORT_TYPE_DEVICE &&
8118 source->ext.device.type == deviceDesc->type()) {
8119 release = true;
8120 }
8121 }
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008122 const char *address = deviceDesc->address().c_str();
Eric Laurentd60560a2015-04-10 11:31:20 -07008123 for (size_t j = 0; j < patchDesc->mPatch.num_sinks && !release; j++) {
8124 const struct audio_port_config *sink = &patchDesc->mPatch.sinks[j];
8125 if (sink->type == AUDIO_PORT_TYPE_DEVICE &&
Francois Gaffiea0e5c992020-09-29 16:05:07 +02008126 sink->ext.device.type == deviceDesc->type() &&
8127 (strnlen(address, AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0
8128 || strncmp(sink->ext.device.address, address,
8129 AUDIO_DEVICE_MAX_ADDRESS_LEN) == 0)) {
Eric Laurentd60560a2015-04-10 11:31:20 -07008130 release = true;
8131 }
8132 }
8133 if (release) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008134 ALOGV("%s releasing patch %u", __FUNCTION__, patchDesc->getHandle());
8135 releaseAudioPatch(patchDesc->getHandle(), patchDesc->getUid());
Eric Laurentd60560a2015-04-10 11:31:20 -07008136 }
8137 }
Francois Gaffie716e1432019-01-14 16:58:59 +01008138
Francois Gaffieba2cf0f2018-12-12 16:40:25 +01008139 mInputs.clearSessionRoutesForDevice(deviceDesc);
8140
Francois Gaffie716e1432019-01-14 16:58:59 +01008141 mHwModules.cleanUpForDevice(deviceDesc);
Eric Laurentd60560a2015-04-10 11:31:20 -07008142}
8143
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008144void AudioPolicyManager::modifySurroundFormats(
8145 const sp<DeviceDescriptor>& devDesc, FormatVector *formatsPtr) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008146 std::unordered_set<audio_format_t> enforcedSurround(
8147 devDesc->encodedFormats().begin(), devDesc->encodedFormats().end());
Mikhail Naganov100f0122018-11-29 11:22:16 -08008148 std::unordered_set<audio_format_t> allSurround; // A flat set of all known surround formats
Mikhail Naganov68e3f642023-04-28 13:06:32 -07008149 for (const auto& pair : mConfig->getSurroundFormats()) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008150 allSurround.insert(pair.first);
8151 for (const auto& subformat : pair.second) allSurround.insert(subformat);
8152 }
Phil Burk09bc4612016-02-24 15:58:15 -08008153
8154 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8155 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
Phil Burk0709b0a2016-03-31 12:54:57 -07008156 ALOGD("%s: forced use = %d", __FUNCTION__, forceUse);
Mikhail Naganov100f0122018-11-29 11:22:16 -08008157 // This is the resulting set of formats depending on the surround mode:
8158 // 'all surround' = allSurround
8159 // 'enforced surround' = enforcedSurround [may include IEC69137 which isn't raw surround fmt]
8160 // 'non-surround' = not in 'all surround' and not in 'enforced surround'
8161 // 'manual surround' = mManualSurroundFormats
8162 // AUTO: formats v 'enforced surround'
8163 // ALWAYS: formats v 'all surround' v 'enforced surround'
8164 // NEVER: formats ^ 'non-surround'
8165 // MANUAL: formats ^ ('non-surround' v 'manual surround' v (IEC69137 ^ 'enforced surround'))
Phil Burk09bc4612016-02-24 15:58:15 -08008166
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008167 std::unordered_set<audio_format_t> formatSet;
8168 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL
8169 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008170 // formatSet is (formats ^ 'non-surround')
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008171 for (auto formatIter = formatsPtr->begin(); formatIter != formatsPtr->end(); ++formatIter) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008172 if (allSurround.count(*formatIter) == 0 && enforcedSurround.count(*formatIter) == 0) {
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008173 formatSet.insert(*formatIter);
8174 }
8175 }
8176 } else {
8177 formatSet.insert(formatsPtr->begin(), formatsPtr->end());
8178 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008179 formatsPtr->clear(); // Re-filled from the formatSet at the end.
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008180
jiabin81772902018-04-02 17:52:27 -07008181 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Mikhail Naganov100f0122018-11-29 11:22:16 -08008182 formatSet.insert(mManualSurroundFormats.begin(), mManualSurroundFormats.end());
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008183 // Enable IEC61937 when in MANUAL mode if it's enforced for this device.
8184 if (enforcedSurround.count(AUDIO_FORMAT_IEC61937) != 0) {
8185 formatSet.insert(AUDIO_FORMAT_IEC61937);
Phil Burk09bc4612016-02-24 15:58:15 -08008186 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008187 } else if (forceUse != AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) { // AUTO or ALWAYS
8188 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS) {
8189 formatSet.insert(allSurround.begin(), allSurround.end());
Phil Burk07ac1142016-03-25 13:39:29 -07008190 }
Mikhail Naganov100f0122018-11-29 11:22:16 -08008191 formatSet.insert(enforcedSurround.begin(), enforcedSurround.end());
Phil Burk09bc4612016-02-24 15:58:15 -08008192 }
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008193 for (const auto& format : formatSet) {
jiabin06e4bab2019-07-29 10:13:34 -07008194 formatsPtr->push_back(format);
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008195 }
Phil Burk0709b0a2016-03-31 12:54:57 -07008196}
8197
jiabin06e4bab2019-07-29 10:13:34 -07008198void AudioPolicyManager::modifySurroundChannelMasks(ChannelMaskSet *channelMasksPtr) {
8199 ChannelMaskSet &channelMasks = *channelMasksPtr;
Phil Burk0709b0a2016-03-31 12:54:57 -07008200 audio_policy_forced_cfg_t forceUse = mEngine->getForceUse(
8201 AUDIO_POLICY_FORCE_FOR_ENCODED_SURROUND);
8202
8203 // If NEVER, then remove support for channelMasks > stereo.
8204 if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_NEVER) {
jiabin06e4bab2019-07-29 10:13:34 -07008205 for (auto it = channelMasks.begin(); it != channelMasks.end();) {
8206 audio_channel_mask_t channelMask = *it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008207 if (channelMask & ~AUDIO_CHANNEL_OUT_STEREO) {
Eric Laurentfecbceb2021-02-09 14:46:43 +01008208 ALOGV("%s: force NEVER, so remove channelMask 0x%08x", __FUNCTION__, channelMask);
jiabin06e4bab2019-07-29 10:13:34 -07008209 it = channelMasks.erase(it);
Phil Burk0709b0a2016-03-31 12:54:57 -07008210 } else {
jiabin06e4bab2019-07-29 10:13:34 -07008211 ++it;
Phil Burk0709b0a2016-03-31 12:54:57 -07008212 }
8213 }
jiabin81772902018-04-02 17:52:27 -07008214 // If ALWAYS or MANUAL, then make sure we at least support 5.1
8215 } else if (forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_ALWAYS
8216 || forceUse == AUDIO_POLICY_FORCE_ENCODED_SURROUND_MANUAL) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008217 bool supports5dot1 = false;
8218 // Are there any channel masks that can be considered "surround"?
Mikhail Naganovcf84e592017-12-07 11:25:11 -08008219 for (audio_channel_mask_t channelMask : channelMasks) {
Phil Burk0709b0a2016-03-31 12:54:57 -07008220 if ((channelMask & AUDIO_CHANNEL_OUT_5POINT1) == AUDIO_CHANNEL_OUT_5POINT1) {
8221 supports5dot1 = true;
8222 break;
8223 }
8224 }
8225 // If not then add 5.1 support.
8226 if (!supports5dot1) {
jiabin06e4bab2019-07-29 10:13:34 -07008227 channelMasks.insert(AUDIO_CHANNEL_OUT_5POINT1);
Eric Laurentfecbceb2021-02-09 14:46:43 +01008228 ALOGV("%s: force MANUAL or ALWAYS, so adding channelMask for 5.1 surround", __func__);
Phil Burk0709b0a2016-03-31 12:54:57 -07008229 }
Phil Burk09bc4612016-02-24 15:58:15 -08008230 }
8231}
8232
Mikhail Naganovd5e18052018-11-30 14:55:45 -08008233void AudioPolicyManager::updateAudioProfiles(const sp<DeviceDescriptor>& devDesc,
Phil Burk00eeb322016-03-31 12:41:00 -07008234 audio_io_handle_t ioHandle,
jiabin12537fc2023-10-12 17:56:08 +00008235 const sp<IOProfile>& profile) {
8236 if (!profile->hasDynamicAudioProfile()) {
8237 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008238 }
François Gaffie112b0af2015-11-19 16:13:25 +01008239
jiabin12537fc2023-10-12 17:56:08 +00008240 audio_port_v7 devicePort;
8241 devDesc->toAudioPort(&devicePort);
François Gaffie112b0af2015-11-19 16:13:25 +01008242
jiabin12537fc2023-10-12 17:56:08 +00008243 audio_port_v7 mixPort;
8244 profile->toAudioPort(&mixPort);
8245 mixPort.ext.mix.handle = ioHandle;
8246
8247 status_t status = mpClientInterface->getAudioMixPort(&devicePort, &mixPort);
8248 if (status != NO_ERROR) {
8249 ALOGE("%s failed to query the attributes of the mix port", __func__);
8250 return;
François Gaffie112b0af2015-11-19 16:13:25 +01008251 }
jiabin12537fc2023-10-12 17:56:08 +00008252
8253 std::set<audio_format_t> supportedFormats;
8254 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8255 supportedFormats.insert(mixPort.audio_profiles[i].format);
8256 }
8257 FormatVector formats(supportedFormats.begin(), supportedFormats.end());
8258 mReportedFormatsMap[devDesc] = formats;
8259
8260 if (devDesc->type() == AUDIO_DEVICE_OUT_HDMI ||
8261 isDeviceOfModule(devDesc,AUDIO_HARDWARE_MODULE_ID_MSD)) {
8262 modifySurroundFormats(devDesc, &formats);
8263 size_t modifiedNumProfiles = 0;
8264 for (size_t i = 0; i < mixPort.num_audio_profiles; ++i) {
8265 if (std::find(formats.begin(), formats.end(), mixPort.audio_profiles[i].format) ==
8266 formats.end()) {
8267 // Skip the format that is not present after modifying surround formats.
8268 continue;
8269 }
8270 memcpy(&mixPort.audio_profiles[modifiedNumProfiles], &mixPort.audio_profiles[i],
8271 sizeof(struct audio_profile));
8272 ChannelMaskSet channels(mixPort.audio_profiles[modifiedNumProfiles].channel_masks,
8273 mixPort.audio_profiles[modifiedNumProfiles].channel_masks +
8274 mixPort.audio_profiles[modifiedNumProfiles].num_channel_masks);
8275 modifySurroundChannelMasks(&channels);
8276 std::copy(channels.begin(), channels.end(),
8277 std::begin(mixPort.audio_profiles[modifiedNumProfiles].channel_masks));
8278 mixPort.audio_profiles[modifiedNumProfiles++].num_channel_masks = channels.size();
8279 }
8280 mixPort.num_audio_profiles = modifiedNumProfiles;
8281 }
8282 profile->importAudioPort(mixPort);
François Gaffie112b0af2015-11-19 16:13:25 +01008283}
Eric Laurentd60560a2015-04-10 11:31:20 -07008284
Mikhail Naganovdc769682018-05-04 15:34:08 -07008285status_t AudioPolicyManager::installPatch(const char *caller,
8286 audio_patch_handle_t *patchHandle,
8287 AudioIODescriptorInterface *ioDescriptor,
8288 const struct audio_patch *patch,
8289 int delayMs)
8290{
8291 ssize_t index = mAudioPatches.indexOfKey(
8292 patchHandle && *patchHandle != AUDIO_PATCH_HANDLE_NONE ?
8293 *patchHandle : ioDescriptor->getPatchHandle());
8294 sp<AudioPatch> patchDesc;
8295 status_t status = installPatch(
8296 caller, index, patchHandle, patch, delayMs, mUidCached, &patchDesc);
8297 if (status == NO_ERROR) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008298 ioDescriptor->setPatchHandle(patchDesc->getHandle());
Mikhail Naganovdc769682018-05-04 15:34:08 -07008299 }
8300 return status;
8301}
8302
8303status_t AudioPolicyManager::installPatch(const char *caller,
8304 ssize_t index,
8305 audio_patch_handle_t *patchHandle,
8306 const struct audio_patch *patch,
8307 int delayMs,
8308 uid_t uid,
8309 sp<AudioPatch> *patchDescPtr)
8310{
8311 sp<AudioPatch> patchDesc;
8312 audio_patch_handle_t afPatchHandle = AUDIO_PATCH_HANDLE_NONE;
8313 if (index >= 0) {
8314 patchDesc = mAudioPatches.valueAt(index);
François Gaffieafd4cea2019-11-18 15:50:22 +01008315 afPatchHandle = patchDesc->getAfHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008316 }
8317
8318 status_t status = mpClientInterface->createAudioPatch(patch, &afPatchHandle, delayMs);
8319 ALOGV("%s() AF::createAudioPatch returned %d patchHandle %d num_sources %d num_sinks %d",
8320 caller, status, afPatchHandle, patch->num_sources, patch->num_sinks);
8321 if (status == NO_ERROR) {
8322 if (index < 0) {
8323 patchDesc = new AudioPatch(patch, uid);
François Gaffieafd4cea2019-11-18 15:50:22 +01008324 addAudioPatch(patchDesc->getHandle(), patchDesc);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008325 } else {
8326 patchDesc->mPatch = *patch;
8327 }
François Gaffieafd4cea2019-11-18 15:50:22 +01008328 patchDesc->setAfHandle(afPatchHandle);
Mikhail Naganovdc769682018-05-04 15:34:08 -07008329 if (patchHandle) {
François Gaffieafd4cea2019-11-18 15:50:22 +01008330 *patchHandle = patchDesc->getHandle();
Mikhail Naganovdc769682018-05-04 15:34:08 -07008331 }
8332 nextAudioPortGeneration();
8333 mpClientInterface->onAudioPatchListUpdate();
8334 }
8335 if (patchDescPtr) *patchDescPtr = patchDesc;
8336 return status;
8337}
8338
jiabinbce0c1d2020-10-05 11:20:18 -07008339bool AudioPolicyManager::areAllActiveTracksRerouted(const sp<SwAudioOutputDescriptor>& output)
8340{
8341 const TrackClientVector activeClients = output->getActiveClients();
8342 if (activeClients.empty()) {
8343 return true;
8344 }
8345 ssize_t index = mAudioPatches.indexOfKey(output->getPatchHandle());
8346 if (index < 0) {
8347 ALOGE("%s, no audio patch found while there are active clients on output %d",
8348 __func__, output->getId());
8349 return false;
8350 }
8351 sp<AudioPatch> patchDesc = mAudioPatches.valueAt(index);
8352 DeviceVector routedDevices;
8353 for (int i = 0; i < patchDesc->mPatch.num_sinks; ++i) {
8354 sp<DeviceDescriptor> device = mAvailableOutputDevices.getDeviceFromId(
8355 patchDesc->mPatch.sinks[i].id);
8356 if (device == nullptr) {
8357 ALOGE("%s, no audio device found with id(%d)",
8358 __func__, patchDesc->mPatch.sinks[i].id);
8359 return false;
8360 }
8361 routedDevices.add(device);
8362 }
8363 for (const auto& client : activeClients) {
jiabin49256852022-03-09 11:21:35 -08008364 if (client->isInvalid()) {
8365 // No need to take care about invalidated clients.
8366 continue;
8367 }
jiabinbce0c1d2020-10-05 11:20:18 -07008368 sp<DeviceDescriptor> preferredDevice =
8369 mAvailableOutputDevices.getDeviceFromId(client->preferredDeviceId());
8370 if (mEngine->getOutputDevicesForAttributes(
8371 client->attributes(), preferredDevice, false) == routedDevices) {
8372 return false;
8373 }
8374 }
8375 return true;
8376}
8377
8378sp<SwAudioOutputDescriptor> AudioPolicyManager::openOutputWithProfileAndDevice(
Eric Laurentb4f42a92022-01-17 17:37:31 +01008379 const sp<IOProfile>& profile, const DeviceVector& devices,
jiabina84c3d32022-12-02 18:59:55 +00008380 const audio_config_base_t *mixerConfig, const audio_config_t *halConfig,
8381 audio_output_flags_t flags)
jiabinbce0c1d2020-10-05 11:20:18 -07008382{
8383 for (const auto& device : devices) {
8384 // TODO: This should be checking if the profile supports the device combo.
8385 if (!profile->supportsDevice(device)) {
jiabina84c3d32022-12-02 18:59:55 +00008386 ALOGE("%s profile(%s) doesn't support device %#x", __func__, profile->getName().c_str(),
8387 device->type());
jiabinbce0c1d2020-10-05 11:20:18 -07008388 return nullptr;
8389 }
8390 }
8391 sp<SwAudioOutputDescriptor> desc = new SwAudioOutputDescriptor(profile, mpClientInterface);
8392 audio_io_handle_t output = AUDIO_IO_HANDLE_NONE;
jiabina84c3d32022-12-02 18:59:55 +00008393 status_t status = desc->open(halConfig, mixerConfig, devices,
8394 AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008395 if (status != NO_ERROR) {
jiabina84c3d32022-12-02 18:59:55 +00008396 ALOGE("%s failed to open output %d", __func__, status);
jiabinbce0c1d2020-10-05 11:20:18 -07008397 return nullptr;
8398 }
jiabin14b50cc2023-12-13 19:01:52 +00008399 if ((flags & AUDIO_OUTPUT_FLAG_BIT_PERFECT) == AUDIO_OUTPUT_FLAG_BIT_PERFECT) {
8400 auto portConfig = desc->getConfig();
8401 for (const auto& device : devices) {
8402 device->setPreferredConfig(&portConfig);
8403 }
8404 }
jiabinbce0c1d2020-10-05 11:20:18 -07008405
8406 // Here is where the out_set_parameters() for card & device gets called
8407 sp<DeviceDescriptor> device = devices.getDeviceForOpening();
8408 const audio_devices_t deviceType = device->type();
8409 const String8 &address = String8(device->address().c_str());
Tomasz Wasilczykfd9ffd12023-08-14 17:56:22 +00008410 if (!address.empty()) {
jiabinbce0c1d2020-10-05 11:20:18 -07008411 char *param = audio_device_address_to_parameter(deviceType, address.c_str());
8412 mpClientInterface->setParameters(output, String8(param));
8413 free(param);
8414 }
jiabin12537fc2023-10-12 17:56:08 +00008415 updateAudioProfiles(device, output, profile);
jiabinbce0c1d2020-10-05 11:20:18 -07008416 if (!profile->hasValidAudioProfile()) {
8417 ALOGW("%s() missing param", __func__);
8418 desc->close();
8419 return nullptr;
jiabina84c3d32022-12-02 18:59:55 +00008420 } else if (profile->hasDynamicAudioProfile() && halConfig == nullptr) {
8421 // Reopen the output with the best audio profile picked by APM when the profile supports
8422 // dynamic audio profile and the hal config is not specified.
jiabinbce0c1d2020-10-05 11:20:18 -07008423 desc->close();
8424 output = AUDIO_IO_HANDLE_NONE;
8425 audio_config_t config = AUDIO_CONFIG_INITIALIZER;
8426 profile->pickAudioProfile(
8427 config.sample_rate, config.channel_mask, config.format);
8428 config.offload_info.sample_rate = config.sample_rate;
8429 config.offload_info.channel_mask = config.channel_mask;
8430 config.offload_info.format = config.format;
8431
jiabina84c3d32022-12-02 18:59:55 +00008432 status = desc->open(&config, mixerConfig, devices, AUDIO_STREAM_DEFAULT, flags, &output);
jiabinbce0c1d2020-10-05 11:20:18 -07008433 if (status != NO_ERROR) {
8434 return nullptr;
8435 }
8436 }
8437
8438 addOutput(output, desc);
Eric Laurentb4f42a92022-01-17 17:37:31 +01008439
baek.kim -61c20122022-07-27 10:05:32 +00008440 sp<DeviceDescriptor> speaker = mAvailableOutputDevices.getDevice(
8441 AUDIO_DEVICE_OUT_SPEAKER, String8(""), AUDIO_FORMAT_DEFAULT);
8442
jiabinbce0c1d2020-10-05 11:20:18 -07008443 if (audio_is_remote_submix_device(deviceType) && address != "0") {
8444 sp<AudioPolicyMix> policyMix;
8445 if (mPolicyMixes.getAudioPolicyMix(deviceType, address, policyMix) == NO_ERROR) {
8446 policyMix->setOutput(desc);
8447 desc->mPolicyMix = policyMix;
8448 } else {
8449 ALOGW("checkOutputsForDevice() cannot find policy for address %s",
Tomasz Wasilczyk833345b2023-08-15 20:59:35 +00008450 address.c_str());
jiabinbce0c1d2020-10-05 11:20:18 -07008451 }
8452
baek.kim -61c20122022-07-27 10:05:32 +00008453 } else if (hasPrimaryOutput() && speaker != nullptr
8454 && mPrimaryOutput->supportsDevice(speaker) && !desc->supportsDevice(speaker)
Eric Laurentb4f42a92022-01-17 17:37:31 +01008455 && ((desc->mFlags & AUDIO_OUTPUT_FLAG_DIRECT) == 0)) {
8456 // no duplicated output for:
8457 // - direct outputs
8458 // - outputs used by dynamic policy mixes
baek.kim -61c20122022-07-27 10:05:32 +00008459 // - outputs that supports SPEAKER while the primary output does not.
jiabinbce0c1d2020-10-05 11:20:18 -07008460 audio_io_handle_t duplicatedOutput = AUDIO_IO_HANDLE_NONE;
8461
8462 //TODO: configure audio effect output stage here
8463
8464 // open a duplicating output thread for the new output and the primary output
8465 sp<SwAudioOutputDescriptor> dupOutputDesc =
8466 new SwAudioOutputDescriptor(nullptr, mpClientInterface);
8467 status = dupOutputDesc->openDuplicating(mPrimaryOutput, desc, &duplicatedOutput);
8468 if (status == NO_ERROR) {
8469 // add duplicated output descriptor
8470 addOutput(duplicatedOutput, dupOutputDesc);
8471 } else {
8472 ALOGW("checkOutputsForDevice() could not open dup output for %d and %d",
8473 mPrimaryOutput->mIoHandle, output);
8474 desc->close();
8475 removeOutput(output);
8476 nextAudioPortGeneration();
8477 return nullptr;
8478 }
8479 }
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008480 if (mPrimaryOutput == nullptr && profile->getFlags() & AUDIO_OUTPUT_FLAG_PRIMARY) {
8481 ALOGV("%s(): re-assigning mPrimaryOutput", __func__);
8482 mPrimaryOutput = desc;
François Gaffiedb1755b2023-09-01 11:50:35 +02008483 mPrimaryModuleHandle = mPrimaryOutput->getModuleHandle();
Francois Gaffiebce7cd42020-10-14 16:13:20 +02008484 }
jiabinbce0c1d2020-10-05 11:20:18 -07008485 return desc;
8486}
8487
jiabinf1c73972022-04-14 16:28:52 -07008488status_t AudioPolicyManager::getDevicesForAttributes(
8489 const audio_attributes_t &attr, DeviceVector &devices, bool forVolume) {
8490 // Devices are determined in the following precedence:
8491 //
8492 // 1) Devices associated with a dynamic policy matching the attributes. This is often
8493 // a remote submix from MIX_ROUTE_FLAG_LOOP_BACK.
8494 //
8495 // If no such dynamic policy then
8496 // 2) Devices containing an active client using setPreferredDevice
8497 // with same strategy as the attributes.
8498 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8499 //
8500 // If no corresponding active client with setPreferredDevice then
8501 // 3) Devices associated with the strategy determined by the attributes
8502 // (from the default Engine::getOutputDevicesForAttributes() implementation).
8503 //
8504 // See related getOutputForAttrInt().
8505
8506 // check dynamic policies but only for primary descriptors (secondary not used for audible
8507 // audio routing, only used for duplication for playback capture)
8508 sp<AudioPolicyMix> policyMix;
Oscar Azucena873d10f2023-01-12 18:34:42 -08008509 bool unneededUsePrimaryOutputFromPolicyMixes = false;
jiabinf1c73972022-04-14 16:28:52 -07008510 status_t status = mPolicyMixes.getOutputForAttr(attr, AUDIO_CONFIG_BASE_INITIALIZER,
Oscar Azucena873d10f2023-01-12 18:34:42 -08008511 0 /*uid unknown here*/, AUDIO_SESSION_NONE, AUDIO_OUTPUT_FLAG_NONE,
8512 mAvailableOutputDevices, nullptr /* requestedDevice */, policyMix,
8513 nullptr /* secondaryMixes */, unneededUsePrimaryOutputFromPolicyMixes);
jiabinf1c73972022-04-14 16:28:52 -07008514 if (status != OK) {
8515 return status;
8516 }
8517
8518 if (policyMix != nullptr && policyMix->getOutput() != nullptr &&
8519 // For volume control, skip LOOPBACK mixes which use AUDIO_DEVICE_OUT_REMOTE_SUBMIX
8520 // as they are unaffected by device/stream volume
8521 // (per SwAudioOutputDescriptor::isFixedVolume()).
8522 (!forVolume || policyMix->mDeviceType != AUDIO_DEVICE_OUT_REMOTE_SUBMIX)
8523 ) {
8524 sp<DeviceDescriptor> deviceDesc = mAvailableOutputDevices.getDevice(
8525 policyMix->mDeviceType, policyMix->mDeviceAddress, AUDIO_FORMAT_DEFAULT);
8526 devices.add(deviceDesc);
8527 } else {
8528 // The default Engine::getOutputDevicesForAttributes() uses findPreferredDevice()
8529 // which selects setPreferredDevice if active. This means forVolume call
8530 // will take an active setPreferredDevice, if such exists.
8531
8532 devices = mEngine->getOutputDevicesForAttributes(
8533 attr, nullptr /* preferredDevice */, false /* fromCache */);
8534 }
8535
8536 if (forVolume) {
8537 // We alias the device AUDIO_DEVICE_OUT_SPEAKER_SAFE to AUDIO_DEVICE_OUT_SPEAKER
8538 // for single volume control in AudioService (such relationship should exist if
8539 // SPEAKER_SAFE is present).
8540 //
8541 // (This is unrelated to a different device grouping as Volume::getDeviceCategory)
8542 DeviceVector speakerSafeDevices =
8543 devices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER_SAFE);
8544 if (!speakerSafeDevices.isEmpty()) {
8545 devices.merge(mAvailableOutputDevices.getDevicesFromType(AUDIO_DEVICE_OUT_SPEAKER));
8546 devices.remove(speakerSafeDevices);
8547 }
8548 }
8549
8550 return NO_ERROR;
8551}
8552
8553status_t AudioPolicyManager::getProfilesForDevices(const DeviceVector& devices,
8554 AudioProfileVector& audioProfiles,
8555 uint32_t flags,
8556 bool isInput) {
8557 for (const auto& hwModule : mHwModules) {
8558 // the MSD module checks for different conditions
8559 if (strcmp(hwModule->getName(), AUDIO_HARDWARE_MODULE_ID_MSD) == 0) {
8560 continue;
8561 }
8562 IOProfileCollection ioProfiles = isInput ? hwModule->getInputProfiles()
8563 : hwModule->getOutputProfiles();
8564 for (const auto& profile : ioProfiles) {
8565 if (!profile->areAllDevicesSupported(devices) ||
8566 !profile->isCompatibleProfileForFlags(
8567 flags, false /*exactMatchRequiredForInputFlags*/)) {
8568 continue;
8569 }
8570 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8571 }
8572 }
8573
8574 if (!isInput) {
8575 // add the direct profiles from MSD if present and has audio patches to all the output(s)
8576 const auto &msdModule = mHwModules.getModuleFromName(AUDIO_HARDWARE_MODULE_ID_MSD);
8577 if (msdModule != nullptr) {
8578 if (msdHasPatchesToAllDevices(devices.toTypeAddrVector())) {
8579 ALOGV("%s: MSD audio patches set to all output devices.", __func__);
8580 for (const auto &profile: msdModule->getOutputProfiles()) {
8581 if (!profile->asAudioPort()->isDirectOutput()) {
8582 continue;
8583 }
8584 audioProfiles.addAllValidProfiles(profile->asAudioPort()->getAudioProfiles());
8585 }
8586 } else {
8587 ALOGV("%s: MSD audio patches NOT set to all output devices.", __func__);
8588 }
8589 }
8590 }
8591
8592 return NO_ERROR;
8593}
8594
jiabin3ff8d7d2022-12-13 06:27:44 +00008595sp<SwAudioOutputDescriptor> AudioPolicyManager::reopenOutput(sp<SwAudioOutputDescriptor> outputDesc,
8596 const audio_config_t *config,
8597 audio_output_flags_t flags,
8598 const char* caller) {
jiabina84c3d32022-12-02 18:59:55 +00008599 closeOutput(outputDesc->mIoHandle);
8600 sp<SwAudioOutputDescriptor> preferredOutput = openOutputWithProfileAndDevice(
8601 outputDesc->mProfile, outputDesc->devices(), nullptr /*mixerConfig*/, config, flags);
8602 if (preferredOutput == nullptr) {
8603 ALOGE("%s failed to reopen output device=%d, caller=%s",
8604 __func__, outputDesc->devices()[0]->getId(), caller);
jiabina84c3d32022-12-02 18:59:55 +00008605 }
jiabin3ff8d7d2022-12-13 06:27:44 +00008606 return preferredOutput;
8607}
8608
8609void AudioPolicyManager::reopenOutputsWithDevices(
8610 const std::map<audio_io_handle_t, DeviceVector> &outputsToReopen) {
8611 for (const auto& [output, devices] : outputsToReopen) {
8612 sp<SwAudioOutputDescriptor> desc = mOutputs.valueFor(output);
8613 closeOutput(output);
8614 openOutputWithProfileAndDevice(desc->mProfile, devices);
8615 }
jiabina84c3d32022-12-02 18:59:55 +00008616}
8617
jiabinc44b3462022-12-08 12:52:31 -08008618PortHandleVector AudioPolicyManager::getClientsForStream(
8619 audio_stream_type_t streamType) const {
8620 PortHandleVector clients;
8621 for (size_t i = 0; i < mOutputs.size(); ++i) {
8622 PortHandleVector clientsForStream = mOutputs.valueAt(i)->getClientsForStream(streamType);
8623 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8624 }
8625 return clients;
8626}
8627
8628void AudioPolicyManager::invalidateStreams(StreamTypeVector streams) const {
8629 PortHandleVector clients;
8630 for (auto stream : streams) {
8631 PortHandleVector clientsForStream = getClientsForStream(stream);
8632 clients.insert(clients.end(), clientsForStream.begin(), clientsForStream.end());
8633 }
8634 mpClientInterface->invalidateTracks(clients);
8635}
8636
Mikhail Naganov1b2a7942017-12-08 10:18:09 -08008637} // namespace android